text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { notEmailFriendly } from "html-entities-not-email-friendly"; import { allNamedEntities } from "all-named-html-entities"; import { expander } from "string-range-expander"; import { convertOne } from "string-apostrophes"; import he from "he"; import { left, right, // leftStopAtRawNbsp, // rightStopAtRawNbsp, leftStopAtNewLines, rightStopAtNewLines, } from "string-left-right"; import { Ranges } from "ranges-push"; import { doConvertEntities, isUppercaseLetter, isLowercaseLetter, rightSingleQuote, rightDoubleQuote, punctuationChars, leftSingleQuote, leftDoubleQuote, widowRegexTest, ApplicableOpts, EndOfLineVal, rawEllipsis, isLetter, isNumber, rawMDash, rawNDash, isQuote, rawNbsp, State, Opts, } from "./util"; // This function gets from-to indexes and numeric character code. // It is used by processOutside() which skips already processed ranges and // iterates over the remaining indexes. Also, it is used to validate the // encode entities - those are decoded and ran through this function as well. // That's why we need this fancy "y" - "up to" index and we can't make it // using simple "i + 1" - the "character" might be actually an encoded // chunk of characters. We separate the location of character(s) // (which could be expressed as string.slice(i, y)) and the value it // represents ("charcode"). function processCharacter( str: string, opts: Opts, rangesArr: Ranges, i: number, y: number, offsetBy: (amount: number) => void, brClosingBracketIndexesArr: number[], state: State, applicableOpts: ApplicableOpts, endOfLineVal: EndOfLineVal ): void { const len = str.length; console.log( `\u001b[${36}m${`===============================`}\u001b[${39}m \u001b[${35}m${`str[i] at ${i} = ${ str[i].trim() ? str.slice(i, y) : JSON.stringify(str[i], null, 0) }`}\u001b[${39}m ${`\u001b[${90}m (${str .slice(i, y) .split("") .map((v) => `#${v.charCodeAt(0)}`) .join( `; ` )}); i = ${i}; y = ${y}\u001b[${39}m`} \u001b[${36}m${`===============================`}\u001b[${39}m` ); console.log( `${`\u001b[${90}m${`state = ${JSON.stringify( state, null, 4 )}`}\u001b[${39}m`}` ); // console.log(`075 received endOfLineVal = ${JSON.stringify(endOfLineVal, null, 0)}`); if ( /[\uD800-\uDFFF]/g.test(str[i]) && !( (str.charCodeAt(i + 1) >= 0xdc00 && str.charCodeAt(i + 1) <= 0xdfff) || (str.charCodeAt(i - 1) >= 0xd800 && str.charCodeAt(i - 1) <= 0xdbff) ) ) { // if it's a surrogate and another surrogate doesn't come in front or // follow, it's considered to be stray and liable for removal console.log(`091 processCharacter.js - it's a stray surrogate`); rangesArr.push(i, i + 1); console.log( `094 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${ i + 1 }]` ); } else if (y - i > 1) { applicableOpts.convertEntities = true; console.log( `101 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); applicableOpts.dontEncodeNonLatin = applicableOpts.dontEncodeNonLatin || doConvertEntities(str.slice(i, y), true) !== doConvertEntities(str.slice(i, y), false); console.log( `110 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.dontEncodeNonLatin = ${ applicableOpts.dontEncodeNonLatin }` ); // if it's astral character which comprises of more than one character, // tackle it separately from "normal" charactrs of length === 1 if (opts.convertEntities) { rangesArr.push( i, y, doConvertEntities(str.slice(i, y), opts.dontEncodeNonLatin) ); } } else { // // // // // // // // so it's single character. const charcode = str[i].charCodeAt(0); // Filter ASCII // the cutoff point is 127 not 128 because large chunk of invisibles, C1 // group starts at DEL, decimal point 128. if (charcode < 127) { // within ASCII - no need to encode, just clean console.log( `141 processCharacter.js - ${`\u001b[${90}m${`character within ASCII`}\u001b[${39}m`}` ); if (charcode < 32) { if (charcode < 9) { if (charcode === 3) { // that's \u0003, END OF TEXT - replace with line break console.log( `148 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "${ opts.removeLineBreaks ? " " : "\\n" }"]` ); rangesArr.push( i, y, opts.removeLineBreaks ? " " : opts.replaceLineBreaks ? `<br${opts.useXHTML ? "/" : ""}>\n` : "\n" ); applicableOpts.removeLineBreaks = true; console.log( `164 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.removeLineBreaks = ${ applicableOpts.removeLineBreaks }` ); if (!opts.removeLineBreaks) { applicableOpts.replaceLineBreaks = true; console.log( `171 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.replaceLineBreaks = ${ applicableOpts.replaceLineBreaks }` ); if (opts.replaceLineBreaks) { applicableOpts.useXHTML = true; console.log( `179 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.useXHTML = ${ applicableOpts.useXHTML }` ); } } } else { // charcodes: [0;2], [4;8] - remove these control chars console.log( `188 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}]` ); rangesArr.push(i, y); } // continue to the next character (otherwise it would get encoded): // continue; } else if (charcode === 9) { // Replace all tabs, '\u0009', with spaces: console.log( `197 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, " "]` ); rangesArr.push(i, y, " "); // continue to the next character (otherwise it would get encoded): // continue; } else if (charcode === 10) { // 10 - "\u000A" - line feed, LF or \n console.log(`204 processCharacter.js - LF caught`); if (!applicableOpts.removeLineBreaks) { applicableOpts.removeLineBreaks = true; console.log( `209 processCharacter.js: SET ${`\u001b[${32}m${`applicableOpts.removeLineBreaks`}\u001b[${39}m`} = ${ applicableOpts.removeLineBreaks }` ); } if ( !opts.removeLineBreaks && (!brClosingBracketIndexesArr || (Array.isArray(brClosingBracketIndexesArr) && !brClosingBracketIndexesArr.some( (idx) => left(str, i) === idx ))) ) { if (opts.replaceLineBreaks) { applicableOpts.useXHTML = true; applicableOpts.replaceLineBreaks = true; console.log( `227 processCharacter.js: SET ${`\u001b[${32}m${`applicableOpts.useXHTML`}\u001b[${39}m`} = ${ applicableOpts.useXHTML }; ${`\u001b[${32}m${`applicableOpts.replaceLineBreaks`}\u001b[${39}m`} = ${ applicableOpts.replaceLineBreaks }` ); } else if (!opts.replaceLineBreaks) { // opts.replaceLineBreaks === false applicableOpts.replaceLineBreaks = true; console.log( `237 processCharacter.js: SET ${`\u001b[${32}m${`applicableOpts.replaceLineBreaks`}\u001b[${39}m`} = ${ applicableOpts.replaceLineBreaks }` ); } } if (!opts.removeLineBreaks) { applicableOpts.eol = true; console.log( `247 processCharacter.js: SET ${`\u001b[${32}m${`applicableOpts.eol`}\u001b[${39}m`} = ${ applicableOpts.eol }` ); } // won't run on CRLF, only on LF - the CR will be processed separately if (opts.removeLineBreaks) { // only remove replace with space if it's standalone, Mac-style // EOL ending, not Windows CRLF, because CR would have already // been replaced and replacing here would result in two spaces added let whatToInsert = " "; if (punctuationChars.includes(str[right(str, i) as number])) { whatToInsert = ""; } console.log( `264 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${JSON.stringify( whatToInsert, null, 0 )}]` ); rangesArr.push(i, y, whatToInsert); } else if ( opts.replaceLineBreaks && (!brClosingBracketIndexesArr || (Array.isArray(brClosingBracketIndexesArr) && !brClosingBracketIndexesArr.some( (idx) => left(str, i) === idx ))) ) { // above, we check, is there a closing bracket of <br>. // All this contraption is necessary because br's can have HTML // attributes - you can't just match <br> or <br/> or <br />, // there can be ESP tags in non-HTML let startingIdx = i; if ( str[i - 1] === " " && typeof leftStopAtNewLines(str, i) === "number" ) { startingIdx = (leftStopAtNewLines(str, i) as number) + 1; } rangesArr.push( startingIdx, i + (endOfLineVal === "\r" ? 1 : 0), `<br${opts.useXHTML ? "/" : ""}>${ endOfLineVal === "\r\n" ? "\r" : "" }${endOfLineVal === "\r" ? "\r" : ""}` ); console.log( `299 processCharacter.js: ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${startingIdx}, ${ i + (endOfLineVal === "\r" ? 1 : 0) }, ${`<br${opts.useXHTML ? "/" : ""}>${JSON.stringify( endOfLineVal === "\r\n" ? "\r" : "", null, 4 )}${JSON.stringify( endOfLineVal === "\r" ? "\r" : "", null, 4 )}`}]` ); } else { // // // delete any whitespace to the left if ( str[leftStopAtNewLines(str, i) as number] && str[leftStopAtNewLines(str, i) as number].trim() ) { // delete trailing whitespace at the end of each line const tempIdx = leftStopAtNewLines(str, i); if (typeof tempIdx === "number" && tempIdx < i - 1) { console.log( `323 processCharacter.js: ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ tempIdx + 1 }, ${i}]` ); rangesArr.push( tempIdx + 1, i, `${endOfLineVal === "\r\n" ? "\r" : ""}` ); } } if (endOfLineVal === "\r\n" && str[i - 1] !== "\r") { rangesArr.push(i, i, "\r"); console.log( `338 processCharacter.js: ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} missing CR for this Windows EOL [${i}, ${i}, "\\r"]` ); } else if (endOfLineVal === "\r") { rangesArr.push(i, i + 1); console.log( `343 processCharacter.js: delete this LF ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${ i + 1 }]` ); } // either way, delete any whitespace to the right const temp = rightStopAtNewLines(str, i); if (temp && str[temp].trim()) { if (temp > i + 1) { console.log( `354 processCharacter.js: ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ i + 1 }, ${temp}]` ); rangesArr.push(i + 1, temp); } } } // // URL detection: // // TODO - check state.onUrlCurrently state.onUrlCurrently = false; console.log( `370 processCharacter.js - SET ${`\u001b[${33}m${`state.onUrlCurrently`}\u001b[${39}m`} = false` ); } else if (charcode === 11 || charcode === 12) { // 11 - "\u000B" - tab // 12 - "\u000C" - form feed applicableOpts.removeLineBreaks = true; console.log( `377 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.removeLineBreaks = ${ applicableOpts.removeLineBreaks }` ); rangesArr.push(i, y, opts.removeLineBreaks ? " " : "\n"); console.log( `384 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${ opts.removeLineBreaks ? " " : "\\n" }]` ); // continue; } else if (charcode === 13) { // 13 - "\u000D" - carriage return console.log(`391 CR caught`); if (!applicableOpts.removeLineBreaks) { applicableOpts.removeLineBreaks = true; console.log( `396 processCharacter.js: SET ${`\u001b[${32}m${`applicableOpts.removeLineBreaks`}\u001b[${39}m`} = ${ applicableOpts.removeLineBreaks }` ); } if ( !opts.removeLineBreaks && (!brClosingBracketIndexesArr || (Array.isArray(brClosingBracketIndexesArr) && !brClosingBracketIndexesArr.some( (idx) => left(str, i) === idx ))) ) { if (opts.replaceLineBreaks && !opts.removeLineBreaks) { applicableOpts.useXHTML = true; applicableOpts.replaceLineBreaks = true; console.log( `414 processCharacter.js: SET ${`\u001b[${32}m${`applicableOpts.useXHTML`}\u001b[${39}m`} = ${ applicableOpts.useXHTML }; ${`\u001b[${32}m${`applicableOpts.replaceLineBreaks`}\u001b[${39}m`} = ${ applicableOpts.replaceLineBreaks }` ); } else if (!opts.replaceLineBreaks) { // opts.replaceLineBreaks === false applicableOpts.replaceLineBreaks = true; console.log( `424 processCharacter.js: SET ${`\u001b[${32}m${`applicableOpts.replaceLineBreaks`}\u001b[${39}m`} = ${ applicableOpts.replaceLineBreaks }` ); } } if (!opts.removeLineBreaks) { applicableOpts.eol = true; console.log( `434 processCharacter.js: SET ${`\u001b[${32}m${`applicableOpts.eol`}\u001b[${39}m`} = ${ applicableOpts.eol }` ); } if (opts.removeLineBreaks) { let whatToInsert = " "; if ( punctuationChars.includes(str[right(str, i) as number]) || ["\n", "\r"].includes(str[i + 1]) ) { whatToInsert = ""; } rangesArr.push(i, y, whatToInsert); console.log( `450 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${JSON.stringify( whatToInsert, null, 0 )}]` ); } else if ( opts.replaceLineBreaks && (!brClosingBracketIndexesArr || (Array.isArray(brClosingBracketIndexesArr) && !brClosingBracketIndexesArr.some( (idx) => left(str, i) === idx ))) ) { console.log(`464`); let startingIdx = i; if ( str[i - 1] === " " && typeof leftStopAtNewLines(str, i) === "number" ) { startingIdx = (leftStopAtNewLines(str, i) as number) + 1; } let endingIdx = i; let whatToInsert = ""; if (str[i + 1] !== "\n") { if (endOfLineVal === "\n") { whatToInsert = "\n"; } else if (endOfLineVal === "\r\n") { // add missing LF after current CR rangesArr.push(i + 1, i + 1, "\n"); console.log( `482 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i + 1}, ${ i + 1 }]` ); } } if (endOfLineVal === "\n") { // extend this range to also delete this CR endingIdx = i + 1; } else if (endOfLineVal === "\r" && str[i + 1] === "\n") { // delete that LF from wrong CRLF set which is present rangesArr.push(i + 1, i + 2); console.log( `496 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i + 1}, ${ i + 2 }]` ); } rangesArr.push( startingIdx, endingIdx, `<br${opts.useXHTML ? "/" : ""}>${whatToInsert}` ); console.log( `507 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${startingIdx}, ${endingIdx}, ${JSON.stringify( whatToInsert, null, 4 )}]` ); // skip the \n that follows if (str[i + 1] === "\n") { console.log(`516 offset by 1`); offsetBy(1); } } else { console.log(`520`); if (endOfLineVal === "\n") { rangesArr.push(i, i + 1, str[i + 1] === "\n" ? "" : "\n"); console.log( `524 PUSH [${i}, ${i + 1}, ${JSON.stringify( str[i + 1] === "\n" ? "" : "\n", null, 0 )}]` ); } else if (endOfLineVal === "\r" && str[i + 1] === "\n") { // delete the LF that follows rangesArr.push(i + 1, i + 2); console.log(`533 PUSH [${i + 1}, ${i + 2}]`); } else if (endOfLineVal === "\r\n" && str[i + 1] !== "\n") { // add LF afterwards rangesArr.push(i, i + 1, "\n"); console.log(`537 PUSH [${i}, ${i + 1}, "\\n"]`); } // delete whitespace at the beginning and at the end of each line const tempIdx1 = leftStopAtNewLines(str, i); if (typeof tempIdx1 === "number" && str[tempIdx1].trim()) { // delete trailing whitespace at the end of each line let endingIdx = i; if (endOfLineVal === "\n") { // extend this range to also delete this CR endingIdx = i + 1; } if (tempIdx1 < i - 1) { console.log( `551 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ tempIdx1 + 1 }, ${endingIdx}, ${JSON.stringify( `${str[i + 1] === "\n" ? "" : "\n"}`, null, 4 )}]` ); rangesArr.push( tempIdx1 + 1, endingIdx, `${str[i + 1] === "\n" ? "" : "\n"}` ); } } // delete whitespace in front of each line const tempIdx2 = rightStopAtNewLines(str, i); if (tempIdx2 && str[tempIdx2].trim() && str[i + 1] !== "\n") { if (tempIdx2 > i + 1) { console.log( `572 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ i + 1 }, ${tempIdx2}]` ); rangesArr.push(i + 1, tempIdx2); } } } } else if (charcode > 13) { // charcodes: [14;31] - remove these control chars rangesArr.push(i, y); console.log( `584 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}]` ); // continue; } } else { console.log(`589 processCharacter.js - clauses 32 <= charcode < 127`); // 32 <= charcode < 127 // NO ENCODING HERE, JUST FIXES if (charcode === 32) { // IF SPACE CHARACTER } else if (charcode === 34) { // IF DOUBLE QUOTE console.log(`597 processCharacter.js: double quote caught`); applicableOpts.convertEntities = true; console.log( `600 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); if (isNumber(left(str, i)) || isNumber(right(str, i))) { applicableOpts.convertApostrophes = true; console.log( `607 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertApostrophes = ${ applicableOpts.convertApostrophes }` ); } const tempRes = convertOne(str, { from: i, convertEntities: opts.convertEntities, convertApostrophes: opts.convertApostrophes, offsetBy, }); console.log( `619 ${`\u001b[${33}m${`tempRes`}\u001b[${39}m`} = ${JSON.stringify( tempRes, null, 4 )}` ); if (tempRes && tempRes.length) { rangesArr.push(tempRes as any); } else if (opts.convertEntities) { rangesArr.push(i, i + 1, "&quot;"); } } else if (charcode === 38) { // IF AMPERSAND, the & console.log(`632 processCharacter.js - ampersand clauses`); if (isLetter(str[i + 1])) { // it can be a named entity const temp = Object.keys(allNamedEntities).find( (entName) => str.startsWith(entName, i + 1) && str[i + entName.length + 1] === ";" ); console.log( `641 processCharacter.js - ${`\u001b[${33}m${`temp`}\u001b[${39}m`} = ${JSON.stringify( temp, null, 4 )}` ); applicableOpts.convertEntities = true; console.log( `649 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); if (temp) { console.log( `655 processCharacter.js - named entity, ${`\u001b[${32}m${temp}\u001b[${39}m`} found` ); if (temp === "apos") { applicableOpts.convertApostrophes = true; console.log( `661 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertApostrophes = ${ applicableOpts.convertApostrophes }` ); console.log(`666 processCharacter.js - let's decode`); const decodedTempRes = convertOne(str, { from: i, to: i + temp.length + 2, value: `'`, convertEntities: opts.convertEntities, convertApostrophes: opts.convertApostrophes, offsetBy, }); if (Array.isArray(decodedTempRes) && decodedTempRes.length) { rangesArr.push(decodedTempRes as any); console.log( `678 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( decodedTempRes, null, 0 )}` ); console.log(`684 offset by ${temp.length + 2}`); offsetBy(temp.length + 2); } else { rangesArr.push([i, i + temp.length + 2, `'`]); console.log( `689 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( [i, i + temp.length + 2, `'`], null, 0 )}` ); console.log(`695 offset by ${temp.length + 2}`); offsetBy(temp.length + 2); } } else if ( opts.convertEntities && Object.keys(notEmailFriendly).includes( str.slice(i + 1, i + temp.length + 1) ) ) { console.log( `705 processCharacter.js - not email-friendly named entity` ); rangesArr.push( i, i + temp.length + 2, `&${notEmailFriendly[str.slice(i + 1, i + temp.length + 1)]};` ); console.log( `713 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${ i + temp.length + 2 }, &${JSON.stringify( notEmailFriendly[str.slice(i + 1, i + temp.length + 1)], null, 4 )};]` ); offsetBy(temp.length + 1); console.log(`722 offset by ${temp.length + 1}`); } else if (!opts.convertEntities) { console.log( `725 decoded ${JSON.stringify( str.slice(i, i + temp.length + 2), null, 4 )} (charCodeAt = ${he .decode(`${str.slice(i, i + temp.length + 2)}`) .charCodeAt(0)})` ); console.log( `734 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} decoded [${i}, ${ i + temp.length + 2 }, ${JSON.stringify( he.decode(`${str.slice(i, i + temp.length + 2)}`), null, 4 )}]` ); rangesArr.push( i, i + temp.length + 2, he.decode(`${str.slice(i, i + temp.length + 2)}`) ); offsetBy(temp.length + 1); console.log(`748 offset by ${temp.length + 1}`); } else { // if opts.convertEntities // just skip offsetBy(temp.length + 1); console.log(`753 offset by ${temp.length + 1}`); } } else if (opts.convertEntities) { // no named entities matched, so encode the ampersand rangesArr.push(i, i + 1, "&amp;"); console.log( `759 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${ i + 1 }, "&amp;"]` ); } } else if (str[right(str, i) as number] === "#") { // it can be a numeric, a decimal or a hex entity console.log("766 ██ numeric, a decimal or a hex entity"); for (let z = right(str, i) as number; z < len; z++) { if (str[z].trim() && !isNumber(str[z]) && str[z] !== "#") { if (str[z] === ";") { // it's numeric entity console.log(`771 carved out "${str.slice(i, z + 1)}"`); const tempRes = he.encode(he.decode(str.slice(i, z + 1)), { useNamedReferences: true, }); console.log( `776 ${`\u001b[${33}m${`tempRes`}\u001b[${39}m`} = ${JSON.stringify( tempRes, null, 4 )}` ); if (tempRes) { rangesArr.push(i, z + 1, tempRes); console.log( `785 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${ z + 1 }, "${tempRes}"]` ); } offsetBy(z + 1 - i); console.log(`791 offset by ${z + 1 - i}`); } else { // do checks, maybe semicol is missing? // TODO } } } } else { applicableOpts.convertEntities = true; console.log( `801 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); if (opts.convertEntities) { // encode it rangesArr.push(i, i + 1, "&amp;"); console.log( `809 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${ i + 1 }, "&amp;"]` ); } } } else if (charcode === 39) { // IF SINGLE QUOTE OR APOSTROPHE, the ' // first, calculate theoretical maximum setting and set applicable rules // based on it const temp = convertOne(str, { from: i, convertEntities: true, convertApostrophes: true, }); if (temp && temp.length) { applicableOpts.convertApostrophes = true; console.log( `828 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertApostrophes = ${ applicableOpts.convertApostrophes }` ); if (opts.convertApostrophes) { applicableOpts.convertEntities = true; console.log( `835 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); } rangesArr.push( convertOne(str, { from: i, convertEntities: opts.convertEntities, convertApostrophes: opts.convertApostrophes, offsetBy, }) as any ); } } else if (charcode === 44 || charcode === 59) { // IF COMMA (,) OR SEMICOLON (;) // 1. check for whitespace leading to colon or semicolon if (str[i - 1] && !str[i - 1].trim()) { const whatsOnTheLeft = left(str, i); if (typeof whatsOnTheLeft === "number" && whatsOnTheLeft < i - 1) { rangesArr.push(whatsOnTheLeft + 1, i); console.log( `858 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ whatsOnTheLeft + 1 }, ${i}]` ); } } // 2. comma-specific if ( charcode === 44 && str[y] !== undefined && !state.onUrlCurrently && !isNumber(str[y]) && str[y].trim() && str[y] !== " " && str[y] !== "\n" && str[y] !== '"' && str[y] !== "'" && str[y] !== leftSingleQuote && str[y] !== leftDoubleQuote && str[y] !== rightSingleQuote && str[y] !== rightDoubleQuote ) { // comma, not on URL, not followed by number = add space afterwards applicableOpts.addMissingSpaces = true; console.log( `884 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.addMissingSpaces = ${ applicableOpts.addMissingSpaces }` ); if (opts.addMissingSpaces) { rangesArr.push(y, y, " "); console.log( `892 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${y}, ${y}, " "]` ); } } console.log(`897`); // 3. semicolon-specific if ( charcode === 59 && str[y] !== undefined && !state.onUrlCurrently && str[y].trim() && str[y] !== "&" && str[y] !== '"' && str[y] !== "'" && str[y] !== leftSingleQuote && str[y] !== leftDoubleQuote && str[y] !== rightSingleQuote && str[y] !== rightDoubleQuote ) { applicableOpts.addMissingSpaces = true; console.log( `914 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.addMissingSpaces = ${ applicableOpts.addMissingSpaces }` ); if (opts.addMissingSpaces) { rangesArr.push(y, y, " "); console.log( `922 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${y}, ${y}, " "]` ); } } } else if (charcode === 45) { // IF MINUS SIGN / HYPHEN console.log("928 processCharacter.js - minus caught"); // don't mess up if minus is between two numbers if ( str[i - 1] === " " && str[y] === " " && isNumber(str[left(str, i) as number]) && isNumber(str[right(str, y) as number]) ) { console.log(`936 processCharacter.js - seems legit - skip`); } // add space after minus/dash character if there's nbsp or space in front of it, // but the next character is not currency or digit. // That's to prevent the space addition in front of legit minuses. else if ( (str[i - 1] === rawNbsp || str[i - 1] === " ") && str[y] !== "$" && str[y] !== "£" && str[y] !== "€" && str[y] !== "₽" && str[y] !== "0" && str[y] !== "1" && str[y] !== "2" && str[y] !== "3" && str[y] !== "4" && str[y] !== "5" && str[y] !== "6" && str[y] !== "7" && str[y] !== "8" && str[y] !== "9" && str[y] !== "-" && str[y] !== ">" && str[y] !== " " ) { applicableOpts.addMissingSpaces = true; console.log( `963 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.addMissingSpaces = ${ applicableOpts.addMissingSpaces }` ); if (opts.addMissingSpaces) { // add space after it: rangesArr.push(y, y, " "); console.log( `972 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${y}, ${y}, " "]` ); } } else if ( str[i - 1] && str[y] && ((isNumber(str[i - 1]) && isNumber(str[y])) || (str[i - 1].toLowerCase() === "a" && str[y].toLowerCase() === "z")) ) { applicableOpts.convertDashes = true; console.log( `984 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertDashes = ${ applicableOpts.convertDashes }` ); if (opts.convertDashes) { applicableOpts.convertEntities = true; console.log( `992 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); console.log( `998 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${ opts.convertEntities ? "&ndash;" : "\u2013" }]` ); rangesArr.push(i, y, opts.convertEntities ? "&ndash;" : "\u2013"); } } else if ( str[i - 1] && str[y] && ((!str[i - 1].trim() && !str[y].trim()) || (isLowercaseLetter(str[i - 1]) && str[y] === "'")) ) { applicableOpts.convertDashes = true; console.log( `1012 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertDashes = ${ applicableOpts.convertDashes }` ); if (opts.convertDashes) { applicableOpts.convertEntities = true; console.log( `1020 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); console.log( `1026 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${ opts.convertEntities ? "&mdash;" : rawMDash }]` ); rangesArr.push(i, y, opts.convertEntities ? "&mdash;" : rawMDash); } } else if ( str[i - 1] && str[y] && isLetter(str[i - 1]) && isQuote(str[y]) ) { applicableOpts.convertDashes = true; console.log( `1040 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertDashes = ${ applicableOpts.convertDashes }` ); if (opts.convertDashes) { applicableOpts.convertEntities = true; console.log( `1048 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); // direct speech breaks off console.log( `1055 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${ opts.convertEntities ? "&mdash;" : rawMDash }]` ); rangesArr.push(i, y, opts.convertEntities ? "&mdash;" : rawMDash); } } // tackle widow word setting - space in front when opts.removeWidows is on if ( str[i - 2] && str[i - 2].trim() && !str[i - 1].trim() && !["\n", "\r"].includes(str[i - 1]) ) { // 1. mark option as applicable applicableOpts.removeWidows = true; console.log( `1073 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.removeWidows`}\u001b[${39}m`} = ${ applicableOpts.removeWidows }` ); // 2. if option is on, apply it if (opts.removeWidows) { applicableOpts.convertEntities = true; console.log( `1082 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts.convertEntities`}\u001b[${39}m`} = ${ applicableOpts.convertEntities }` ); rangesArr.push( i - 1, i, opts.convertEntities ? "&nbsp;" : rawNbsp ); console.log( `1093 processCharacter.js: ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} nbsp [${ i - 1 }, ${i}, ${opts.convertEntities ? "&nbsp;" : rawNbsp}]` ); } } } else if (charcode === 46) { // IF DOT CHARACTER // // 1. convert first of three and only three dots to ellipsis, encode // if needed // TODO - improve matching to account for possible spaces between dots if ( str[i - 1] !== "." && str[y] === "." && str[y + 1] === "." && str[y + 2] !== "." ) { applicableOpts.convertDotsToEllipsis = true; console.log( `1113 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertDotsToEllipsis = ${ applicableOpts.convertDotsToEllipsis }` ); if (opts.convertDotsToEllipsis) { applicableOpts.convertEntities = true; console.log( `1121 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); console.log( `1127 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${ y + 2 }, ${opts.convertEntities ? "&hellip;" : `${rawEllipsis}`}]` ); rangesArr.push( i, y + 2, opts.convertEntities ? "&hellip;" : `${rawEllipsis}` ); } } // 2. add missing space after full stop or comma except on extensions and URL's const first = str[y] ? str[y].toLowerCase() : ""; const second = str[y + 1] ? str[y + 1].toLowerCase() : ""; const third = str[y + 2] ? str[y + 2].toLowerCase() : ""; const fourth = str[y + 3] ? str[y + 3].toLowerCase() : ""; const nextThreeChars = first + second + third; if ( first + second !== "js" && nextThreeChars !== "jpg" && nextThreeChars !== "png" && nextThreeChars !== "gif" && nextThreeChars !== "svg" && nextThreeChars !== "htm" && nextThreeChars !== "pdf" && nextThreeChars !== "psd" && nextThreeChars !== "tar" && nextThreeChars !== "zip" && nextThreeChars !== "rar" && nextThreeChars !== "otf" && nextThreeChars !== "ttf" && nextThreeChars !== "eot" && nextThreeChars !== "php" && nextThreeChars !== "rss" && nextThreeChars !== "asp" && nextThreeChars !== "ppt" && nextThreeChars !== "doc" && nextThreeChars !== "txt" && nextThreeChars !== "rtf" && nextThreeChars !== "git" && nextThreeChars + fourth !== "jpeg" && nextThreeChars + fourth !== "html" && nextThreeChars + fourth !== "woff" && !( !isLetter(str[i - 2]) && str[i - 1] === "p" && str[y] === "s" && str[y + 1] === "t" && !isLetter(str[y + 2]) ) ) { // two tasks: deleting any spaces before and adding spaces after // // 2-1. ADDING A MISSING SPACE AFTER IT: if ( str[y] !== undefined && // - When it's not within a URL, the requirement for next letter to be uppercase letter. // This prevents both numbers with decimal digits and short url's like "detergent.io" // - When it's within URL, it's stricter: // next letter has to be an uppercase letter, followed by lowercase letter. ((!state.onUrlCurrently && isUppercaseLetter(str[y])) || (state.onUrlCurrently && isLetter(str[y]) && isUppercaseLetter(str[y]) && isLetter(str[y + 1]) && isLowercaseLetter(str[y + 1]))) && str[y] !== " " && str[y] !== "." && str[y] !== "\n" ) { applicableOpts.addMissingSpaces = true; console.log( `1200 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.addMissingSpaces = ${ applicableOpts.addMissingSpaces }` ); if (opts.addMissingSpaces) { rangesArr.push(y, y, " "); console.log( `1208 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${y}, ${y}, " "]` ); } } // 2-2. REMOVING SPACES BEFORE IT: if ( str[i - 1] !== undefined && str[i - 1].trim() === "" && str[y] !== "." && (str[i - 2] === undefined || str[i - 2] !== ".") // that's for cases: "aaa. . " < observe second dot. ) { // march backwards for (y = i - 1; y--; ) { if (str[y].trim() !== "") { rangesArr.push(y + 1, i); console.log( `1225 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ y + 1 }, ${i}]` ); break; } } } } } else if (charcode === 47) { console.log("1235 processCharacter.js - right slash caught"); // IF RIGHT SLASH, / } else if (charcode === 58) { // IF COLON (:) // // URL detection // if ( str[y - 1] && str[right(str, y - 1) as number] === "/" && str[right(str, right(str, y - 1) as number) as number] === "/" ) { state.onUrlCurrently = true; console.log( `1250 processCharacter.js - ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`state.onUrlCurrently`}\u001b[${39}m`} = true` ); } } else if (charcode === 60) { // IF LESS THAN SIGN, < applicableOpts.convertEntities = true; console.log( `1257 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); if (opts.convertEntities) { rangesArr.push(i, i + 1, "&lt;"); console.log( `1265 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${ i + 1 }, "&lt;"]` ); } } else if (charcode === 62) { // IF GREATER THAN SIGN, > applicableOpts.convertEntities = true; console.log( `1274 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); if (opts.convertEntities) { rangesArr.push(i, i + 1, "&gt;"); console.log( `1282 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${ i + 1 }, "&gt;"]` ); } } else if (charcode === 119) { // IF LETTER w // // URL detection // if ( str[y + 1] && str[y].toLowerCase() === "w" && str[y + 1].toLowerCase() === "w" ) { state.onUrlCurrently = true; console.log( `1299 processCharacter.js - ${`\u001b[${33}m${`state.onUrlCurrently`}\u001b[${39}m`} = true` ); } } else if (charcode === 123) { // opening curly bracket { // check for following {{ and {%, if following skip until closing found let stopUntil; if (str[y] === "{") { stopUntil = "}}"; } else if (str[y] === "%") { stopUntil = "%}"; } // PS. whitespace limiting with dashes like {%- zz -%} don't matter // because dashes sit inside and will be caught by standard {%..%} if (stopUntil) { console.log( `1316 processCharacter.js - stopUntil = ${stopUntil} so loop:` ); for (let z = i; z < len; z++) { console.log(`= str[z] = ${str[z]}`); if (str[z] === stopUntil[0] && str[z + 1] === stopUntil[1]) { console.log( `1322 processCharacter.js - offset by ${z + 1 - i}` ); offsetBy(z + 1 - i); break; } } // if end is reached and closing counterpart is not found, // nothing happens. } } } } else { // >= 127 // outside ASCII, need to encode (unless requested not to) console.log( `1337 processCharacter.js - ${`\u001b[${90}m${`character outside ASCII`}\u001b[${39}m`}; charcode = ${charcode}` ); // plan - filter all characters for deletion and leave reset (ELSE) to // be encoded if (charcode > 126 && charcode < 160) { // C1 group if (charcode !== 133) { // over thirty characters, so they are statistically more likely to happen: rangesArr.push(i, y); console.log( `1349 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}]` ); } else { // only codepoint 133 - Next Line (NEL), statistically less probable // so it comes second: applicableOpts.removeLineBreaks = true; console.log( `1356 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.removeLineBreaks = ${ applicableOpts.removeLineBreaks }` ); rangesArr.push(i, y, opts.removeLineBreaks ? "" : "\n"); console.log( `1363 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${ opts.removeLineBreaks ? "" : "\\n" }]` ); } } else if (charcode === 160) { // IF RAW non-breaking space // if opts.removeWidows is disabled, replace all non-breaking spaces // with spaces if (!opts.removeWidows) { // we need to remove this nbsp // thing to consider - edges, like "&nbsp; a b" const calculatedFrom = i; const calculatedTo = y; let calculatedValue = " "; // const charOnTheLeft = leftStopAtRawNbsp(str, i); const charOnTheLeft = left(str, i); console.log( `1383 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`charOnTheLeft`}\u001b[${39}m`} = ${JSON.stringify( charOnTheLeft, null, 4 )}` ); // const charOnTheRight = rightStopAtRawNbsp(str, calculatedTo - 1); const charOnTheRight = right(str, calculatedTo - 1); console.log( `1392 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`charOnTheRight`}\u001b[${39}m`} = ${JSON.stringify( charOnTheRight, null, 4 )}` ); if (charOnTheLeft === null || charOnTheRight === null) { // this means, this raw nbsp is around the edge of the string, // for example: // <raw nbsp> a b // ^^^^^^^^^^ // might be decoded &nbsp; - single character // restore it back: calculatedValue = opts.convertEntities ? "&nbsp;" : rawNbsp; console.log( `1409 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`calculatedValue`}\u001b[${39}m`} = ${JSON.stringify( calculatedValue, null, 4 )}` ); applicableOpts.convertEntities = true; console.log( `1418 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); } else { // if it's deleted, it's applicable applicableOpts.removeWidows = true; console.log( `1426 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.removeWidows = ${ applicableOpts.removeWidows }` ); } if (calculatedValue) { rangesArr.push(calculatedFrom, calculatedTo, calculatedValue); console.log( `1435 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${calculatedFrom}, ${calculatedTo}, ${JSON.stringify( calculatedValue, null, 4 )}(#${calculatedValue.charCodeAt(0)})]` ); } else { rangesArr.push(calculatedFrom, calculatedTo); console.log( `1444 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${calculatedFrom}, ${calculatedTo}]` ); } } else { applicableOpts.convertEntities = true; console.log( `1450 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); applicableOpts.removeWidows = true; console.log( `1456 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.removeWidows = ${ applicableOpts.removeWidows }` ); if (opts.convertEntities) { // push "&nbsp;" to retain in console.log( `1464 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "&nbsp;"]` ); rangesArr.push(i, y, "&nbsp;"); } } } else if (charcode === 173) { // IF SOFT HYPHEN, '\u00AD' rangesArr.push(i, y); console.log( `1473 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}]` ); } else if (charcode === 8232 || charcode === 8233) { // '\u2028', '\u2029' applicableOpts.removeLineBreaks = true; console.log( `1479 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.removeLineBreaks = ${ applicableOpts.removeLineBreaks }` ); rangesArr.push(i, y, opts.removeLineBreaks ? "" : "\n"); console.log( `1486 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${ opts.removeLineBreaks ? "" : "\\n" }]` ); } else if ( [ 5760, 8191, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, ].includes(charcode) ) { // replace with spaces from // https://www.fileformat.info/info/unicode/category/Zs/list.htm // - ogham space marks (#5760), '\u1680' // - en quad (#8192), '\u2000' // - em quad (#8193), '\u2001' // - en space (#8194), '\u2002' // - em space (#8195), '\u2003' // - three-per-em-space (#8196), '\u2004' // - four-per-em-space (#8197), '\u2005' // - six-per-em-space (#8198), '\u2006' // - figure space (#8199), '\u2007' // - punctuation space (#8200), '\u2008' // - thin space (#8201), '\u2009' // - hair space (#8202), '\u200A' // - narrow no break space (#8239), '\u202F' // - medium mathematical space (#8287), '\u205F' // - ideographic space (#12288), '\u3000' console.log("1515 processCharacter.js - hairspace caught"); if (!str[y]) { rangesArr.push(i, y); console.log( `1519 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}]` ); } else { // rangesArr.push(i, y, " "); const expandedRange = expander({ str, from: i, to: y, wipeAllWhitespaceOnLeft: true, wipeAllWhitespaceOnRight: true, addSingleSpaceToPreventAccidentalConcatenation: true, }); console.log( `1532 processCharacter.js - expanded to ${JSON.stringify( expandedRange, null, 0 )} and then pushed it` ); (rangesArr as any).push(...expandedRange); } } else if (charcode === 8206) { // remove all left-to-right mark chars, '\u200E' console.log("1542 processCharacter.js - LTR mark caught"); rangesArr.push(i, y); console.log( `1545 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}]` ); } else if (charcode === 8207) { console.log("1548 processCharacter.js - RTL mark caught"); // remove all right-to-right mark chars, '\u200F' rangesArr.push(i, y); console.log( `1552 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}]` ); } else if ( charcode === 8211 || (charcode === 65533 && isNumber(str[i - 1]) && isNumber(str[y])) ) { // IF N-DASH, '\u2013' console.log("1559 processCharacter.js - N dash caught"); applicableOpts.convertDashes = true; console.log( `1563 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertDashes = ${ applicableOpts.convertDashes }` ); if (!opts.convertDashes) { console.log(`1569 conversion is off`); rangesArr.push(i, y, "-"); console.log( `1572 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "-"]` ); } else { applicableOpts.convertEntities = true; console.log( `1577 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); if (opts.convertEntities) { // if it's space-ndash-space, put m-dash instead if ( str[i - 1] && !str[i - 1].trim() && str[i + 1] && !str[i + 1].trim() && !(isNumber(str[i - 2]) && isNumber(str[i + 2])) ) { rangesArr.push(i, y, "&mdash;"); console.log( `1593 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "&mdash;"]` ); } else { // ELSE - n-dash stays rangesArr.push(i, y, "&ndash;"); console.log( `1599 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "&ndash;"]` ); } } else if (charcode === 65533) { if ( str[i - 1] && !str[i - 1].trim() && str[i + 1] && !str[i + 1].trim() ) { rangesArr.push(i, y, rawMDash); console.log( `1611 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "raw m-dash"]` ); } else { rangesArr.push(i, y, rawNDash); console.log( `1616 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "raw n-dash"]` ); } } } // if there's space in front but no space after: // --------------------------------------------- if (str[i - 1] && !str[i - 1].trim() && str[y].trim()) { console.log(`1625`); if (str[i - 2] && isNumber(str[i - 2]) && isNumber(str[y])) { rangesArr.push(i - 1, i); console.log( `1629 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} (TO DELETE) [${ i - 1 }, ${i}]` ); } else { applicableOpts.addMissingSpaces = true; console.log( `1636 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.addMissingSpaces = ${ applicableOpts.addMissingSpaces }` ); applicableOpts.convertEntities = true; console.log( `1642 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); // 1. // add space after if (opts.addMissingSpaces) { let whatToAdd = " "; // imagine case "10am&nbsp;&ndash;11am" - we're adding space // before "11am", but there needs to be non-breaking space because // widow removal is on if (!widowRegexTest.test(str.slice(y))) { applicableOpts.removeWidows = true; console.log( `1657 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.removeWidows = ${ applicableOpts.removeWidows }` ); if (opts.removeWidows) { whatToAdd = opts.convertEntities ? "&nbsp;" : rawNbsp; console.log( `1664 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} whatToAdd = ${ opts.convertEntities ? whatToAdd : "rawNbsp" }` ); } } rangesArr.push(y, y, whatToAdd); console.log( `1673 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${y}, ${y}, ${JSON.stringify( whatToAdd, null, 0 )}]` ); } // 2. // replace space in front with non-breaking space if widow removal is on if (str.slice(i - 1, i) !== rawNbsp) { applicableOpts.removeWidows = true; console.log( `1686 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.removeWidows = ${ applicableOpts.removeWidows }` ); if (opts.removeWidows) { rangesArr.push( i - 1, i, opts.convertEntities ? "&nbsp;" : rawNbsp ); console.log( `1698 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ i - 1 }, ${i}, ${JSON.stringify( opts.convertEntities ? "&nbsp;" : rawNbsp, null, 0 )}]` ); } } } } else if ( str[i - 2] && str[i - 1] && str[y] && str[y + 1] && isNumber(str[i - 2]) && isNumber(str[y + 1]) && !str[i - 1].trim() && !str[y].trim() ) { // delete spaces around n-dash if those are number strings rangesArr.push(i - 1, i); rangesArr.push(y, y + 1); console.log( `1723 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ i - 1 }, ${i}], then [${y}, ${y + 1}]` ); } // Also, if it is mistakenly put instead of an m-dash, we need to tackle // the widow word, space in front of it within this clause. if ( str[i - 2] && str[i + 1] && !str[i - 1].trim() && str[i - 2].trim() && !str[i + 1].trim() && !(isNumber(str[i - 2]) && isNumber(str[i + 2])) ) { // 1. report as applicable applicableOpts.removeWidows = true; if (opts.removeWidows) { // 2. replace the space rangesArr.push(i - 1, i, opts.convertEntities ? "&nbsp;" : rawNbsp); console.log( `1746 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ i - 1 }, ${i}, ${JSON.stringify( opts.convertEntities ? "&nbsp;" : rawNbsp, null, 4 )}]` ); } } } else if ( charcode === 8212 || (charcode === 65533 && str[i - 1] === " " && str[y] === " ") ) { // IF RAW M-DASH, '\u2014' console.log("1761 processCharacter.js - M dash caught"); applicableOpts.convertDashes = true; console.log( `1765 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertDashes = ${ applicableOpts.convertDashes }` ); // replace spaces in front with nbsp if widow removal is on if (str[i - 1] === " " && left(str, i) !== null) { applicableOpts.removeWidows = true; console.log( `1774 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.removeWidows = ${ applicableOpts.removeWidows }` ); if (opts.removeWidows) { applicableOpts.convertEntities = true; console.log( `1782 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); if (typeof left(str, i) === "number") { rangesArr.push( (left(str, i) as number) + 1, i, opts.convertEntities ? "&nbsp;" : rawNbsp ); console.log( `1794 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${ (left(str, i) as number) + 1 }, ${i}, ${JSON.stringify( opts.convertEntities ? "&nbsp;" : rawNbsp, null, 4 )} (charCodeAt=${rawNbsp.charCodeAt(0)})]` ); } } } // tackle conversion into hyphen and surrounding spaces if (!opts.convertDashes) { console.log(`1808 processCharacter.js - conversion is off`); rangesArr.push(i, y, "-"); console.log( `1811 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "-"]` ); } else { applicableOpts.convertEntities = true; console.log( `1816 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); // 1. if there's space in front but no space after M-dash, add one after if (str[i - 1] && !str[i - 1].trim() && str[y].trim()) { applicableOpts.addMissingSpaces = true; console.log( `1824 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.addMissingSpaces = ${ applicableOpts.addMissingSpaces }` ); if (opts.addMissingSpaces) { rangesArr.push(y, y, " "); console.log( `1832 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${y}, ${y}, " "]` ); } } // 2. encode if applicable if (opts.convertEntities) { rangesArr.push(i, y, "&mdash;"); console.log( `1841 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "&mdash;"]` ); } else if (charcode === 65533) { rangesArr.push(i, y, rawMDash); console.log( `1846 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "raw m-dash"]` ); } console.log( `processCharacter.js - ${`\u001b[${33}m${`rangesArr.current()`}\u001b[${39}m`} = ${JSON.stringify( rangesArr.current(), null, 4 )}` ); } } else if (charcode === 8216) { // IF UNENCODED LEFT SINGLE QUOTE const tempRes = convertOne(str, { from: i, to: y, convertEntities: true, convertApostrophes: true, }); if (tempRes && tempRes.length) { applicableOpts.convertApostrophes = true; console.log( `1871 processCharacter.js - ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertApostrophes = ${ applicableOpts.convertApostrophes }` ); const tempRes2 = convertOne(str, { from: i, to: y, convertEntities: true, convertApostrophes: true, }); if (tempRes2) { if (opts.convertApostrophes) { applicableOpts.convertEntities = true; console.log( `1887 processCharacter.js - ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); } rangesArr.push( convertOne(str, { from: i, to: y, convertEntities: opts.convertEntities, convertApostrophes: opts.convertApostrophes, offsetBy, }) as any ); } } } else if (charcode === 8217) { // IF UNENCODED RIGHT SINGLE QUOTE applicableOpts.convertApostrophes = true; console.log( `1908 processCharacter.js - ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertApostrophes = ${ applicableOpts.convertApostrophes }` ); if (!opts.convertApostrophes) { rangesArr.push(i, y, "'"); console.log( `1916 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "'"]` ); } else { applicableOpts.convertEntities = true; console.log( `1921 processCharacter.js - ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); if (opts.convertEntities) { rangesArr.push(i, y, "&rsquo;"); console.log( `1928 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "&rsquo;"]` ); } } } else if (charcode === 8220) { // IF UNENCODED LEFT DOUBLE QUOTE applicableOpts.convertApostrophes = true; console.log( `1936 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertApostrophes = ${ applicableOpts.convertApostrophes }` ); if (!opts.convertApostrophes) { applicableOpts.convertEntities = true; console.log( `1944 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); rangesArr.push(i, y, opts.convertEntities ? `&quot;` : `"`); console.log( `1950 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${JSON.stringify( opts.convertEntities ? `&quot;` : `"`, null, 0 )}]` ); } else if (opts.convertEntities) { applicableOpts.convertEntities = true; console.log( `1959 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); rangesArr.push(i, y, "&ldquo;"); console.log( `1965 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "&ldquo;"]` ); } } else if (charcode === 8221) { // IF UNENCODED RIGHT DOUBLE QUOTE applicableOpts.convertApostrophes = true; console.log( `1972 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertApostrophes = ${ applicableOpts.convertApostrophes }` ); if (!opts.convertApostrophes) { applicableOpts.convertEntities = true; console.log( `1980 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); rangesArr.push(i, y, opts.convertEntities ? `&quot;` : `"`); console.log( `1986 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${JSON.stringify( opts.convertEntities ? `&quot;` : `"`, null, 0 )}]` ); } else if (opts.convertEntities) { applicableOpts.convertEntities = true; console.log( `1995 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); rangesArr.push(i, y, "&rdquo;"); console.log( `2001 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "&rdquo;"]` ); } } else if (charcode === 8230) { // IF UNENCODED HORIZONTAL ELLIPSIS CHARACTER &hellip; applicableOpts.convertDotsToEllipsis = true; console.log( `2008 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertDotsToEllipsis = ${ applicableOpts.convertDotsToEllipsis }` ); if (!opts.convertDotsToEllipsis) { rangesArr.push(i, y, "..."); console.log( `2016 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "..."]` ); } else { applicableOpts.convertEntities = true; console.log( `2021 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); if (opts.convertEntities) { rangesArr.push(i, y, "&hellip;"); console.log( `2029 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "&hellip;"]` ); } } } else if (charcode === 65279) { // IF BOM, '\uFEFF' rangesArr.push(i, y); console.log( `2037 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}]` ); } else { console.log( `2041 processCharacter.js - ${`\u001b[${90}m${`else clause leading to encode`}\u001b[${39}m`}` ); // // // ENCODE (on by default, but can be turned off) // // if ( !applicableOpts.dontEncodeNonLatin && doConvertEntities(str[i], true) !== doConvertEntities(str[i], false) ) { applicableOpts.dontEncodeNonLatin = true; console.log( `2055 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.dontEncodeNonLatin = ${ applicableOpts.dontEncodeNonLatin }` ); } // try to convert the current character into HTML entities. let convertedCharVal = doConvertEntities( str[i], opts.dontEncodeNonLatin ); console.log( `2067 processCharacter.js - ${`\u001b[${33}m${`convertedCharVal`}\u001b[${39}m`} = ${JSON.stringify( convertedCharVal, null, 4 )}` ); if ( Object.keys(notEmailFriendly).includes( convertedCharVal.slice(1, convertedCharVal.length - 1) ) ) { convertedCharVal = `&${ notEmailFriendly[ convertedCharVal.slice(1, convertedCharVal.length - 1) ] };`; } console.log( `2085 processCharacter.js - ${`\u001b[${33}m${`convertedCharVal`}\u001b[${39}m`} = ${JSON.stringify( convertedCharVal, null, 4 )}` ); // 2. If the result is different from the original character, this means // that this character needs to be encoded. We will submit this character's // range up for replacement. if (str[i] !== convertedCharVal) { applicableOpts.convertEntities = true; console.log( `2097 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); if (opts.convertEntities) { if (convertedCharVal === "&mldr;") { console.log( `2105 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, "&hellip;"]` ); rangesArr.push(i, y, "&hellip;"); } else if (convertedCharVal !== "&apos;") { console.log( `2110 processCharacter.js - ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} [${i}, ${y}, ${convertedCharVal}]` ); rangesArr.push(i, y, convertedCharVal); } applicableOpts.convertEntities = true; console.log( `2117 processCharacter.js: ${`\u001b[${32}m${`SET`}\u001b[${39}m`} applicableOpts.convertEntities = ${ applicableOpts.convertEntities }` ); } } } } if (state.onUrlCurrently && !str[i].trim()) { console.log( `2128 SET ${`\u001b[${33}m${`state.onUrlCurrently`}\u001b[${39}m`} = false` ); state.onUrlCurrently = false; } // // // // // // // } console.log( `2143 processCharacter.js - ${`\u001b[${32}m${`finally`}\u001b[${39}m`}, rangesArr = ${JSON.stringify( rangesArr.current(), null, 4 )}` ); } export { processCharacter };
the_stack
import {Component, DoCheck, EventEmitter, OnDestroy, OnInit, Output, ViewChild} from '@angular/core'; import {HyperParametersComponent} from './hyper-parameters/hyper-parameters.component'; import {PrepareDatasetsComponent} from './prepare-datasets/prepare-datasets.component'; import {ContainerSettingsComponent} from './container-settings/container-settings.component'; import {MatSnackBar, MatStepper} from '@angular/material'; import {DataValidatorService} from '../../../Services/data-validator.service'; import {IgeneralSettings} from '../../../Interfaces/Igeneral-settings'; import {IHyperParameters} from '../../../Interfaces/IHyperParameters'; import {IPrepareDataSet} from '../../../Interfaces/prepare-data-set'; import {HttpErrorResponse, HttpResponse} from '@angular/common/http'; import {throwError} from 'rxjs'; import {Config} from 'codelyzer'; import {DataGetter} from '../../../Services/data-getter.service'; import {AdvancedHyperParametersComponent} from './advanced-hyper-parameters/advanced-hyper-parameters.component'; import {AdvancedHyperParameters} from '../../../Interfaces/advanced-hyper-parameters'; import {ConfigFileManagerService} from '../../../Services/config-file-manager.service'; import {JobsService} from '../../../Services/jobs.service'; import {Ijob} from '../../../Interfaces/ijob'; import {Router} from '@angular/router'; import {delay} from 'rxjs/operators'; import {FormControl, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'app-create-job', templateUrl: './create-job.component.html', styleUrls: ['./create-job.component.css'] }) export class CreateJobComponent implements OnInit , DoCheck , OnDestroy { // tslint:disable-next-line:max-line-length constructor(private dataValidatorService: DataValidatorService, private snackBar: MatSnackBar, private gpuGetterService: DataGetter, private configFileManager: ConfigFileManagerService, private JobService: JobsService, private router: Router ) {} // @ts-ignore @ViewChild(HyperParametersComponent) hyperParameters: HyperParametersComponent; // @ts-ignore @ViewChild(AdvancedHyperParametersComponent) advancedHyperParameters: AdvancedHyperParametersComponent; // @ts-ignore @ViewChild(PrepareDatasetsComponent) prepareDataset: PrepareDatasetsComponent; // @ts-ignore @ViewChild(ContainerSettingsComponent) containerSettings: ContainerSettingsComponent; @Output() pageTitleOutput = new EventEmitter<string>(); step = 0; pageTitle = 'Create Job'; hyperParameterData: IHyperParameters; advancedHyperParameterData: AdvancedHyperParameters; configFile = ''; prepareDataSetData: IPrepareDataSet; generalSettingsData: IgeneralSettings; stepCompleted = false; nextButtonClicked = false; availableGPUs: number[]; showImageControl = true; advancedOptions = false; networkArchitectureThatDoesntRequireImageControl = ['frcnn_resnet_50', 'frcnn_resnet_101']; defaultHyperParameters: IHyperParameters; jobs: string[]; downloadableModels: string[] = []; firstStepEditable = false; ngOnInit() { this.pageTitleOutput.emit(this.pageTitle); } ngDoCheck(): void { if ( this.prepareDataset.sendRequest === true) { this.dataValidatorService.getLabelsType(this.prepareDataset.FieldControl.value.datasetFolder).subscribe( message => { this.prepareDataset.labelTypes = message; } , error => { this.prepareDataset.labelTypes = []; this.snackBar.open('Invalid dataset' , '' , {duration: 2000, panelClass: 'redSnackBar'}); }); } } ngOnDestroy(): void { this.JobService.runningDatasetFolder.next(''); this.JobService.runningNetworkArchitecture.next(''); this.JobService.runningJobName.next(''); this.configFileManager.resetEnteringCreateJobComponent.next(0); // this.configFileManager.resetEnteringCreateJobComponentAvancedHyperParameters.next(0); } prepareDatasetValidator() { if (this.prepareDataset.validateData() && !this.nextButtonClicked) { // this.firstStepEditable = true; this.JobService.runningDatasetFolder.next(this.prepareDataset.FieldControl.value.datasetFolder); this.nextButtonClicked = true; this.stepCompleted = false; this.dataValidatorService.sendDatasetInfo(this.prepareDataSetData).subscribe((message: HttpResponse<Config>) => { // @ts-ignore if (message === true) { this.snackBar.open('Success !', '', {duration: 5000, panelClass: 'greenSnackBar'}); // getting Valid gPUs this.gpuGetterService.getAvailableGPUs().subscribe((AvailableGPUsResponse: number[]) => { this.availableGPUs = AvailableGPUsResponse; }, error1 => this.handleError(error1)); this.gpuGetterService.getAvailableNetworks().subscribe((AvailableNetworks: string[]) => { this.containerSettings.networksList = AvailableNetworks; this.stepCompleted = true; setTimeout(() => { this.advanceStep(); }, 100); }, error => this.handleError(error)); } else { this.nextButtonClicked = false; this.snackBar.open('Invalid Dataset !', '', {duration: 5000, panelClass: 'redSnackBar'}); } }, error2 => this.handleError(error2) ); } } generalSettingsValidator() { if (this.containerSettings.validateData() && !this.nextButtonClicked) { // this.firstStepEditable = false; this.JobService.runningJobName.next(this.containerSettings.FieldControl.value.containerName); this.JobService.runningNetworkArchitecture.next(this.containerSettings.FieldControl.value.networkArchitecture); this.nextButtonClicked = true; this.dataValidatorService.startJob(this.generalSettingsData).subscribe((startJobResponse: HttpResponse<Config>) => { this.dataValidatorService.create_pbtxt().subscribe((responseMessage: HttpResponse<Config>) => { this.dataValidatorService.create_tfrecord().subscribe((message: HttpResponse<Config>) => { this.testIfImageControlIsAvailable(this.generalSettingsData.networkArchitecture); this.getHyperParametersDefaultValues(); this.JobService.getAllJobs().subscribe((jobs: string[]) => { this.jobs = jobs; this.JobService.jobs.next(jobs); this.JobService.getDownloadableModels().subscribe((models: string[]) => { this.downloadableModels = models; this.JobService.downloadableModels.next(models); }, error => this.handleError(error)); }, error => this.handleError(error)); }, error2 => this.handleError(error2)); }, error1 => this.handleError(error1)); }, startJobError => this.handleError(startJobError)); } else { this.snackBar.open('Please enter all the required values', '', {duration: 3000, panelClass: 'redSnackBar'}); } } getHyperParametersDefaultValues() { this.gpuGetterService.getDefaultValues(this.generalSettingsData.networkArchitecture, this.generalSettingsData.APIPort).subscribe((defaultValue: IHyperParameters) => { // console.log('defaultValue', defaultValue); this.defaultHyperParameters = defaultValue; this.stepCompleted = true; setTimeout(() => { this.advanceStep(); }, 100); }, error1 => this.handleError(error1)); } hyperParametersValidator() { if (this.advancedOptions) { if (this.advancedHyperParameters.validateData() && !this.nextButtonClicked) { this.nextButtonClicked = true; // tslint:disable-next-line:max-line-length if (Array.isArray(this.advancedHyperParameterData.content)) { this.advancedHyperParameterData.content = this.advancedHyperParameterData.content[0]; } // tslint:disable-next-line:max-line-length this.dataValidatorService.advancedHyperParametersValidator(this.advancedHyperParameterData).subscribe((message: HttpResponse<Config>) => { this.stepCompleted = true; setTimeout(() => { this.advanceStep(); }, 100); this.snackBar.open(this.generalSettingsData.containerName + ' Started on GPU ' + this.generalSettingsData.gPUs, '', {duration: 6000, panelClass: 'greenBar'}); }, error2 => this.handleError(error2)); } } else { if (this.hyperParameters.validateData() && !this.nextButtonClicked) { this.nextButtonClicked = true; this.dataValidatorService.hyperParametersValidator(this.hyperParameterData).subscribe((message: HttpResponse<Config>) => { this.stepCompleted = true; setTimeout(() => { this.nextButtonClicked = false; document.getElementById('hyperParametersNextButton').click(); this.stepCompleted = false; }, 100); this.snackBar.open(this.generalSettingsData.containerName + ' Started on GPU ' + this.generalSettingsData.gPUs, '', {duration: 6000, panelClass: 'greenBar'}); }, error2 => this.handleError(error2)); } } } handleError(errorResponse: HttpErrorResponse) { this.nextButtonClicked = false; if (errorResponse.status === 404) { // A client-side or network error occurred. Handle it accordingly. this.snackBar.open('API unreachable', '', {duration: 3000, panelClass: 'redSnackBar'}); } if (errorResponse.status === 400) { this.snackBar.open('Bad Request', '', {duration: 3000, panelClass: 'redSnackBar'}); } if (errorResponse.status === 422) { this.snackBar.open('Validation error', '', {duration: 3000, panelClass: 'redSnackBar'}); } if (errorResponse.status === 500) { this.snackBar.open('internal server error', '', {duration: 3000, panelClass: 'redSnackBar'}); } else { this.snackBar.open(errorResponse.message, '', {duration: 3000, panelClass: 'redSnackBar'}); } return throwError( 'Something bad happened; please try again later.'); } testIfImageControlIsAvailable(networkArchitecture) { if (this.networkArchitectureThatDoesntRequireImageControl.includes(networkArchitecture)) { this.showImageControl = false; this.dataValidatorService.sendImageControl = false; } else { this.dataValidatorService.sendImageControl = true; } } advanceOptionToggle() { const apiPort = +this.generalSettingsData.APIPort; console.log('the api port field is : ', this.generalSettingsData.APIPort); console.log('the api port field is : ', apiPort); this.configFileManager.getConfigFile(apiPort, this.generalSettingsData.networkArchitecture).subscribe((configFile: object) => { // @ts-ignore this.configFile = configFile.content; this.advancedOptions = !this.advancedOptions; }); } advanceStep() { if (this.step === 2) { document.getElementById('hyperParametersNextButton').click(); } this.step++; this.nextButtonClicked = false; document.getElementById('NextButton').click(); this.stepCompleted = false; } cancelJob() { this.nextButtonClicked = true; this.JobService.getAllJobs().subscribe((jobs: string[]) => { this.jobs = jobs; this.JobService.jobs.next(jobs); this.JobService.getDownloadableModels().subscribe((models: string[]) => { this.downloadableModels = models; this.JobService.downloadableModels.next(models); const job: Ijob = { name: this.jobs[0] }; this.JobService.stopJob(job).subscribe(() => { this.nextButtonClicked = false; this.snackBar.open('Job Deleted !', '', {duration: 4000}); this.router.navigate(['/training']); }, error => this.handleError(error)); }, error => this.handleError(error)); }, error => this.handleError(error)); } openHome() { window.open('training'); } goBackStepper() { this.firstStepEditable = true; setTimeout(() => { this.step = 0; this.firstStepEditable = false; }, 1); } }
the_stack
import { buildWhereClauseExpr, getDefaultInstance, LetExprType, LogicalWhereExpr, Query, WhereClauseException, Schema, model, } from '../src'; import { verifyWhereObjectKey } from '../src/query/helpers/builders'; import { bucketName, startInTest } from './testData'; describe('Collection operators', () => { test(`-> build where clause CollectionDeepSearchOperator with array target expression`, async () => { const whereIn = buildWhereClauseExpr('', { country: { $in: ['United Kingdom'] } }); const whereWithin = buildWhereClauseExpr('', { country: { $within: ['United Kingdom'] } }); const whereNotIn = buildWhereClauseExpr('', { country: { $notIn: ['United Kingdom'] } }); const whereNotWithin = buildWhereClauseExpr('', { country: { $notWithin: ['United Kingdom'] } }); expect(whereIn).toBe(`country IN ["United Kingdom"]`); expect(whereWithin).toBe(`country WITHIN ["United Kingdom"]`); expect(whereNotIn).toBe(`country NOT IN ["United Kingdom"]`); expect(whereNotWithin).toBe(`country NOT WITHIN ["United Kingdom"]`); }); test(`-> build where clause CollectionDeepSearchOperator with string target expression`, async () => { const whereIn = buildWhereClauseExpr('', { country: { $in: { $field: 'address' } } }); const whereWithin = buildWhereClauseExpr('', { country: { $within: { $field: 'address' } } }); const whereNotIn = buildWhereClauseExpr('', { country: { $notIn: { $field: 'address' } } }); const whereNotWithin = buildWhereClauseExpr('', { country: { $notWithin: { $field: 'address' } } }); expect(whereIn).toBe(`country IN address`); expect(whereWithin).toBe(`country WITHIN address`); expect(whereNotIn).toBe(`country NOT IN address`); expect(whereNotWithin).toBe(`country NOT WITHIN address`); }); test(`-> build where clause CollectionRangePredicateOperator required $expr and $satisfies props`, async () => { const where = { $any: { $dummyExpr: [{ departure: { $in: 'schedule' } }], $dummySatisfies: { 'departure.day': { $gt: 0 } }, }, }; expect(() => buildWhereClauseExpr('', where)).toThrowError( `Range predicate operator '$any' only allow required properties '$expr' and '$satisfies'. Properties ['$dummyExpr', '$dummySatisfies'] are not valid.`, ); }); test(`-> build where clause CollectionRangePredicateOperator many expression defined`, async () => { const where = { $any: { $expr: [{ departure: { $in: 'schedule' }, dummyExpr: { $within: [5] } }], $satisfies: { 'departure.day': { $gt: 0 } }, }, }; expect(() => buildWhereClauseExpr('', where)).toThrowError( `More than one property have been defined for range predicate 'ANY' as variable name in the same IN/WITHIN expression. You should select only one of the following 'departure'|'dummyExpr'.`, ); }); test(`-> build where clause CollectionRangePredicateOperator simple`, async () => { // ANY basic expression const where1 = buildWhereClauseExpr('', { $any: { $expr: [{ departure: { $in: 'schedule' } }], $satisfies: { 'departure.day': { $gt: 0 } }, }, }); // ANY with satisfies target IN/WITHIN value const where2 = buildWhereClauseExpr('', { $any: { $expr: [{ departure: { $in: 'schedule' } }], $satisfies: { 'departure.day': { $in: [0] } }, }, }); // ANY with satisfies target literal expression value const where3 = buildWhereClauseExpr('', { $any: { $expr: [{ departure: { $in: 'schedule' } }], $satisfies: { 'departure.utc': { $gt: '03:53' } }, }, }); // ANY with multiple search expression const where4 = buildWhereClauseExpr('', { $any: { $expr: [{ departure: { $in: 'schedule' } }, { distance: { $within: '_default' } }], $satisfies: { $and: [{ 'departure.utc': { $gt: '03:53' } }, { distance: { $gte: 2000 } }] }, }, }); // ANY with multiple search expression with one array const where5 = buildWhereClauseExpr('', { $any: { $expr: [ { departure: { $in: 'schedule' } }, { distance: { $within: '_default' } }, { other: { $in: ['KL', 'AZ'] } }, ], $satisfies: { $and: [{ 'departure.utc': { $gt: '03:53' } }, { distance: { $gte: 2000 } }, { other: { $field: 'airline' } }], }, }, }); expect(where1).toBe('ANY departure IN schedule SATISFIES departure.day>0 END'); expect(where2).toBe('ANY departure IN schedule SATISFIES departure.day IN [0] END'); expect(where3).toBe('ANY departure IN schedule SATISFIES departure.utc>"03:53" END'); expect(where4).toBe( 'ANY departure IN schedule,distance WITHIN _default SATISFIES (departure.utc>"03:53" AND distance>=2000) END', ); expect(where5).toBe( 'ANY departure IN schedule,distance WITHIN _default,other IN ["KL","AZ"] SATISFIES (departure.utc>"03:53" AND distance>=2000 AND other=airline) END', ); }); test(`-> build where clause $field option`, async () => { const where1 = buildWhereClauseExpr('', { other: { $field: 'address' } }); const where2 = buildWhereClauseExpr('', { other: { $in: { $field: 'address' } } }); const where3 = buildWhereClauseExpr('', { other: { $gt: { $field: 'address' } } }); const where4 = buildWhereClauseExpr('', { other: { $like: { $field: 'address' } } }); expect(where1).toBe('other=address'); expect(where2).toBe('other IN address'); expect(where3).toBe('other>address'); expect(where4).toBe('other LIKE address'); }); test(`-> build where clause verifyWhereObjectKey`, async () => { ['$and', '$or', '$not', '$any', '$every', 'address', 'position'].forEach((value) => expect(() => verifyWhereObjectKey({ [value]: {} })).toBeTruthy(), ); ['$in', '$eq', '$like'].forEach((value) => expect(() => verifyWhereObjectKey({ [value]: {} })).toThrow(WhereClauseException), ); }); /** * @example https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/collectionops.html#collection-op-in * @example https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/collectionops.html#collection-op-within **/ test('-> CollectionDeepSearchOperator in Query builder', async () => { const where: LogicalWhereExpr = { type: 'airline', country: { $in: ['United Kingdom', 'France'] }, [`"CORSAIR"`]: { $within: { $field: 't' } }, }; const query = new Query({}, `${bucketName} t`).select('name,country,id').where(where).build(); const ottoman = getDefaultInstance(); await startInTest(ottoman); const response = await ottoman.query(query); expect(query).toStrictEqual( `SELECT name,country,id FROM \`${bucketName}\` t WHERE type="airline" AND country IN ["United Kingdom","France"] AND "CORSAIR" WITHIN t`, ); expect(response.rows).toStrictEqual([ { country: 'France', id: 1908, name: 'Corsairfly', }, ]); }); /** * @example https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/collectionops.html#collection-op-any **/ test(`-> Range predicate ANY with CollectionDeepSearchOperator ( IN | WITHIN ) in a Query builder and execution`, async () => { const selectExpr = 'airline,airlineid,destinationairport,distance'; const letExpr: LetExprType = { destination: ['ATL'] }; const whereExpr: LogicalWhereExpr = { type: { $eq: 'route' }, $and: [ { sourceairport: { $eq: 'ABQ' } }, { $any: { $expr: [{ departure: { $in: 'schedule' } }, { other: { $within: ['KL', 'AZ'] } }], $satisfies: { $and: [{ 'departure.utc': { $gt: '03:53' } }, { other: { $field: 'airline' } }], }, }, }, { destinationairport: { $in: { $field: 'destination' } } }, ], }; const query = new Query({}, 'travel-sample').select(selectExpr).let(letExpr).where(whereExpr).build(); const ottoman = getDefaultInstance(); await startInTest(ottoman); const response = await ottoman.query(query); expect(response.rows).toStrictEqual([ { airline: 'AZ', airlineid: 'airline_596', destinationairport: 'ATL', distance: 2038.3535078909663, }, { airline: 'KL', airlineid: 'airline_3090', destinationairport: 'ATL', distance: 2038.3535078909663, }, ]); }); /** * @example https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/collectionops.html#collection-op-every **/ test(`-> Range predicate EVERY with CollectionDeepSearchOperator ( IN | WITHIN ) in a Query builder and execution`, async () => { const selectExpr = 'airline,airlineid,destinationairport,distance'; const whereExpr: LogicalWhereExpr = { type: { $eq: 'route' }, $and: [ { airline: { $eq: 'KL' } }, { sourceairport: { $like: 'ABQ' } }, { destinationairport: { $in: ['ATL'] } }, { $every: { $expr: [{ departure: { $in: 'schedule' } }], $satisfies: { 'departure.utc': { $gt: '00:35' } }, }, }, ], }; const query = new Query({}, 'travel-sample').select(selectExpr).where(whereExpr).build(); const ottoman = getDefaultInstance(); await startInTest(ottoman); const response = await ottoman.query(query); expect(query).toBe( `SELECT airline,airlineid,destinationairport,distance FROM \`travel-sample\` WHERE type="route" AND (airline="KL" AND sourceairport LIKE "ABQ" AND destinationairport IN ["ATL"] AND EVERY departure IN schedule SATISFIES departure.utc>"00:35" END)`, ); expect(response.rows).toStrictEqual([ { airline: 'KL', airlineid: 'airline_3090', destinationairport: 'ATL', distance: 2038.3535078909663, }, ]); }); test(`-> Using data model structure vs Query builder`, async () => { const airlineSchema = new Schema({ callsign: String, country: String, iata: String, icao: String, id: Number, name: String, type: String, }); const collectionName = 'airline'; const Airline = model(collectionName, airlineSchema, { modelKey: 'type' }); const ottoman = getDefaultInstance(); await startInTest(ottoman); const response1 = await Airline.find( { type: 'airline', $and: [{ country: { $in: ['United Kingdom', 'France'] } }], callsign: { $isNotNull: true }, $any: { $expr: [{ description: { $within: ['EU'] } }], $satisfies: { icao: { $like: { $field: '"%"||description' } } }, }, }, { limit: 2, select: 'country,icao,name', lean: true }, ); let fromClause = `\`${bucketName}\``; if (!process.env.OTTOMAN_LEGACY_TEST) { fromClause = `\`${bucketName}\`.\`_default\`.\`${collectionName}\``; } const query = new Query({ select: 'country,icao,name' }, fromClause) .where({ type: 'airline', $and: [{ country: { $in: ['United Kingdom', 'France'] } }], callsign: { $isNotNull: true }, $any: { $expr: [{ description: { $within: ['EU'] } }], $satisfies: { icao: { $like: { $field: '"%"||description' } } }, }, }) .limit(2) .build(); const response2 = await ottoman.query(query); const response3 = await Airline.find({ $and: [{ country: { $in: 'United Kingdom' } }] }); expect(response3.rows).toStrictEqual([]); expect(query).toBe( `SELECT country,icao,name FROM ${fromClause} WHERE type="airline" AND (country IN ["United Kingdom","France"]) AND callsign IS NOT NULL AND ANY description WITHIN ["EU"] SATISFIES icao LIKE "%"||description END LIMIT 2`, ); expect(response1.rows).toStrictEqual(response2.rows); }); });
the_stack
import crypto from 'crypto'; import { StarkwareLib } from '@dydxprotocol/starkex-eth'; import { ApiMethod, KeyPair, OrderWithClientId, SignableOrder, SignableWithdrawal, asEcKeyPair, asSimpleKeyPair, SignableConditionalTransfer, SignableTransfer, nonceFromClientId, TransferParams as StarklibTransferParams, } from '@dydxprotocol/starkex-lib'; import _ from 'lodash'; import { generateQueryPath, generateRandomClientId } from '../helpers/request-helpers'; import { RequestMethod, axiosRequest, } from '../lib/axios'; import { getAccountId } from '../lib/db'; import { AccountAction, AccountLeaderboardPnlResponseObject, AccountResponseObject, ApiFastWithdrawal, ApiFastWithdrawalParams, ApiKeyCredentials, ApiOrder, ApiTransfer, ApiWithdrawal, Data, FillResponseObject, FundingResponseObject, GenericParams, HistoricalPnlResponseObject, ISO8601, ISO31661ALPHA2, LeaderboardPnlPeriod, LiquidityProviderRewardsResponseObject, Market, OrderResponseObject, OrderSide, OrderStatus, OrderType, PartialBy, PositionResponseObject, PositionStatus, Provider, RetroactiveMiningRewardsResponseObject, TradingRewardsResponseObject, TransferParams, TransferResponseObject, UserResponseObject, ActiveOrderResponseObject, } from '../types'; import Clock from './clock'; // TODO: Figure out if we can get rid of this. const METHOD_ENUM_MAP: Record<RequestMethod, ApiMethod> = { [RequestMethod.DELETE]: ApiMethod.DELETE, [RequestMethod.GET]: ApiMethod.GET, [RequestMethod.POST]: ApiMethod.POST, [RequestMethod.PUT]: ApiMethod.PUT, }; const collateralTokenDecimals = 6; export default class Private { readonly host: string; readonly apiKeyCredentials: ApiKeyCredentials; readonly networkId: number; readonly starkLib: StarkwareLib; readonly starkKeyPair?: KeyPair; readonly clock: Clock; constructor({ host, apiKeyCredentials, starkPrivateKey, networkId, clock, }: { host: string, apiKeyCredentials: ApiKeyCredentials, networkId: number, starkPrivateKey?: string | KeyPair, clock: Clock, }) { this.host = host; this.apiKeyCredentials = apiKeyCredentials; this.networkId = networkId; this.starkLib = new StarkwareLib({} as Provider, networkId); if (starkPrivateKey) { this.starkKeyPair = asSimpleKeyPair(asEcKeyPair(starkPrivateKey)); } this.clock = clock; } // ============ Request Helpers ============ protected async request( method: RequestMethod, endpoint: string, data?: {}, ): Promise<Data> { const requestPath = `/v3/${endpoint}`; const isoTimestamp: ISO8601 = this.clock.getAdjustedIsoString(); const headers = { 'DYDX-SIGNATURE': this.sign({ requestPath, method, isoTimestamp, data, }), 'DYDX-API-KEY': this.apiKeyCredentials.key, 'DYDX-TIMESTAMP': isoTimestamp, 'DYDX-PASSPHRASE': this.apiKeyCredentials.passphrase, }; return axiosRequest({ url: `${this.host}${requestPath}`, method, data, headers, }); } protected async _get( endpoint: string, params: {}, ): Promise<Data> { return this.request(RequestMethod.GET, generateQueryPath(endpoint, params)); } protected async post( endpoint: string, data: {}, ): Promise<Data> { return this.request(RequestMethod.POST, endpoint, data); } protected async put( endpoint: string, data: {}, ): Promise<Data> { return this.request(RequestMethod.PUT, endpoint, data); } protected async delete( endpoint: string, params: {}, ): Promise<Data> { return this.request(RequestMethod.DELETE, generateQueryPath(endpoint, params)); } // ============ Requests ============ async get(endpoint: string, params: {}): Promise<Data> { return this._get( endpoint, params, ); } /** * @description get a signature for the ethereumAddress if registered */ async getRegistration(genericParams: GenericParams = {}): Promise<{ signature: string }> { return this._get( 'registration', { ...genericParams, }, ); } /** * @description get the user associated with the ethereumAddress */ async getUser(genericParams: GenericParams = {}): Promise<{ user: UserResponseObject }> { return this._get( 'users', { ...genericParams, }, ); } /** * @description update information for the user * * @param { * @userData specifiying information about the user * @email associated with the user * @username for the user * @isSharingUsername if the user wants their username publicly shared * @isSharingAddress if the user wants their ethereumAddress publicly shared * @country for the user (ISO 3166-1 Alpha-2 Compliant) * } */ async updateUser({ userData, email, username, isSharingUsername, isSharingAddress, country, }: { userData: {}, email?: string | null, username?: string, isSharingUsername?: boolean, isSharingAddress?: boolean, country?: ISO31661ALPHA2, }): Promise<{ user: UserResponseObject }> { return this.put( 'users', { email, username, isSharingUsername, isSharingAddress, userData: JSON.stringify(userData), country, }, ); } /** * @description create an account for an ethereumAddress * * @param starkKey for the account that will be used as the public key in starkwareEx-Lib requests * going forward for this account. * @param starkKeyYCoordinate for the account that will be used as the Y coordinate for the public * key in starkwareEx-Lib requests going forward for this account. */ async createAccount( starkKey: string, starkKeyYCoordinate: string, ): Promise<{ account: AccountResponseObject }> { return this.post( 'accounts', { starkKey, starkKeyYCoordinate, }, ); } /** * @description get account associated with an ethereumAddress and accountNumber 0 * * @param ethereumAddress the account is associated with */ async getAccount( ethereumAddress: string, genericParams: GenericParams = {}, ): Promise<{ account: AccountResponseObject }> { return this._get( `accounts/${getAccountId({ address: ethereumAddress })}`, { ...genericParams }, ); } /** * @description get all accounts associated with an ethereumAddress */ async getAccounts( genericParams: GenericParams = {}, ): Promise<{ accounts: AccountResponseObject[] }> { return this._get( 'accounts', { ...genericParams }, ); } /** * @description get leaderboard pnl for period and accountNumber 0 * * @param period the period of pnls to retrieve */ async getAccountLeaderboardPnl( period: LeaderboardPnlPeriod, params: { startedBeforeOrAt?: ISO8601, }, genericParams: GenericParams = {}, ): Promise<{ leaderboardPnl: AccountLeaderboardPnlResponseObject }> { return this._get( `accounts/leaderboard-pnl/${period}`, { ...params, ...genericParams, }, ); } /** * @description get all positions for an account, meeting query parameters * * @param { * @market the positions are for * @status of the positions * @limit to the number of positions returned * @createdBeforeOrAt latest the positions could have been created * } */ async getPositions( params: { market?: Market, status?: PositionStatus, limit?: number, createdBeforeOrAt?: ISO8601, }, genericParams: GenericParams = {}, ): Promise<{ positions: PositionResponseObject[] }> { return this._get( 'positions', { ...params, ...genericParams, }, ); } /** * @description get orders for a user by a set of query parameters * * @param { * @market the orders are for * @status the orders have * @side of the book the orders are on * @type of order * @limit to the number of orders returned * @createdBeforeOrAt sets the time of the last fill that will be received * @returnLatestOrders returns the latest orders instead of the oldest and the order is * from most recent to least recent (up to limit) * } */ async getOrders( params: { market?: Market, status?: OrderStatus, side?: OrderSide, type?: OrderType, limit?: number, createdBeforeOrAt?: ISO8601, returnLatestOrders?: boolean, } = {}, genericParams: GenericParams = {}, ): Promise<{ orders: OrderResponseObject[] }> { return this._get( 'orders', { ...params, ...genericParams, }, ); } /** * @description get active orders (PENDING, OPEN, UNTRIGGERED) for a user by a set of query * parameters - if id is included then side is required * * @param { * @market the orders are for * @side of the book the orders are on * @id of the order * } */ async getActiveOrders( market: Market, side?: OrderSide, id?: string, genericParams: GenericParams = {}, ): Promise<{ orders: ActiveOrderResponseObject[] }> { return this._get( 'active-orders', { market, side, id, ...genericParams, }, ); } /** * @description get an order by a unique id * * @param orderId of the order */ async getOrderById( orderId: string, genericParams: GenericParams = {}, ): Promise<{ order: OrderResponseObject }> { return this._get( `orders/${orderId}`, { ...genericParams }, ); } /** * @description get an order by a clientId * * @param clientId of the order */ async getOrderByClientId( clientId: string, genericParams: GenericParams = {}, ): Promise<{ order: OrderResponseObject }> { return this._get( `orders/client/${clientId}`, { ...genericParams }, ); } /** *@description place a new order * * @param { * @market of the order * @side of the order * @type of the order * @timeInForce of the order * @postOnly of the order * @size of the order * @price of the order * @limitFee of the order * @expiration of the order * @cancelId if the order is replacing an existing one * @triggerPrice of the order if the order is a triggerable order * @trailingPercent of the order if the order is a trailing stop order * } * @param positionId associated with the order */ async createOrder( params: PartialBy<ApiOrder, 'clientId' | 'signature'>, positionId: string, ): Promise<{ order: OrderResponseObject }> { const clientId = params.clientId || generateRandomClientId(); let signature: string | undefined = params.signature; if (!signature) { if (!this.starkKeyPair) { throw new Error('Order is not signed and client was not initialized with starkPrivateKey'); } const orderToSign: OrderWithClientId = { humanSize: params.size, humanPrice: params.price, limitFee: params.limitFee, market: params.market, side: params.side, expirationIsoTimestamp: params.expiration, clientId, positionId, }; const starkOrder = SignableOrder.fromOrder(orderToSign, this.networkId); signature = await starkOrder.sign(this.starkKeyPair); } const order: ApiOrder = { ...params, clientId, signature, }; return this.post( 'orders', order, ); } /** * @description cancel a specific order for a user by the order's unique id * * @param orderId of the order being canceled */ async cancelOrder(orderId: string): Promise<{ cancelOrder: OrderResponseObject }> { return this.delete( `orders/${orderId}`, {}, ); } /** * @description cancel all orders for a user for a specific market * * @param market of the orders being canceled */ async cancelAllOrders(market?: Market): Promise<{ cancelOrders: OrderResponseObject[] }> { const params = market ? { market } : {}; return this.delete( 'orders', params, ); } /** * @description cancel active orders (PENDING, OPEN, UNTRIGGERED) for a user by a set of query * parameters - if id is included then side is required * * @param { * @market the orders are for * @side of the book the orders are on * @id of the order * } */ async cancelActiveOrders( market: Market, side?: OrderSide, id?: string, genericParams: GenericParams = {}, ): Promise<{ cancelOrders: ActiveOrderResponseObject[] }> { return this.delete( 'active-orders', { market, side, id, ...genericParams, }, ); } /** *@description get fills for a user by a set of query parameters * * @param { * @market the fills are for * @orderId associated with the fills * @limit to the number of fills returned * @createdBeforeOrAt sets the time of the last fill that will be received * } */ async getFills( params: { market?: Market, orderId?: string, limit?: number, createdBeforeOrAt?: ISO8601, }, genericParams: GenericParams = {}, ): Promise<{ fills: FillResponseObject[] }> { return this._get( 'fills', { ...params, ...genericParams, }, ); } /** * @description get transfers for a user by a set of query parameters * * @param { * @type of transfer * @limit to the number of transfers returned * @createdBeforeOrAt sets the time of the last transfer that will be received * } */ async getTransfers( params: { type?: AccountAction, limit?: number, createdBeforeOrAt?: ISO8601, } = {}, genericParams: GenericParams = {}, ): Promise<{ transfers: TransferResponseObject[] }> { return this._get( 'transfers', { ...params, ...genericParams, }, ); } /** * @description post a new withdrawal * * @param { * @amount specifies the size of the withdrawal * @asset specifies the asset being withdrawn * @clientId specifies the clientId for the address * } * @param positionId specifies the associated position for the transfer */ async createWithdrawal( params: PartialBy<ApiWithdrawal, 'clientId' | 'signature'>, positionId: string, ): Promise<{ withdrawal: TransferResponseObject }> { const clientId = params.clientId || generateRandomClientId(); let signature: string | undefined = params.signature; if (!signature) { if (!this.starkKeyPair) { throw new Error( 'Withdrawal is not signed and client was not initialized with starkPrivateKey', ); } const withdrawalToSign = { humanAmount: params.amount, expirationIsoTimestamp: params.expiration, clientId, positionId, }; const starkWithdrawal = SignableWithdrawal.fromWithdrawal(withdrawalToSign, this.networkId); signature = await starkWithdrawal.sign(this.starkKeyPair); } const withdrawal: ApiWithdrawal = { ...params, clientId, signature, }; return this.post( 'withdrawals', withdrawal, ); } /** * @description post a new fast-withdrawal * * @param { * @creditAmount specifies the size of the withdrawal * @debitAmount specifies the amount to be debited * @creditAsset specifies the asset being withdrawn * @toAddress is the address being withdrawn to * @lpPositionId is the LP positionId for the fast withdrawal * @clientId specifies the clientId for the address * @signature starkware specific signature for fast-withdrawal * } */ async createFastWithdrawal( { lpStarkKey, ...params }: PartialBy<ApiFastWithdrawalParams, 'clientId' | 'signature'>, positionId: string, ): Promise<{ withdrawal: TransferResponseObject }> { const clientId = params.clientId || generateRandomClientId(); let signature: string | undefined = params.signature; if (!signature) { if (!this.starkKeyPair) { throw new Error('Fast withdrawal is not signed and client was not initialized with starkPrivateKey'); } const fact = this.starkLib.factRegistry.getTransferErc20Fact({ recipient: params.toAddress, tokenAddress: this.starkLib.collateralToken.getAddress(), tokenDecimals: collateralTokenDecimals, humanAmount: params.creditAmount, salt: nonceFromClientId(clientId), }); const transferToSign = { senderPositionId: positionId, receiverPositionId: params.lpPositionId, receiverPublicKey: lpStarkKey, factRegistryAddress: this.starkLib.factRegistry.getAddress(), fact, humanAmount: params.debitAmount, clientId, expirationIsoTimestamp: params.expiration, }; const starkConditionalTransfer = SignableConditionalTransfer.fromTransfer( transferToSign, this.networkId, ); signature = await starkConditionalTransfer.sign(this.starkKeyPair); } const fastWithdrawal: ApiFastWithdrawal = { ...params, clientId, signature, }; return this.post( 'fast-withdrawals', fastWithdrawal, ); } /** * @description post a new transfer * * @param { * @amount specifies the size of the transfer * @receiverAccountId specifies the receiver account id * @receiverPublicKey specifies the receiver public key * @receiverPositionId specifies the receiver position id * @clientId specifies the clientId for the address * @signature starkware specific signature for the transfer * } * @param positionId specifies the associated position for the transfer */ async createTransfer( params: PartialBy<TransferParams, 'clientId' | 'signature'>, positionId: string, ): Promise<{ transfer: TransferResponseObject }> { const clientId = params.clientId || generateRandomClientId(); let signature: string | undefined = params.signature; if (!signature) { if (!this.starkKeyPair) { throw new Error( 'Transfer is not signed and client was not initialized with starkPrivateKey', ); } const transferToSign: StarklibTransferParams = { humanAmount: params.amount, expirationIsoTimestamp: params.expiration, receiverPositionId: params.receiverPositionId, senderPositionId: positionId, receiverPublicKey: params.receiverPublicKey, clientId, }; const starkTransfer = SignableTransfer.fromTransfer(transferToSign, this.networkId); signature = await starkTransfer.sign(this.starkKeyPair); } const transfer: ApiTransfer = { amount: params.amount, receiverAccountId: params.receiverAccountId, clientId, signature, expiration: params.expiration, }; return this.post( 'transfers', transfer, ); } /** * @description get a user's funding payments by a set of query parameters * * @param { * @market the funding payments are for * @limit to the number of funding payments returned * @effectiveBeforeOrAt sets the latest funding payment received * } */ async getFundingPayments( params: { market?: Market, limit?: number, effectiveBeforeOrAt?: ISO8601, }, genericParams: GenericParams = {}, ): Promise<{ fundingPayments: FundingResponseObject }> { return this._get( 'funding', { ...params, ...genericParams, }, ); } /** * @description get historical pnl ticks for an account between certain times * * @param { * @createdBeforeOrAt latest historical pnl tick being returned * @createdOnOrAfter earliest historical pnl tick being returned * } */ getHistoricalPnl( params: { createdBeforeOrAt?: ISO8601, createdOnOrAfter?: ISO8601, }, genericParams: GenericParams = {}, ): Promise<{ historicalPnl: HistoricalPnlResponseObject[] }> { return this._get( 'historical-pnl', { ...params, ...genericParams, }, ); } /** * @description get trading rewards for a user for a given epoch * * @param { * @epoch to request rewards data for (optional) * } */ getTradingRewards( params: { epoch?: number, }, genericParams: GenericParams = {}, ): Promise<{ tradingRewards: TradingRewardsResponseObject }> { return this._get( 'rewards/weight', { ...params, ...genericParams, }, ); } /** * @description get liquidity provider rewards for a user for a given epoch * * @param { * @epoch to request rewards data for (optional) * } */ getLiquidityProviderRewards( params: { epoch?: number, }, genericParams: GenericParams = {}, ): Promise<{ liquidityRewards: LiquidityProviderRewardsResponseObject }> { return this._get( 'rewards/liquidity', { ...params, ...genericParams, }, ); } /** * @description get retroactive mining rewards for a user for a given epoch * */ getRetroactiveMiningRewards( genericParams: GenericParams = {}, ): Promise<{ retroactiveMiningRewards: RetroactiveMiningRewardsResponseObject }> { return this._get( 'rewards/retroactive-mining', { ...genericParams, }, ); } /** * @description get the key ids associated with an ethereumAddress * */ async getApiKeys( genericParams: GenericParams = {}, ): Promise<{ apiKeys: { key: string }[] }> { return this._get('api-keys', { ...genericParams }); } /** * @description send verification email to email specified by User */ async sendVerificationEmail(): Promise<{}> { return this.put( 'emails/send-verification-email', {}, ); } /** * @description requests tokens on dYdX's staging server. * NOTE: this will not work on Mainnet/Production. */ async requestTestnetTokens(): Promise<{ transfer: TransferResponseObject }> { // Ropsten if (this.networkId !== 3) { throw new Error('Network is not Ropsten'); } return this.post( 'testnet/tokens', {}, ); } // ============ Signing ============ sign({ requestPath, method, isoTimestamp, data, }: { requestPath: string, method: RequestMethod, isoTimestamp: ISO8601, data?: {}, }): string { const messageString: string = ( isoTimestamp + METHOD_ENUM_MAP[method] + requestPath + (_.isEmpty(data) ? '' : JSON.stringify(data)) ); return crypto.createHmac( 'sha256', Buffer.from(this.apiKeyCredentials.secret, 'base64'), ).update(messageString).digest('base64'); } }
the_stack
import { HttpResponse, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs';import { HttpOptions } from './types'; import * as models from './models'; export interface APIClientInterface { /** * Arguments object for method `firestoreProjectsDatabasesDocumentsBatchGet`. */ firestoreProjectsDatabasesDocumentsBatchGetParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.BatchGetDocumentsRequest, /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ database: string, }; /** * Gets multiple documents. * * * Documents returned by this method are not guaranteed to be returned in the * same order that they were requested. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.BatchGetDocumentsResponse>; firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.BatchGetDocumentsResponse>>; firestoreProjectsDatabasesDocumentsBatchGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBatchGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.BatchGetDocumentsResponse>>; /** * Arguments object for method `firestoreProjectsDatabasesDocumentsBeginTransaction`. */ firestoreProjectsDatabasesDocumentsBeginTransactionParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.BeginTransactionRequest, /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ database: string, }; /** * Starts a new transaction. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.BeginTransactionResponse>; firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.BeginTransactionResponse>>; firestoreProjectsDatabasesDocumentsBeginTransaction( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsBeginTransactionParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.BeginTransactionResponse>>; /** * Arguments object for method `firestoreProjectsDatabasesDocumentsCommit`. */ firestoreProjectsDatabasesDocumentsCommitParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.CommitRequest, /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ database: string, }; /** * Commits a transaction, while optionally updating documents. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.CommitResponse>; firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.CommitResponse>>; firestoreProjectsDatabasesDocumentsCommit( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCommitParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.CommitResponse>>; /** * Arguments object for method `firestoreProjectsDatabasesDocumentsListen`. */ firestoreProjectsDatabasesDocumentsListenParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.ListenRequest, /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ database: string, }; /** * Listens to changes. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListenResponse>; firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListenResponse>>; firestoreProjectsDatabasesDocumentsListen( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListenParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListenResponse>>; /** * Arguments object for method `firestoreProjectsDatabasesDocumentsRollback`. */ firestoreProjectsDatabasesDocumentsRollbackParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.RollbackRequest, /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. */ database: string, }; /** * Rolls back a transaction. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Empty>; firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Empty>>; firestoreProjectsDatabasesDocumentsRollback( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRollbackParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Empty>>; /** * Arguments object for method `firestoreProjectsDatabasesDocumentsWrite`. */ firestoreProjectsDatabasesDocumentsWriteParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.WriteRequest, /** * The database name. In the format: * `projects/{project_id}/databases/{database_id}`. * This is only required in the first message. */ database: string, }; /** * Streams batches of document updates and deletes, in order. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.WriteResponse>; firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.WriteResponse>>; firestoreProjectsDatabasesDocumentsWrite( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsWriteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.WriteResponse>>; /** * Arguments object for method `firestoreProjectsDatabasesIndexesDelete`. */ firestoreProjectsDatabasesIndexesDeleteParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, /** * When set to `true`, the target document must exist. * When set to `false`, the target document must not exist. */ currentDocumentExists?: boolean, /** * When set, the target document must exist and have been last updated at * that time. */ currentDocumentUpdateTime?: string, /** * The index name. For example: * `projects/{project_id}/databases/{database_id}/indexes/{index_id}` */ name: string, }; /** * Deletes an index. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Empty>; firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Empty>>; firestoreProjectsDatabasesIndexesDelete( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesDeleteParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Empty>>; /** * Arguments object for method `firestoreProjectsDatabasesIndexesGet`. */ firestoreProjectsDatabasesIndexesGetParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ maskFieldPaths?: string[], /** * The name of the index. For example: * `projects/{project_id}/databases/{database_id}/indexes/{index_id}` */ name: string, /** * Reads the version of the document at the given time. * This may not be older than 60 seconds. */ readTime?: string, /** Reads the document in a transaction. */ transaction?: string, }; /** * Gets an index. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Index>; firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Index>>; firestoreProjectsDatabasesIndexesGet( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesGetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Index>>; /** * Arguments object for method `firestoreProjectsDatabasesDocumentsPatch`. */ firestoreProjectsDatabasesDocumentsPatchParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.Document, /** * When set to `true`, the target document must exist. * When set to `false`, the target document must not exist. */ currentDocumentExists?: boolean, /** * When set, the target document must exist and have been last updated at * that time. */ currentDocumentUpdateTime?: string, /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ maskFieldPaths?: string[], /** * The resource name of the document, for example * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. */ name: string, /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ updateMaskFieldPaths?: string[], }; /** * Updates or inserts a document. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Document>; firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Document>>; firestoreProjectsDatabasesDocumentsPatch( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsPatchParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Document>>; /** * Arguments object for method `firestoreProjectsDatabasesIndexesList`. */ firestoreProjectsDatabasesIndexesListParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, filter?: string, /** The standard List page size. */ pageSize?: number, /** The standard List page token. */ pageToken?: string, /** * The database name. For example: * `projects/{project_id}/databases/{database_id}` */ parent: string, }; /** * Lists the indexes that match the specified filters. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListIndexesResponse>; firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListIndexesResponse>>; firestoreProjectsDatabasesIndexesList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListIndexesResponse>>; /** * Arguments object for method `firestoreProjectsDatabasesIndexesCreate`. */ firestoreProjectsDatabasesIndexesCreateParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.Index, /** * The name of the database this index will apply to. For example: * `projects/{project_id}/databases/{database_id}` */ parent: string, }; /** * Creates the specified index. * A newly created index's initial state is `CREATING`. On completion of the * returned google.longrunning.Operation, the state will be `READY`. * If the index already exists, the call will return an `ALREADY_EXISTS` * status. * * * During creation, the process could result in an error, in which case the * index will move to the `ERROR` state. The process can be recovered by * fixing the data that caused the error, removing the index with * delete, then re-creating the index with * create. * * * Indexes with a single field cannot be created. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Operation>; firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Operation>>; firestoreProjectsDatabasesIndexesCreate( args: Exclude<APIClientInterface['firestoreProjectsDatabasesIndexesCreateParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Operation>>; /** * Arguments object for method `firestoreProjectsDatabasesDocumentsList`. */ firestoreProjectsDatabasesDocumentsListParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, /** * The collection ID, relative to `parent`, to list. For example: `chatrooms` * or `messages`. */ collectionId: string, /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ maskFieldPaths?: string[], /** The order to sort results by. For example: `priority desc, name`. */ orderBy?: string, /** The maximum number of documents to return. */ pageSize?: number, /** The `next_page_token` value returned from a previous List request, if any. */ pageToken?: string, /** * The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ parent: string, /** * Reads documents as they were at the given time. * This may not be older than 60 seconds. */ readTime?: string, /** * If the list should show missing documents. A missing document is a * document that does not exist but has sub-documents. These documents will * be returned with a key but will not have fields, Document.create_time, * or Document.update_time set. * * * Requests with `show_missing` may not specify `where` or * `order_by`. */ showMissing?: boolean, /** Reads documents in a transaction. */ transaction?: string, }; /** * Lists documents. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListDocumentsResponse>; firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListDocumentsResponse>>; firestoreProjectsDatabasesDocumentsList( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListDocumentsResponse>>; /** * Arguments object for method `firestoreProjectsDatabasesDocumentsCreateDocument`. */ firestoreProjectsDatabasesDocumentsCreateDocumentParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.Document, /** The collection ID, relative to `parent`, to list. For example: `chatrooms`. */ collectionId: string, /** * The client-assigned document ID to use for this document. * * Optional. If not specified, an ID will be assigned by the service. */ documentId?: string, /** * The list of field paths in the mask. See Document.fields for a field * path syntax reference. */ maskFieldPaths?: string[], /** * The parent resource. For example: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/chatrooms/{chatroom_id}` */ parent: string, }; /** * Creates a new document. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Document>; firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Document>>; firestoreProjectsDatabasesDocumentsCreateDocument( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsCreateDocumentParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Document>>; /** * Arguments object for method `firestoreProjectsDatabasesDocumentsListCollectionIds`. */ firestoreProjectsDatabasesDocumentsListCollectionIdsParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.ListCollectionIdsRequest, /** * The parent document. In the format: * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ parent: string, }; /** * Lists all the collection IDs underneath a document. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ListCollectionIdsResponse>; firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ListCollectionIdsResponse>>; firestoreProjectsDatabasesDocumentsListCollectionIds( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsListCollectionIdsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ListCollectionIdsResponse>>; /** * Arguments object for method `firestoreProjectsDatabasesDocumentsRunQuery`. */ firestoreProjectsDatabasesDocumentsRunQueryParams?: { /** * - error format * - 1 V1 * - 2 V2 * */ $Xgafv?: models.$Xgafv, /** OAuth access token. */ accessToken?: string, /** * Data format for response. * If not set, server will use the default value: json */ alt?: models.Alt, /** OAuth bearer token. */ bearerToken?: string, /** JSONP */ callback?: string, /** Selector specifying which fields to include in a partial response. */ fields?: string, /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string, /** OAuth 2.0 token for the current user. */ oauthToken?: string, /** * Pretty-print response. * If not set, server will use the default value: true */ pp?: boolean, /** * Returns response with indentations and line breaks. * If not set, server will use the default value: true */ prettyPrint?: boolean, /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string, /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string, /** Upload protocol for media (e.g. "raw", "multipart"). */ uploadProtocol?: string, body?: models.RunQueryRequest, /** * The parent resource name. In the format: * `projects/{project_id}/databases/{database_id}/documents` or * `projects/{project_id}/databases/{database_id}/documents/{document_path}`. * For example: * `projects/my-project/databases/my-database/documents` or * `projects/my-project/databases/my-database/documents/chatrooms/my-chatroom` */ parent: string, }; /** * Runs a query. * Response generated for [ 200 ] HTTP response code. */ firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.RunQueryResponse>; firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.RunQueryResponse>>; firestoreProjectsDatabasesDocumentsRunQuery( args: Exclude<APIClientInterface['firestoreProjectsDatabasesDocumentsRunQueryParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.RunQueryResponse>>; }
the_stack
import { Tabulator } from 'tabulator-tables'; import { View } from './view'; import * as sanitizeHtml from 'sanitize-html'; import { TabularDatabaseModel } from '../model/tabular'; import { Dic, Utils, _, __ } from '../helpers/utils'; import { strings } from '../model/strings'; import { i18n } from '../model/i18n'; import { ContextMenu } from '../helpers/contextmenu'; import { tabulatorGetAllRows, tabulatorTreeChildrenFilter, TabulatorTreeChildrenFilterParams } from '../model/extend-tabulator'; export enum BranchType { Table, Column, Measure, Hierarchy, Folder } export interface Branch { id: string name: string dataType: string type: BranchType isHidden: boolean isInactive?: boolean // It can't be clicked isUnselectable?: boolean // It can't be selected _children?: Branch[] attributes?: any } export enum PlainTreeFilter { ParentOnly, LastChildrenOnly, } interface TabularBrowserFilter { viewAsTree: boolean searchValue: string } export interface TabularBrowserConfig { search?: boolean activable?: boolean selectable?: boolean showSelectionCount?: boolean initialSelected?: string[] noBorders?: boolean placeholder?: string additionalColumns?: Tabulator.ColumnDefinition[] toggableTree?: PlainTreeFilter rowFormatter?: (branch: Branch, element: HTMLElement)=>void } export class TabularBrowser extends View { activeItem: Branch; config: TabularBrowserConfig; table: Tabulator; searchBox: HTMLInputElement; branches: Branch[]; rows: Branch[]; viewAsTree: boolean = true; constructor(id: string, container: HTMLElement, branches: Branch[], config: TabularBrowserConfig) { super(id, container); this.config = config; this.element.classList.add("tabular-browser"); this.branches = branches; this.render(); } get active(): string { return (this.activeItem ? this.activeItem.id : null); } get selected(): string[] { return (this.table ? this.table.getSelectedData().map((item: Branch) => item.id) : null); } render() { let html = ` ${ this.config.search || Utils.Obj.isSet(this.config.toggableTree) ? ` <div class="toolbar"> ${ this.config.search ? ` <div class="search"> <input type="search" placeholder="${i18n(strings.searchPlaceholder)}"> </div> ` : "" } ${ Utils.Obj.isSet(this.config.toggableTree) ? ` <div class="toggle-tree toggle icon-group ${this.viewAsTree ? "active" : ""}" title="${i18n(strings.toggleTree)}"></div> ` : "" } </div> ` : ""} <div class="table"></div> `; this.element.insertAdjacentHTML("beforeend", html); if (this.config.search) { this.searchBox = <HTMLInputElement>_(".tabular-browser .search input", this.element); ["keyup", "search", "paste"].forEach(listener => { this.searchBox.addEventListener(listener, e => { this.applyFilters(); }); }); this.searchBox.addEventListener('contextmenu', e => { e.preventDefault(); let el = <HTMLInputElement>e.currentTarget; if (el.hasAttribute("disabled")) return; let selection = el.value.substring(el.selectionStart, el.selectionEnd); ContextMenu.editorContextMenu(e, selection, el.value, el); }); } if (Utils.Obj.isSet(this.config.toggableTree)) { _(".toggle-tree", this.element).addEventListener("click", e => { e.preventDefault(); this.viewAsTree = !this.viewAsTree; let el = <HTMLElement>e.currentTarget; el.toggleClass("active", this.viewAsTree); this.updateTable(); }); } this.updateTable(); this.table.on("tableBuilt", ()=>{ if (this.config.initialSelected && this.config.initialSelected.length) { this.table.selectRow( tabulatorGetAllRows(this.table).filter( row => this.config.initialSelected.includes((<Branch>row.getData()).name) ) ); } this.trigger("loaded"); }); } update() { this.updateTable(false); } updateTable(redraw = true) { if (redraw) this.destroyTable(); let data = this.branches; if (!this.viewAsTree && Utils.Obj.isSet(this.config.toggableTree)) { if (!this.rows) this.rows = TabularBrowser.ConvertBranchesToRows(this.branches, this.config.toggableTree); data = this.rows; } if (!this.table) { let columns: Tabulator.ColumnDefinition[] = []; if (this.config.selectable) { columns.push({ formatter:"rowSelection", titleFormatter:"rowSelection", titleFormatterParams:{ rowRange:"active" }, hozAlign: "center", headerHozAlign: "center", cssClass: "column-select", headerSort: false, resizable: false, width: 50 }); } columns.push({ field: "name", title: this.config.selectable ? i18n(strings.tableColPath) : undefined, resizable: false, headerSort: false, cssClass: "column-name", tooltip: true, bottomCalc: this.config.selectable && this.config.showSelectionCount ? "count" : null, bottomCalcFormatter: cell=> i18n(strings.tableSelectedCount, {count: this.table.getSelectedData().length}), formatter: (cell) => { const item = <Branch>cell.getData(); return `<span class="item-type icon-type-${item.dataType}"></span>${item.name}`; } }); if (this.config.additionalColumns) columns = [...columns, ...this.config.additionalColumns]; let tableConfig: Tabulator.Options = { height: (this.config.search ? "calc(100% - 50px)" : "100%"), selectable: this.config.selectable, headerVisible: this.config.selectable, layout: "fitColumns", placeholder: (this.config.placeholder ? this.config.placeholder : " "), // This fixes scrollbar appearing with empty tables dataTree: this.viewAsTree, dataTreeCollapseElement:`<span class="tree-toggle icon icon-collapse"></span>`, dataTreeExpandElement:`<span class="tree-toggle icon icon-expand"></span>`, dataTreeBranchElement: false, dataTreeElementColumn: "name", dataTreeChildIndent: 35, dataTreeSelectPropagate: true, dataTreeStartExpanded: false, dataTreeFilter:true, initialFilter: data => this.filter(data, { viewAsTree: this.viewAsTree, searchValue: (this.searchBox ? this.searchBox.value : "") }), initialSort: [ {column: "name", dir: "asc"}, ], columns: columns, data: data, rowFormatter: row => { try { //Bypass calc rows if ((<any>row)._row && (<any>row)._row.type == "calc") return; let item = <Branch>row.getData(); let element = row.getElement(); if (item.isHidden){ element.classList.add("row-hidden"); } if (item.isInactive === true){ element.classList.add("row-inactive"); } if (this.config.rowFormatter) this.config.rowFormatter(item, element); }catch(ignore){} }, }; if (this.config.selectable) { tableConfig.selectableCheck = (row => { let item = <Branch>row.getData(); return (item.isUnselectable !== true); }); } this.table = new Tabulator(`#${this.element.id} .table`, tableConfig); if (this.config.noBorders) this.table.element.classList.add("no-borders"); if (this.config.selectable) { this.table.on("rowSelectionChanged", (data: any[], rows: Tabulator.RowComponent[]) =>{ if (this.config.showSelectionCount) this.table.recalc(); this.trigger("select", this.selected); }); } this.table.on("rowClick", (e, row) => { let item = <Branch>row.getData(); if (this.config.activable && item.isInactive !== true) { this.activeItem = item; __(".row-active", this.table.element).forEach((el: HTMLElement) => { el.classList.remove("row-active"); }); row.getElement().classList.add("row-active"); } else if (!this.config.selectable) { let el = _(".tree-toggle", <HTMLElement>e.target); if (!el.empty) { row.treeToggle(); } } if (item.isInactive !== true) this.trigger("click", item); }); } else { this.deactivate(); this.table.setData(data); } } deselect() { if (this.table) this.table.deselectRow(); this.trigger("deselect"); } deactivate() { if (this.table) { __(".row-active", this.table.element).forEach((el: HTMLElement) => { el.classList.remove("row-active"); }); } this.activeItem = null; this.trigger("deactivate"); } applyFilters() { if (this.table) { this.table.setFilter(this.filter, { viewAsTree: this.viewAsTree, searchValue: (this.searchBox ? this.searchBox.value : "") }); } } filter(branch: Branch, params: TabularBrowserFilter): boolean { let searchValue = (params.searchValue != "" ? sanitizeHtml(params.searchValue, { allowedTags: [], allowedAttributes: {}}) : ""); if (searchValue != "") { if (params.viewAsTree) { if (!tabulatorTreeChildrenFilter(branch, <TabulatorTreeChildrenFilterParams>{ column: "name", comparison: "like", value: searchValue })) return false; } else { if (!branch.name.toLowerCase().includes(searchValue.toLowerCase())) return false; } } return true } destroyTable() { if (this.table) { this.table.destroy(); this.table = null; } this.deactivate(); } destroy() { this.branches = null; this.destroyTable(); super.destroy(); } redraw() { if (this.table) this.table.redraw(); } /* Converters */ static ConvertBranchesToRows(branches: Branch[], filter: PlainTreeFilter): Branch[] { let rows: Branch[] = []; const iterate = (branches: Branch[]) => { branches.forEach(branch => { switch (filter) { case PlainTreeFilter.ParentOnly: rows.push(branch); break; case PlainTreeFilter.LastChildrenOnly: if ("_children" in branch && branch._children.length) { iterate(branch._children) } else { rows.push(branch); } break; } }); }; iterate(branches); return rows; } static ConvertModelToBranches(model: TabularDatabaseModel): Branch[] { let branches: Dic<Branch> = {}; model.tables .sort((a, b) => a.name.localeCompare(b.name)) .forEach(table => { if (!(table.name in branches)) branches[table.name] = { id: table.name, name: table.name, type: BranchType.Table, dataType: table.isDateTable ? "date-table" : "table", isHidden: table.isHidden, //_children: [] }; }); model.columns .sort((a, b) => a.name.localeCompare(b.name)) .forEach(column => { if (column.tableName in branches) { if (!("_children" in branches[column.tableName])) branches[column.tableName]._children = []; branches[column.tableName]._children.push({ id: column.name, name: column.columnName, type: BranchType.Column, dataType: (column.dataType ? column.dataType.toLowerCase() : ""), isHidden: column.isHidden }); } }); return Object.values(branches); } }
the_stack
import { action, observable } from 'mobx'; import { Autowired, Injectable } from '@opensumi/di'; import { PreferenceService } from '@opensumi/ide-core-browser'; import { Disposable, Emitter, Event, getDebugLogger, Uri, ISplice } from '@opensumi/ide-core-common'; import { combinedDisposable, dispose, DisposableStore, IDisposable, toDisposable } from '@opensumi/ide-core-common'; import { ISCMMenus, ISCMRepository, ISCMResource, ISCMResourceGroup, SCMService } from '../common'; export interface IGroupItem { readonly group: ISCMResourceGroup; visible: boolean; readonly disposable: IDisposable; } export interface IResourceGroupSpliceEvent<T> { target: ISCMRepository; index: number; deleteCount: number; elements: T[]; } export type ISCMDataItem = ISCMResourceGroup | ISCMResource; export class ResourceGroupSplicer { private items: IGroupItem[] = []; private disposables: IDisposable[] = []; private _onDidSplice = new Emitter<IResourceGroupSpliceEvent<ISCMDataItem>>(); readonly onDidSplice: Event<IResourceGroupSpliceEvent<ISCMDataItem>> = this._onDidSplice.event; constructor(private repository: ISCMRepository) {} run() { const groupSequence = this.repository.provider.groups; groupSequence.onDidSplice(this.onDidSpliceGroups, this, this.disposables); this.onDidSpliceGroups({ start: 0, deleteCount: 0, toInsert: groupSequence.elements }); } private onDidSpliceGroups({ start, deleteCount, toInsert }: ISplice<ISCMResourceGroup>): void { let absoluteStart = 0; for (let i = 0; i < start; i++) { const item = this.items[i]; absoluteStart += (item.visible ? 1 : 0) + item.group.elements.length; } let absoluteDeleteCount = 0; for (let i = 0; i < deleteCount; i++) { const item = this.items[start + i]; absoluteDeleteCount += (item.visible ? 1 : 0) + item.group.elements.length; } const itemsToInsert: IGroupItem[] = []; const absoluteToInsert: Array<ISCMResourceGroup | ISCMResource> = []; for (const group of toInsert) { const visible = isGroupVisible(group); if (visible) { absoluteToInsert.push(group); } for (const element of group.elements) { absoluteToInsert.push(element); } const disposable = combinedDisposable([ group.onDidChange(() => this.onDidChangeGroup(group)), group.onDidSplice((splice) => this.onDidSpliceGroup(group, splice)), ]); itemsToInsert.push({ group, visible, disposable }); } const itemsToDispose = this.items.splice(start, deleteCount, ...itemsToInsert); for (const item of itemsToDispose) { item.disposable.dispose(); } this._onDidSplice.fire({ target: this.repository, index: absoluteStart, deleteCount: absoluteDeleteCount, elements: absoluteToInsert, }); } private onDidChangeGroup(group: ISCMResourceGroup): void { const itemIndex = this.items.findIndex((item) => item.group === group); if (itemIndex < 0) { return; } const item = this.items[itemIndex]; const visible = isGroupVisible(group); if (item.visible === visible) { return; } let absoluteStart = 0; for (let i = 0; i < itemIndex; i++) { const item = this.items[i]; absoluteStart += (item.visible ? 1 : 0) + item.group.elements.length; } if (visible) { this._onDidSplice.fire({ target: this.repository, index: absoluteStart, deleteCount: 0, elements: [group, ...group.elements], }); } else { this._onDidSplice.fire({ target: this.repository, index: absoluteStart, deleteCount: 1 + group.elements.length, elements: [], }); } item.visible = visible; } private onDidSpliceGroup(group: ISCMResourceGroup, { start, deleteCount, toInsert }: ISplice<ISCMResource>): void { const itemIndex = this.items.findIndex((item) => item.group === group); if (itemIndex < 0) { return; } const item = this.items[itemIndex]; const visible = isGroupVisible(group); if (!item.visible && !visible) { return; } let absoluteStart = start; for (let i = 0; i < itemIndex; i++) { const item = this.items[i]; absoluteStart += (item.visible ? 1 : 0) + item.group.elements.length; } if (item.visible && !visible) { this._onDidSplice.fire({ target: this.repository, index: absoluteStart, deleteCount: 1 + deleteCount, elements: toInsert, }); } else if (!item.visible && visible) { this._onDidSplice.fire({ target: this.repository, index: absoluteStart, deleteCount, elements: [group, ...toInsert], }); } else { this._onDidSplice.fire({ target: this.repository, index: absoluteStart + 1, deleteCount, elements: toInsert, }); } item.visible = visible; } dispose(): void { this.onDidSpliceGroups({ start: 0, deleteCount: this.items.length, toInsert: [] }); this.disposables = dispose(this.disposables); } } function isGroupVisible(group: ISCMResourceGroup) { return group.elements.length > 0 || !group.hideWhenEmpty; } @Injectable() export class ViewModelContext extends Disposable { @Autowired(SCMService) private readonly scmService: SCMService; @Autowired(ISCMMenus) private readonly _menus: ISCMMenus; @Autowired(PreferenceService) private readonly preferenceService: PreferenceService; private onDidSelectedRepoChangeEmitter: Emitter<ISCMRepository> = new Emitter(); get onDidSelectedRepoChange() { return this.onDidSelectedRepoChangeEmitter.event; } public get menus(): ISCMMenus { return this._menus; } private logger = getDebugLogger(); private toDisposableListener: IDisposable | null; private _onDidSCMListChangeEmitter: Emitter<void> = new Emitter(); public onDidSCMListChange = this._onDidSCMListChangeEmitter.event; constructor() { super(); this.start(); this.initTreeAlwaysShowActions(); this.scmService.onDidChangeSelectedRepositories(this._handleSelectedRepoChanged, this, this.disposables); this._handleSelectedRepoChanged(this.scmService.selectedRepositories); } private _handleSelectedRepoChanged(repos: ISCMRepository[]) { const [selectedRepo] = repos; if (!selectedRepo) { // handle all repo deleted return; } if (this.toDisposableListener) { this.toDisposableListener.dispose(); this.toDisposableListener = null; } this.toDisposableListener = this.listenToCurrentRepo(selectedRepo); } private listenToCurrentRepo(repository: ISCMRepository): IDisposable { const disposables = new DisposableStore(); const resourceGroup = new ResourceGroupSplicer(repository); // 只处理当前 repository 的事件 const repoOnDidSplice = Event.filter(resourceGroup.onDidSplice, (e) => e.target === repository); disposables.add( repoOnDidSplice(({ index, deleteCount, elements }) => { if (repository.provider.rootUri) { // 只处理存在工作区路径的 SCMList this.spliceSCMList(repository.provider.rootUri, index, deleteCount, ...elements); } }), ); resourceGroup.run(); disposables.add(resourceGroup); return toDisposable(() => { disposables.clear(); }); } private initTreeAlwaysShowActions() { this.alwaysShowActions = !!this.preferenceService.get<boolean>('scm.alwaysShowActions'); this.disposables.push( this.preferenceService.onSpecificPreferenceChange( 'scm.alwaysShowActions', (changes) => (this.alwaysShowActions = changes.newValue), ), ); } @observable public alwaysShowActions: boolean; start() { this.scmService.onDidAddRepository( (repo: ISCMRepository) => { this.addRepo(repo); }, this, this.disposables, ); this.scmService.onDidRemoveRepository( (repo: ISCMRepository) => { this.deleteRepo(repo); }, this, this.disposables, ); this.scmService.onDidChangeSelectedRepositories( (repos: ISCMRepository[]) => { this.changeSelectedRepos(repos); }, this, this.disposables, ); this.scmService.repositories.forEach((repo) => { this.addRepo(repo); }); } @observable public repoList = observable.array<ISCMRepository>([]); @observable public selectedRepos = observable.array<ISCMRepository>([]); @observable public selectedRepo: ISCMRepository | undefined; public scmList = new Array<ISCMDataItem>(); private _currentWorkspace: Uri; private spliceSCMList = (workspace: Uri, start: number, deleteCount: number, ...toInsert: ISCMDataItem[]) => { if (!this._currentWorkspace || this._currentWorkspace.toString() === workspace.toString()) { this.scmList.splice(start, deleteCount, ...toInsert); } else { this.scmList = [...toInsert]; } this._currentWorkspace = workspace; this._onDidSCMListChangeEmitter.fire(); }; @action private addRepo(repo: ISCMRepository) { // 因为这里每个传入的 repo 均为新实例,这里需要通过 Uri.toString() 去判断 if ( this.repoList.find( (exist: ISCMRepository) => exist.provider.rootUri?.toString() === repo.provider.rootUri?.toString(), ) ) { this.logger.warn('duplicate scm repo', repo); return; } this.repoList.push(repo); // 兜底: 避免由于生命周期导致 start 方法里的监听后置导致数据更新不到 if (repo.selected && this.repoList.length === 1) { this.changeSelectedRepos([repo]); } } @action private deleteRepo(repo: ISCMRepository) { const index = this.repoList.indexOf(repo); if (index < 0) { this.logger.warn('no such scm repo', repo); return; } this.repoList.splice(index, 1); } @action private changeSelectedRepos(repos: ISCMRepository[]) { this.selectedRepos.replace(repos); const selectedRepo = repos[0]; this.selectedRepo = selectedRepo; this.onDidSelectedRepoChangeEmitter.fire(selectedRepo); } }
the_stack
import React, { PropsWithChildren } from "react"; import { useDispatch, useSelector } from "react-redux"; import Icon from "./Icon"; import ScrollBox from "./ScrollBox"; import Timestamp from "./Timestamp"; import * as codemarkSelectors from "../store/codemarks/reducer"; import * as userSelectors from "../store/users/reducer"; import styled from "styled-components"; import { includes as _includes, sortBy as _sortBy, last as _last } from "lodash-es"; import { CodeStreamState } from "../store"; import { setCurrentCodemark, setCurrentReview, setCurrentCodeError, closeAllPanels } from "../store/context/actions"; import { getActivity } from "../store/activityFeed/reducer"; import { useDidMount, useIntersectionObserver, usePrevious } from "../utilities/hooks"; import { HostApi } from "../webview-api"; import { FetchActivityRequestType, PostPlus, CodemarkPlus, PinReplyToCodemarkRequestType, GetReposScmRequestType, ReposScm, DirectoryTree, ChangeDataType, DidChangeDataNotificationType } from "@codestream/protocols/agent"; import { savePosts } from "../store/posts/actions"; import { addOlderActivity } from "../store/activityFeed/actions"; import { saveCodemarks } from "../store/codemarks/actions"; import { safe, emptyArray } from "../utils"; import { markStreamRead, setUserPreference } from "./actions"; import { CSUser, CSReview, ActivityFilter, RepoSetting, CSCodeError } from "@codestream/protocols/api"; import { resetLastReads } from "../store/unreads/actions"; import { PanelHeader } from "../src/components/PanelHeader"; import { getPost, getThreadPosts } from "../store/posts/reducer"; import Menu from "./Menu"; import { FormattedPlural } from "react-intl"; import { Codemark } from "./Codemark/index"; import { Review } from "./Review"; import { CodeError } from "./CodeError"; import { saveReviews } from "../store/reviews/actions"; import { saveCodeErrors } from "../store/codeErrors/actions"; import { Reply } from "./Posts/Reply"; import { LoadingMessage } from "../src/components/LoadingMessage"; import { Headshot } from "../src/components/Headshot"; import { ProfileLink } from "../src/components/ProfileLink"; import { Keybindings } from "./Keybindings"; import { Dialog } from "../src/components/Dialog"; interface MenuItem { label: any; checked?: boolean; key?: string; title?: string; action?: Function; submenu?: MenuItem[]; } // see comment in SmartFormattedList.tsx const FormattedPluralAlias = FormattedPlural as any; const EmptyMessage = styled.div` height: 100%; width: 100%; display: flex; justify-content: center; align-items: center; p { width: 20em; margin: 0 auto; color: var(--text-color-subtle); text-align: center; } `; const DEFAULT_ACTIVITY_FILTER = { mode: "openInIde", settings: { repos: [] } }; export const ActivityPanel = () => { const dispatch = useDispatch(); const derivedState = useSelector((state: CodeStreamState) => { const usernames = userSelectors.getUsernames(state); const { preferences } = state; return { usernames, users: state.users, noCodemarksAtAll: !codemarkSelectors.teamHasCodemarks(state), postsByStreamId: state.posts.byStream, currentUserName: state.users[state.session.userId!].username, currentUserId: state.session.userId, currentTeamId: state.context.currentTeamId, activity: getActivity(state), hasMoreActivity: state.activityFeed.hasMore, codemarkTypeFilter: state.context.codemarkTypeFilter, umis: state.umis, webviewFocused: state.context.hasFocus, repos: state.repos, activityFilter: preferences[state.context.currentTeamId]?.activityFilter || DEFAULT_ACTIVITY_FILTER }; }); const previousActivityFilter = usePrevious(derivedState.activityFilter); const [activityFilterMenuItems, setActivityFilterMenuItems] = React.useState<any[] | undefined>( undefined ); const [ellipsisMenuOpen, setEllipsisMenuOpen] = React.useState(); const toggleEllipsisMenu = event => { setEllipsisMenuOpen(ellipsisMenuOpen ? undefined : event.target.closest("label")); }; const [repos, setRepos] = React.useState<ReposScm[]>([]); const [maximized, setMaximized] = React.useState(false); const setActivityPreferences = ( data: ActivityFilter, src: "Folder" | "Everyone" | "Open Repos" ) => { dispatch(setUserPreference([derivedState.currentTeamId, "activityFilter"], data)); HostApi.instance.track("Activity Feed Filtered", { "Selected Filter": src }); }; const activity = React.useMemo(() => { let _activity = derivedState.activity; if (!repos?.length) { return _activity; } let repoSettings: RepoSetting[] = []; let isFallback = false; if (derivedState.activityFilter.mode === "selectedRepos") { repoSettings = derivedState.activityFilter?.settings?.repos || []; let mappedRepoIds = repos.map(_ => _.id); repoSettings = repoSettings?.filter(_ => _.id != null && mappedRepoIds.includes(_.id)); if (!repoSettings.length) { // couldn't find a matching repo open in the ide, fallback to open in IDE isFallback = true; } } if (isFallback || derivedState.activityFilter.mode === "openInIde") { repoSettings = repos ?.filter(_ => _.id != null) .map(_ => { return { id: _.id!, paths: [] }; }); } else if (!repoSettings.length) return _activity; const filtered = _activity.map(_ => { const streams = derivedState.postsByStreamId[_.record.streamId]; const post = streams[_.record.postId]; if (post) { if (post.mentionedUserIds?.includes(derivedState.currentUserId!)) { return _; } // check replies as well const parentPosts = Object.values(streams).find(_ => { return _.parentPostId && _.parentPostId === post.id && _.mentionedUserIds?.includes(derivedState.currentUserId!) ? _ : null; }); if (parentPosts) { return _; } } if (_.type === "codemark") { if (_.record.assignees?.includes(derivedState.currentUserId!)) { return _; } let found: any = undefined; for (const repoSetting of repoSettings) { const match = _.record.markers?.find(m => { let isPathMatch = true; if (repoSetting.paths && repoSetting.paths[0] != null) { isPathMatch = (m.file || "").replace(/\\/g, "/").indexOf(repoSetting.paths![0]) === 0; } return isPathMatch && repoSetting.id === m.repoId; }); found = match ? _ : undefined; if (found) { return found; } } return found; } else if (_.type === "review") { if (_.record.reviewers?.includes(derivedState.currentUserId!)) { return _; } let found: any = undefined; for (const repoSetting of repoSettings) { const match = _.record.reviewChangesets?.find(m => { let isPathMatch = true; if (repoSetting.paths && repoSetting.paths[0] != null) { isPathMatch = !!m.modifiedFiles.find( _ => (_.file || "").replace(/\\/g, "/").indexOf(repoSetting.paths![0]) === 0 ); } return isPathMatch && repoSetting.id === m.repoId; }); found = match ? _ : undefined; if (found) { return found; } } return found; } else if (_.type === "codeError") { let found: any = undefined; for (const repoSetting of repoSettings) { const match = _.record.stackTraces?.find(m => { return repoSetting.id === m.repoId; }); found = match ? _ : undefined; if (found) { return found; } } return found; } return null; }); return filtered.filter(Boolean); }, [derivedState.activity, repos, derivedState.activityFilter, derivedState.postsByStreamId]); const filterLabel = React.useMemo(() => { if (derivedState.activityFilter.mode === "selectedRepos") { let repoSettings = derivedState.activityFilter?.settings?.repos || []; if (repoSettings.length) { let mappedRepoIds = repos.map(_ => _.id); repoSettings = repoSettings?.filter(_ => _.id != null && mappedRepoIds.includes(_.id)); // couldn't find a matching repo open in the ide, fallback to open in IDE if (!repoSettings.length) { console.error("falling back to openInIDE"); return "my IDE"; } const labels: string[] = []; for (const repoSetting of repoSettings) { const foundRepo = repos.find(_ => _.id === repoSetting.id); labels.push( `${foundRepo?.folder?.name || `selected repo`}${ repoSetting.paths ? " (" + repoSetting.paths[0] + ")" : "" }` ); } return labels ? labels.join(", ") : "selected repos"; } return "selected repos"; } if (derivedState.activityFilter.mode === "openInIde") { return "my IDE"; } return "my organization"; }, [derivedState.activity, repos]); const fetchActivity = React.useCallback(async () => { let response = await HostApi.instance.send(FetchActivityRequestType, { limit: 50, before: safe(() => _last(activity)!.record.postId) }); dispatch(savePosts(response.posts)); dispatch(saveCodemarks(response.codemarks)); dispatch(saveReviews(response.reviews)); dispatch(saveCodeErrors(response.codeErrors)); dispatch( addOlderActivity({ activities: response.records, hasMore: Boolean(response.more) }) ); }, [activity]); const renderFilter = async () => { const repoResponse = await HostApi.instance.send(GetReposScmRequestType, { inEditorOnly: true, withSubDirectoriesDepth: 2 }); if (repoResponse && repoResponse.repositories) { setRepos(repoResponse.repositories); const selectedReposSubMenuItems: any[] = []; const menuTreeBuilder = (r: DirectoryTree) => { const checked = () => { if (derivedState.activityFilter.mode === "selectedRepos") { const repo = derivedState.activityFilter.settings?.repos?.find(_ => _.id === r.id); if (repo && repoResponse.repositories?.find(_ => _.id === repo.id)) { if (repo.paths && repo.paths.length) { const path = (repo.paths[0] || "").replace(/\\/g, "/"); if (r.partialPath) { const joined = r.partialPath.join("/"); return joined === path || path.indexOf(joined) === 0; } } } return false; } return false; }; const menuItem: MenuItem = { key: r.id + "-" + r.name, checked: checked(), label: r.name, action: () => { setActivityPreferences( { mode: "selectedRepos", settings: { repos: [ { id: r.id!, paths: [r.partialPath.join("/")] } ] } }, "Folder" ); } }; if (r?.children != null && r?.children.length) { const menuItems: MenuItem[] = []; r.children.forEach((child: any) => { menuItems.push(menuTreeBuilder(child)); }); menuItem.submenu = menuItems; } return menuItem; }; const mappedRepoIds = derivedState.activityFilter.settings?.repos?.filter(_ => _.id).map(_ => _.id) || []; const hasASelectedRepo = !!repoResponse.repositories?.find( r => r.id && mappedRepoIds.includes(r.id) ); repoResponse.repositories.forEach(_ => { const checked = () => { if (derivedState.activityFilter.mode === "selectedRepos") { const repo = derivedState.activityFilter.settings?.repos?.find(r => r.id === _.id); return !!(repo && repoResponse.repositories?.find(r => r.id === repo.id)); } return false; }; const repoMenu = { key: _.id, checked: checked(), label: _.folder.name, action: () => { setActivityPreferences( { mode: "selectedRepos", settings: { repos: [ { id: _.id! } ] } }, "Folder" ); } } as any; selectedReposSubMenuItems.push(repoMenu); if (_.directories && _.directories.children != null && _.directories.children.length) { const submenuItems: any[] = []; _.directories.children.forEach(child => { submenuItems.push(menuTreeBuilder(child)); }); repoMenu.submenu = submenuItems; } }); const mainFilterChoices = [ { checked: derivedState.activityFilter.mode === "everyone", key: "everyone", label: "Activity from everyone in the organization", action: () => { setActivityPreferences( { mode: "everyone", settings: { repos: [] } }, "Everyone" ); } }, { checked: derivedState.activityFilter.mode === "openInIde" || (derivedState.activityFilter.mode === "selectedRepos" && !hasASelectedRepo), key: "openInIde", label: "Activity associated with code open in my IDE", action: () => { setActivityPreferences( { mode: "openInIde", settings: { repos: [] } }, "Open Repos" ); } }, { checked: derivedState.activityFilter.mode === "selectedRepos" && hasASelectedRepo, label: "Activity associated with code in selected folder", key: "selectedRepos", submenu: selectedReposSubMenuItems } ] as MenuItem[]; setActivityFilterMenuItems(mainFilterChoices); } return { repos: repoResponse?.repositories || [] }; }; React.useEffect(() => { if (JSON.stringify(previousActivityFilter) !== JSON.stringify(derivedState.activityFilter)) { renderFilter(); } }, [derivedState.activityFilter]); useDidMount(() => { if (derivedState.webviewFocused) HostApi.instance.track("Page Viewed", { "Page Name": "Activity Feed" }); renderFilter().then(() => { if (activity.length === 0) fetchActivity(); }); const disposable = HostApi.instance.on(DidChangeDataNotificationType, (e: any) => { if (e.type === ChangeDataType.Workspace) { renderFilter(); } }); return () => { dispatch(resetLastReads()); disposable.dispose(); }; }); React.useEffect(() => { for (let streamId in derivedState.umis.unreads) { dispatch(markStreamRead(streamId)); } }, [derivedState.webviewFocused]); const { targetRef, rootRef } = useIntersectionObserver(entries => { if (!entries[0].isIntersecting) return; if (!derivedState.hasMoreActivity || activity.length === 0) return; fetchActivity(); }); const renderActivity = () => { if (activity.length === 0 && !derivedState.hasMoreActivity) { return ( <div style={{ height: "75vh" }}> <Keybindings> The activity feed will let you know when your teammates create codemarks, assign issues, request reviews, or add replies. <br /> <br /> </Keybindings> </div> ); } return activity.map(({ type, record }) => { const person = derivedState.users[record.creatorId || ""]; if (!person) return null; if (type === "codemark") { const codemark = record as CodemarkPlus; if ( derivedState.codemarkTypeFilter != "all" && codemark.type !== derivedState.codemarkTypeFilter ) return null; return ( <ActivityWrapper key={codemark.id}> <ActivityVerb> <ProfileLink id={person.id}> <Headshot size={24} person={person} /> </ProfileLink> <div> <b>{person.username}</b> <span className="verb">{codemark.type === "issue" ? " opened an issue " : ""}</span> <Timestamp relative time={codemark.createdAt} /> </div> </ActivityVerb> <ActivityItem streamId={codemark.streamId} postId={codemark.postId}> {({ className, isUnread, post }) => ( // @ts-ignore because typescript isn't handling the union props well <Codemark className={className} collapsed={!isUnread} codemark={codemark} post={post} hoverEffect isUnread={isUnread} onClick={e => { const target = e.target; if ( target && // @ts-ignore (target.closest(".emoji-mart") || target.closest(".reactions")) ) return; HostApi.instance.track("Codemark Clicked", { "Codemark ID": codemark.id, "Codemark Location": "Activity Feed" }); dispatch(setCurrentCodemark(codemark.id)); }} renderActions={true} renderFooter={Footer => ( <Footer style={{ borderTop: "none", paddingLeft: 0, paddingRight: 0, marginTop: 0 }} > <RepliesForActivity parentPost={post} pinnedReplies={codemark.pinnedReplies} /> </Footer> )} /> )} </ActivityItem> </ActivityWrapper> ); } if (type === "review") { if ( derivedState.codemarkTypeFilter != "all" && "review" !== derivedState.codemarkTypeFilter ) return null; // @ts-ignore const repoName = record.reviewChangesets .map(changeset => derivedState.repos[changeset.repoId] ? derivedState.repos[changeset.repoId].name : undefined ) // remove duplictes .filter((val, index, arr) => arr.indexOf(val) === index) .filter(Boolean) .join(", "); return ( <ActivityWrapper key={record.id}> <ActivityVerb> <ProfileLink id={person.id}> <Headshot size={24} person={person} /> </ProfileLink> <div> <b>{person.username}</b>{" "} <span className="verb">requested feedback {repoName && <>in {repoName}</>}</span>{" "} <Timestamp relative time={record.createdAt} className="no-padding" /> </div> </ActivityVerb> <ActivityItem streamId={record.streamId} postId={record.postId}> {({ className, post }) => ( <Review className={className} review={record as CSReview} collapsed hoverEffect onClick={e => { const target = e.target; if ( target && // @ts-ignore (target.closest(".emoji-mart") || target.closest(".reactions")) ) return; dispatch(setCurrentReview(record.id)); }} renderFooter={Footer => ( <Footer style={{ borderTop: "none", paddingLeft: 0, paddingRight: 0, marginTop: 0 }} > <RepliesForActivity parentPost={post} /> </Footer> )} /> )} </ActivityItem> </ActivityWrapper> ); } if (type === "codeError") { if ( derivedState.codemarkTypeFilter != "all" && "codeError" !== derivedState.codemarkTypeFilter ) return null; const repo = null; return ( <ActivityWrapper key={record.id}> <ActivityVerb> <ProfileLink id={person.id}> <Headshot size={24} person={person} /> </ProfileLink> <div> <b>{person.username}</b>{" "} <span className="verb"> started a conversation about a code error {repo && <>in {repo}</>} </span>{" "} <Timestamp relative time={record.createdAt} className="no-padding" /> </div> </ActivityVerb> <ActivityItem streamId={record.streamId} postId={record.postId}> {({ className, post }) => ( <CodeError className={className} codeError={record as CSCodeError} collapsed hoverEffect onClick={e => { const target = e.target; if ( target && // @ts-ignore (target.closest(".emoji-mart") || target.closest(".reactions")) ) return; dispatch( setCurrentCodeError(record.id, { openType: "Activity Feed" }) ); }} renderFooter={Footer => ( <Footer style={{ borderTop: "none", paddingLeft: 0, paddingRight: 0, marginTop: 0 }} > <RepliesForActivity parentPost={post} /> </Footer> )} /> )} </ActivityItem> </ActivityWrapper> ); } return null; }); }; return ( <Dialog wide noPadding onMaximize={() => setMaximized(true)} onMinimize={() => setMaximized(false)} onClose={() => dispatch(closeAllPanels())} > <PanelHeader title="Activity"> {activityFilterMenuItems && ( <> <label onClick={toggleEllipsisMenu} id="activity-filter" style={{ cursor: "pointer" }}> <span> {derivedState.activityFilter.mode === "everyone" ? "Activity from everyone in" : "Activity associated with code in"}{" "} </span> {filterLabel} <Icon name="chevron-down-thin" className="smaller" style={{ verticalAlign: "-1px" }} /> {ellipsisMenuOpen && ( <Menu items={activityFilterMenuItems} action={() => setEllipsisMenuOpen(undefined)} target={ellipsisMenuOpen} /> )} </label> </> )} </PanelHeader> <div style={{ height: maximized ? "calc(100vh - 50px)" : "calc(100vh - 120px)", overflow: "hidden" }} > <ScrollBox> <div ref={rootRef} className="channel-list vscroll"> {renderActivity()} {derivedState.hasMoreActivity && (activity.length === 0 ? ( <LoadingMessage>Loading latest activity...</LoadingMessage> ) : ( <LoadingMessage ref={targetRef}>Loading more...</LoadingMessage> ))} </div> </ScrollBox> </div> </Dialog> ); }; type ActivityItemChildren = (props: { post: PostPlus; className?: string; isUnread?: boolean; }) => any; // this component is a wrapper which generates the unread styling const ActivityItemWrapper = styled( (props: { post: PostPlus; isUnread?: boolean; children: ActivityItemChildren; className?: string; }) => { const { children, ...childProps } = props; return children(childProps); } )` ${props => props.isUnread ? ` border-left: 2px solid var(--text-color-info); ${StyledReply} { border-left: none; } ` : ""} margin-left: 30px; @media only screen and (max-width: 350px) { margin-left: 0; } `; const ActivityVerb = styled.div` display: flex; align-items: center; margin: 5px 0 5px 0; ${Headshot} { flex-shrink: 0; display: inline-block; margin-right: 8px; margin-left: 0; } b { font-weight: normal; color: var(--text-color-highlight); } color: var(--text-color-subtle); .icon { vertical-align: -2px; } .verb { margin-right: 5px; } time { padding: 0; white-space: nowrap; opacity: 0.5; } `; /* For each activity, given postId + streamId, this component will look up the post and determine if it's unread. The child to this is a render function that receives the `ActivityItemChildren` args, which contains info about the activity and post and also a `className` for style overrides */ const ActivityItem = (props: { postId: string; streamId: string; children: ActivityItemChildren; }) => { const { isUnread, post } = useSelector((state: CodeStreamState) => { const post = getPost(state.posts, props.streamId, props.postId); const lastReadForStream = state.umis.lastReads[props.streamId]; return { isUnread: lastReadForStream != undefined && post != undefined && (post as PostPlus).seqNum > lastReadForStream, post }; }); return <ActivityItemWrapper isUnread={isUnread} children={props.children} post={post} />; }; const SeeReplies = styled.div` text-align: center; `; const StyledReply = styled(Reply)` padding-left: 10px; padding-right: 10px; border-left: 2px solid var(--text-color-info); `; const UnreadReply = (props: { author: Partial<CSUser>; post: PostPlus; starred?: boolean; codemarkId?: string; }) => { const menuItems = React.useMemo(() => { // sine the only menu item right now is for pinning replies, don't show it if this is not a reply to a codemark if (props.codemarkId == null) return emptyArray; return [ { label: props.starred ? "Un-Star Reply" : "Star Reply", key: "star", action: () => { HostApi.instance.send(PinReplyToCodemarkRequestType, { codemarkId: props.codemarkId!, postId: props.post.id, value: !props.starred }); } } ]; }, [props.starred]); return ( <StyledReply author={props.author} post={props.post} showParentPreview renderMenu={ menuItems.length === 0 ? undefined : (target, close) => target && <Menu items={menuItems} target={target} action={close} /> } /> ); }; const createUnknownUser = id => ({ username: id, fullName: "Unknown" }); const RepliesForActivity = (props: { parentPost?: PostPlus; pinnedReplies?: string[] }) => { const derivedState = useSelector((state: CodeStreamState) => { if (props.parentPost == undefined) return { numberOfReplies: 0, unreadReplies: [] }; const lastUnreadForStream = state.umis.lastReads[props.parentPost.streamId] as | number | undefined; const unreadReplies: PostPlus[] = lastUnreadForStream != undefined ? (getThreadPosts(state, props.parentPost.streamId, props.parentPost.id).filter( post => (post as any).seqNum > lastUnreadForStream ) as PostPlus[]) : []; return { numberOfReplies: props.parentPost.numReplies, unreadReplies }; }); const users = useSelector((state: CodeStreamState) => state.users); if (derivedState.numberOfReplies === 0) return null; if (derivedState.unreadReplies.length === 0) return null; //<SeeReplies>See replies</SeeReplies>; const otherReplyCount = derivedState.numberOfReplies - derivedState.unreadReplies.length; return ( <> {derivedState.unreadReplies.map(post => ( <UnreadReply key={post.id} post={post} author={users[post.creatorId] || createUnknownUser(post.creatorId)} starred={Boolean(props.pinnedReplies && props.pinnedReplies.includes(post.id))} codemarkId={props.parentPost!.codemarkId} /> ))} {false && otherReplyCount > 0 && ( <SeeReplies> See {otherReplyCount} earlier{" "} <FormattedPluralAlias value={otherReplyCount} one="reply" other="replies" /> </SeeReplies> )} </> ); }; const ActivityWrapper = styled.div` // tag: codemark-width margin: 5px 10px 30px 20px; .codemark-details { margin-bottom: 5px; } .activity-verb { } `;
the_stack
import { GrandFinalType, Match, MatchGame, MatchResults, Participant, ParticipantResult, Result, RoundRobinMode, Seeding, SeedOrdering, Stage, StageType, Status, } from 'brackets-model'; import { BracketKind, Database, Duel, FinalStandingsItem, IdMapping, Nullable, OmitId, ParitySplit, ParticipantSlot, Scores, Side } from './types'; import { ordering } from './ordering'; /** * Splits an array in two parts: one with even indices and the other with odd indices. * * @param array The array to split. */ export function splitByParity<T>(array: T[]): ParitySplit<T> { return { even: array.filter((_, i) => i % 2 === 0), odd: array.filter((_, i) => i % 2 === 1), }; } /** * Makes a list of rounds containing the matches of a round-robin group. * * @param participants The participants to distribute. * @param mode The round-robin mode. */ export function makeRoundRobinMatches<T>(participants: T[], mode: RoundRobinMode = 'simple'): [T, T][][] { const distribution = makeRoundRobinDistribution(participants); if (mode === 'simple') return distribution; // Reverse rounds and their content. const symmetry = distribution.map(round => [...round].reverse()).reverse(); return [...distribution, ...symmetry]; } /** * Distributes participants in rounds for a round-robin group. * * Conditions: * - Each participant plays each other once. * - Each participant plays once in each round. * * @param participants The participants to distribute. */ export function makeRoundRobinDistribution<T>(participants: T[]): [T, T][][] { const n = participants.length; const n1 = n % 2 === 0 ? n : n + 1; const roundCount = n1 - 1; const matchPerRound = n1 / 2; const rounds: [T, T][][] = []; for (let roundId = 0; roundId < roundCount; roundId++) { const matches: [T, T][] = []; for (let matchId = 0; matchId < matchPerRound; matchId++) { if (matchId === 0 && n % 2 === 1) continue; const opponentsIds = [ (roundId - matchId - 1 + n1) % (n1 - 1), matchId === 0 ? n1 - 1 : (roundId + matchId) % (n1 - 1), ]; matches.push([ participants[opponentsIds[0]], participants[opponentsIds[1]], ]); } rounds.push(matches); } return rounds; } /** * A helper to assert our generated round-robin is correct. * * @param input The input seeding. * @param output The resulting distribution of seeds in groups. */ export function assertRoundRobin<T>(input: T[], output: [T, T][][]): void { const n = input.length; const matchPerRound = Math.floor(n / 2); const roundCount = n % 2 === 0 ? n - 1 : n; if (output.length !== roundCount) throw Error('Round count is wrong'); if (!output.every(round => round.length === matchPerRound)) throw Error('Not every round has the good number of matches'); const checkAllOpponents = Object.fromEntries(input.map(element => [element, new Set<T>()])); for (const round of output) { const checkUnique = new Set<T>(); for (const match of round) { if (match.length !== 2) throw Error('One match is not a pair'); if (checkUnique.has(match[0])) throw Error('This team is already playing'); checkUnique.add(match[0]); if (checkUnique.has(match[1])) throw Error('This team is already playing'); checkUnique.add(match[1]); if (checkAllOpponents[match[0]].has(match[1])) throw Error('The team has already matched this team'); checkAllOpponents[match[0]].add(match[1]); if (checkAllOpponents[match[1]].has(match[0])) throw Error('The team has already matched this team'); checkAllOpponents[match[1]].add(match[0]); } } } /** * Distributes elements in groups of equal size. * * @param elements A list of elements to distribute in groups. * @param groupCount The group count. */ export function makeGroups<T>(elements: T[], groupCount: number): T[][] { const groupSize = Math.ceil(elements.length / groupCount); const result: T[][] = []; for (let i = 0; i < elements.length; i++) { if (i % groupSize === 0) result.push([]); result[result.length - 1].push(elements[i]); } return result; } /** * Balances BYEs to prevents having BYE against BYE in matches. * * @param seeding The seeding of the stage. * @param participantCount The number of participants in the stage. */ export function balanceByes(seeding: Seeding, participantCount?: number): Seeding { seeding = seeding.filter(v => v !== null); participantCount = participantCount || getNearestPowerOfTwo(seeding.length); if (seeding.length < participantCount / 2) { const flat = seeding.map(v => [v, null]).flat(); return setArraySize(flat, participantCount, null); } const nonNullCount = seeding.length; const nullCount = participantCount - nonNullCount; const againstEachOther = seeding.slice(0, nonNullCount - nullCount).filter((_, i) => i % 2 === 0).map((_, i) => [seeding[2 * i], seeding[2 * i + 1]]); const againstNull = seeding.slice(nonNullCount - nullCount, nonNullCount).map(v => [v, null]); const flat = [...againstEachOther.flat(), ...againstNull.flat()]; return setArraySize(flat, participantCount, null); } /** * Normalizes IDs in a database. * * Every ID - and references to it - is remapped to consecutive IDs starting from 0. * * @param data Data to normalize. */ export function normalizeIds(data: Database): Database { const mappings = { participant: makeNormalizedIdMapping(data.participant), stage: makeNormalizedIdMapping(data.stage), group: makeNormalizedIdMapping(data.group), round: makeNormalizedIdMapping(data.round), match: makeNormalizedIdMapping(data.match), match_game: makeNormalizedIdMapping(data.match_game), }; return { participant: data.participant.map(value => ({ ...value, id: mappings.participant[value.id], })), stage: data.stage.map(value => ({ ...value, id: mappings.stage[value.id], })), group: data.group.map(value => ({ ...value, id: mappings.group[value.id], stage_id: mappings.stage[value.stage_id], })), round: data.round.map(value => ({ ...value, id: mappings.round[value.id], stage_id: mappings.stage[value.stage_id], group_id: mappings.group[value.group_id], })), match: data.match.map(value => ({ ...value, id: mappings.match[value.id], stage_id: mappings.stage[value.stage_id], group_id: mappings.group[value.group_id], round_id: mappings.round[value.round_id], opponent1: normalizeParticipant(value.opponent1, mappings.participant), opponent2: normalizeParticipant(value.opponent2, mappings.participant), })), match_game: data.match_game.map(value => ({ ...value, id: mappings.match_game[value.id], stage_id: mappings.stage[value.stage_id], parent_id: mappings.match[value.parent_id], opponent1: normalizeParticipant(value.opponent1, mappings.participant), opponent2: normalizeParticipant(value.opponent2, mappings.participant), })), }; } /** * Makes a mapping between old IDs and new normalized IDs. * * @param elements A list of elements with IDs. */ export function makeNormalizedIdMapping(elements: { id: number }[]): IdMapping { let currentId = 0; return elements.reduce((acc, current) => ({ ...acc, [current.id]: currentId++, }), {}) as IdMapping; } /** * Apply a normalizing mapping to a participant. * * @param participant The participant. * @param mapping The mapping of IDs. */ export function normalizeParticipant(participant: ParticipantResult | null, mapping: IdMapping): ParticipantResult | null { if (participant === null) return null; return { ...participant, id: participant.id !== null ? mapping[participant.id] : null, }; } /** * Sets the size of an array with a placeholder if the size is bigger. * * @param array The original array. * @param length The new length. * @param placeholder A placeholder to use to fill the empty space. */ export function setArraySize<T>(array: T[], length: number, placeholder: T): T[] { return Array.from(Array(length), (_, i) => array[i] || placeholder); } /** * Makes pairs with each element and its next one. * * @example [1, 2, 3, 4] --> [[1, 2], [3, 4]] * @param array A list of elements. */ export function makePairs<T>(array: T[]): [T, T][] { return array.map((_, i) => (i % 2 === 0) ? [array[i], array[i + 1]] : []).filter((v): v is [T, T] => v.length === 2); } /** * Ensures that a list of elements has an even size. * * @param array A list of elements. */ export function ensureEvenSized<T>(array: T[]): void { if (array.length % 2 === 1) throw Error('Array size must be even.'); } /** * Ensures there are no duplicates in a list of elements. * * @param array A list of elements. */ export function ensureNoDuplicates<T>(array: Nullable<T>[]): void { const nonNull = getNonNull(array); const unique = [...new Set(nonNull)]; if (unique.length < nonNull.length) throw new Error('The seeding has a duplicate participant.'); } /** * Ensures that two lists of elements have the same size. * * @param left The first list of elements. * @param right The second list of elements. */ export function ensureEquallySized<T>(left: T[], right: T[]): void { if (left.length !== right.length) throw Error('Arrays\' size must be equal.'); } /** * Fixes the seeding by enlarging it if it's not complete. * * @param seeding The seeding of the stage. * @param participantCount The number of participants in the stage. */ export function fixSeeding(seeding: Seeding, participantCount: number): Seeding { if (seeding.length > participantCount) throw Error('The seeding has more participants than the size of the stage.'); if (seeding.length < participantCount) return setArraySize(seeding, participantCount, null); return seeding; } /** * Ensures that the participant count is valid. * * @param participantCount The number to test. */ export function ensureValidSize(participantCount: number): void { if (participantCount === 0) throw Error('Impossible to create an empty stage. If you want an empty seeding, just set the size of the stage.'); if (participantCount < 2) throw Error('Impossible to create a stage with less than 2 participants.'); if (!Number.isInteger(Math.log2(participantCount))) throw Error('The library only supports a participant count which is a power of two.'); } /** * Ensures that a match scores aren't tied. * * @param scores Two numbers which are scores. */ export function ensureNotTied(scores: [number, number]): void { if (scores[0] === scores[1]) throw Error(`${scores[0]} and ${scores[1]} are tied. It cannot be.`); } /** * Converts a participant slot to a result stored in storage. * * @param slot A participant slot. */ export function toResult(slot: ParticipantSlot): ParticipantSlot { return slot && { id: slot.id, }; } /** * Converts a participant slot to a result stored in storage, with the position the participant is coming from. * * @param slot A participant slot. */ export function toResultWithPosition(slot: ParticipantSlot): ParticipantSlot { return slot && { id: slot.id, position: slot.position, }; } /** * Returns the winner of a match. * * @param match The match. */ export function getWinner(match: MatchResults): ParticipantSlot { const winnerSide = getMatchResult(match); if (!winnerSide) return null; return match[winnerSide]; } /** * Returns the loser of a match. * * @param match The match. */ export function getLoser(match: MatchResults): ParticipantSlot { const winnerSide = getMatchResult(match); if (!winnerSide) return null; return match[getOtherSide(winnerSide)]; } /** * Returns the pre-computed winner for a match because of BYEs. * * @param opponents Two opponents. */ export function byeWinner(opponents: Duel): ParticipantSlot { if (opponents[0] === null && opponents[1] === null) // Double BYE. return null; // BYE. if (opponents[0] === null && opponents[1] !== null) // opponent1 BYE. return { id: opponents[1]!.id }; // opponent2. if (opponents[0] !== null && opponents[1] === null) // opponent2 BYE. return { id: opponents[0]!.id }; // opponent1. return { id: null }; // Normal. } /** * Returns the pre-computed winner for a match because of BYEs in a lower bracket. * * @param opponents Two opponents. */ export function byeWinnerToGrandFinal(opponents: Duel): ParticipantSlot { const winner = byeWinner(opponents); if (winner) winner.position = 1; return winner; } /** * Returns the pre-computed loser for a match because of BYEs. * * Only used for loser bracket. * * @param opponents Two opponents. * @param index The index of the duel in the round. */ export function byeLoser(opponents: Duel, index: number): ParticipantSlot { if (opponents[0] === null || opponents[1] === null) // At least one BYE. return null; // BYE. return { id: null, position: index + 1 }; // Normal. } /** * Returns the winner side or `null` if no winner. * * @param match A match's results. */ export function getMatchResult(match: MatchResults): Side | null { if (!isMatchCompleted(match)) return null; if (isMatchDrawCompleted(match)) return null; if (match.opponent1 === null && match.opponent2 === null) return null; let winner: Side | null = null; if (match.opponent1?.result === 'win' || match.opponent2 === null || match.opponent2.forfeit) winner = 'opponent1'; if (match.opponent2?.result === 'win' || match.opponent1 === null || match.opponent1.forfeit) { if (winner !== null) throw Error('There are two winners.'); winner = 'opponent2'; } return winner; } /** * Finds a position in a list of matches. * * @param matches A list of matches to search into. * @param position The position to find. */ export function findPosition(matches: Match[], position: number): ParticipantSlot { for (const match of matches) { if (match.opponent1?.position === position) return match.opponent1; if (match.opponent2?.position === position) return match.opponent2; } return null; } /** * Gets the side where the winner of the given match will go in the next match. * * @param matchNumber Number of the match. */ export function getSide(matchNumber: number): Side { return matchNumber % 2 === 1 ? 'opponent1' : 'opponent2'; } /** * Gets the other side of a match. * * @param side The side that we don't want. */ export function getOtherSide(side: Side): Side { return side === 'opponent1' ? 'opponent2' : 'opponent1'; } /** * Checks if a match is started. * * @param match Partial match results. */ export function isMatchStarted(match: Partial<MatchResults>): boolean { return match.opponent1?.score !== undefined || match.opponent2?.score !== undefined; } /** * Checks if a match is completed. * * @param match Partial match results. */ export function isMatchCompleted(match: Partial<MatchResults>): boolean { return isMatchByeCompleted(match) || isMatchForfeitCompleted(match) || isMatchResultCompleted(match); } /** * Checks if a match is completed because of a forfeit. * * @param match Partial match results. */ export function isMatchForfeitCompleted(match: Partial<MatchResults>): boolean { return match.opponent1?.forfeit !== undefined || match.opponent2?.forfeit !== undefined; } /** * Checks if a match is completed because of a either a draw or a win. * * @param match Partial match results. */ export function isMatchResultCompleted(match: Partial<MatchResults>): boolean { return isMatchDrawCompleted(match) || isMatchWinCompleted(match); } /** * Checks if a match is completed because of a draw. * * @param match Partial match results. */ export function isMatchDrawCompleted(match: Partial<MatchResults>): boolean { return match.opponent1?.result === 'draw' && match.opponent2?.result === 'draw'; } /** * Checks if a match is completed because of a win. * * @param match Partial match results. */ export function isMatchWinCompleted(match: Partial<MatchResults>): boolean { return match.opponent1?.result === 'win' || match.opponent2?.result === 'win' || match.opponent1?.result === 'loss' || match.opponent2?.result === 'loss'; } /** * Checks if a match is completed because of at least one BYE. * * A match "BYE vs. TBD" isn't considered completed yet. * * @param match Partial match results. */ export function isMatchByeCompleted(match: Partial<MatchResults>): boolean { return (match.opponent1 === null && match.opponent2?.id !== null) // BYE vs. someone || (match.opponent2 === null && match.opponent1?.id !== null) // someone vs. BYE || (match.opponent1 === null && match.opponent2 === null); // BYE vs. BYE } /** * Checks if a match's results can't be updated. * * @param match The match to check. */ export function isMatchUpdateLocked(match: MatchResults): boolean { return match.status === Status.Locked || match.status === Status.Waiting || match.status === Status.Archived; } /** * Checks if a match's participants can't be updated. * * @param match The match to check. */ export function isMatchParticipantLocked(match: MatchResults): boolean { return match.status >= Status.Running; } /** * Returns the status of a match based on the presence of the opponents. * * @param opponents The opponents of a match. */ export function getMatchByeStatus(opponents: Duel): Status { return getMatchStatus({ opponent1: opponents[0], opponent2: opponents[1], }); } /** * Indicates whether a match has at least one BYE or not. * * @param match Partial match results. */ export function hasBye(match: Partial<MatchResults>): boolean { return match.opponent1 === null || match.opponent2 === null; } /** * Returns the status of a match based on the results of a match. * * @param match Partial match results. */ export function getMatchStatus(match: Partial<MatchResults>): Status { if (hasBye(match)) // At least one BYE. return Status.Locked; if (match.opponent1?.id === null && match.opponent2?.id === null) // Two TBD opponents. return Status.Locked; if (match.opponent1?.id === null || match.opponent2?.id === null) // One TBD opponent. return Status.Waiting; if (isMatchCompleted(match)) return Status.Completed; if (isMatchStarted(match)) return Status.Running; return Status.Ready; } /** * Updates a match results based on an input. * * @param stored A reference to what will be updated in the storage. * @param match Input of the update. */ export function setMatchResults(stored: MatchResults, match: Partial<MatchResults>): { statusChanged: boolean, resultChanged: boolean, } { const completed = isMatchCompleted(match); const currentlyCompleted = isMatchCompleted(stored); handleOpponentsInversion(stored, match); const statusChanged = setScores(stored, match); if (completed && currentlyCompleted) { // Ensure everything is good. setCompleted(stored, match); return { statusChanged: false, resultChanged: true }; } if (completed && !currentlyCompleted) { setCompleted(stored, match); return { statusChanged: true, resultChanged: true }; } if (!completed && currentlyCompleted) { resetMatchResults(stored); return { statusChanged: true, resultChanged: true }; } return { statusChanged, resultChanged: false }; } /** * Resets the results of a match. (status, forfeit, result) * * @param stored A reference to what will be updated in the storage. */ export function resetMatchResults(stored: MatchResults): void { if (stored.opponent1) { stored.opponent1.forfeit = undefined; stored.opponent1.result = undefined; } if (stored.opponent2) { stored.opponent2.forfeit = undefined; stored.opponent2.result = undefined; } stored.status = getMatchStatus(stored); } /** * Gets the id of the opponent at the given side of the given match. * * @param match The match to get the opponent from. * @param side The side where to get the opponent from. */ export function getOpponentId(match: MatchResults, side: Side): number | null { const opponent = match[side]; return opponent && opponent.id; } /** * Gets the origin position of a side of a match. * * @param match The match. * @param side The side. */ export function getOriginPosition(match: Match, side: Side): number { const matchNumber = match[side]?.position; if (matchNumber === undefined) throw Error('Position is undefined.'); return matchNumber; } /** * Returns every loser in a list of matches. * * @param participants The list of participants. * @param matches A list of matches to get losers of. */ export function getLosers(participants: Participant[], matches: Match[]): Participant[][] { const losers: Participant[][] = []; let currentRound: number | null = null; let roundIndex = -1; for (const match of matches) { if (match.round_id !== currentRound) { currentRound = match.round_id; roundIndex++; losers[roundIndex] = []; } const loser = getLoser(match); if (loser === null) continue; losers[roundIndex].push(findParticipant(participants, loser)); } return losers; } /** * Makes final standings based on participants grouped by ranking. * * @param grouped A list of participants grouped by ranking. */ export function makeFinalStandings(grouped: Participant[][]): FinalStandingsItem[] { const standings: FinalStandingsItem[] = []; let rank = 1; for (const group of grouped) { for (const participant of group) { standings.push({ id: participant.id, name: participant.name, rank, }); } rank++; } return standings; } /** * Returns the decisive match of a Grand Final. * * @param type The type of Grand Final. * @param matches The matches in the Grand Final. */ export function getGrandFinalDecisiveMatch(type: GrandFinalType, matches: Match[]): Match { if (type === 'simple') return matches[0]; if (type === 'double') { const result = getMatchResult(matches[0]); if (result === 'opponent2') return matches[1]; return matches[0]; } throw Error('The Grand Final is disabled.'); } /** * Finds a participant in a list. * * @param participants The list of participants. * @param slot The slot of the participant to find. */ export function findParticipant(participants: Participant[], slot: ParticipantSlot): Participant { const participant = participants.find(participant => participant.id === slot?.id); if (!participant) throw Error('Participant not found.'); return participant; } /** * Gets the side the winner of the current match will go to in the next match. * * @param matchNumber Number of the current match. * @param roundNumber Number of the current round. * @param roundCount Count of rounds. * @param matchLocation Location of the current match. */ export function getNextSide(matchNumber: number, roundNumber: number, roundCount: number, matchLocation: BracketKind): Side { // The nextSide comes from the same bracket. if (matchLocation === 'loser_bracket' && roundNumber % 2 === 1) return 'opponent2'; // The nextSide comes from the loser bracket to the final group. if (matchLocation === 'loser_bracket' && roundNumber === roundCount) return 'opponent2'; return getSide(matchNumber); } /** * Gets the side the winner of the current match in loser bracket will go in the next match. * * @param matchNumber Number of the match. * @param nextMatch The next match. * @param roundNumber Number of the current round. */ export function getNextSideLoserBracket(matchNumber: number, nextMatch: Match, roundNumber: number): Side { // The nextSide comes from the WB. if (roundNumber > 1) return 'opponent1'; // The nextSide comes from the WB round 1. if (nextMatch.opponent1?.position === matchNumber) return 'opponent1'; return 'opponent2'; } export type SetNextOpponent = (nextMatch: Match, nextSide: Side, match?: Match, currentSide?: Side) => void; /** * Sets an opponent in the next match he has to go. * * @param nextMatch A match which follows the current one. * @param nextSide The side the opponent will be on in the next match. * @param match The current match. * @param currentSide The side the opponent is currently on. */ export function setNextOpponent(nextMatch: Match, nextSide: Side, match?: Match, currentSide?: Side): void { nextMatch[nextSide] = match![currentSide!] && { // Keep BYE. id: getOpponentId(match!, currentSide!), // This implementation of SetNextOpponent always has those arguments. position: nextMatch[nextSide]?.position, // Keep position. }; nextMatch.status = getMatchStatus(nextMatch); } /** * Resets an opponent in the match following the current one. * * @param nextMatch A match which follows the current one. * @param nextSide The side the opponent will be on in the next match. */ export function resetNextOpponent(nextMatch: Match, nextSide: Side): void { nextMatch[nextSide] = nextMatch[nextSide] && { // Keep BYE. id: null, position: nextMatch[nextSide]?.position, // Keep position. }; nextMatch.status = Status.Locked; } /** * Inverts opponents if requested by the input. * * @param stored A reference to what will be updated in the storage. * @param match Input of the update. */ export function handleOpponentsInversion(stored: MatchResults, match: Partial<MatchResults>): void { const id1 = match.opponent1?.id; const id2 = match.opponent2?.id; const storedId1 = stored.opponent1?.id; const storedId2 = stored.opponent2?.id; if (Number.isInteger(id1) && id1 !== storedId1 && id1 !== storedId2) throw Error('The given opponent1 ID does not exist in this match.'); if (Number.isInteger(id2) && id2 !== storedId1 && id2 !== storedId2) throw Error('The given opponent2 ID does not exist in this match.'); if (Number.isInteger(id1) && id1 === storedId2 || Number.isInteger(id2) && id2 === storedId1) invertOpponents(match); } /** * Inverts `opponent1` and `opponent2` in a match. * * @param match A match to update. */ export function invertOpponents(match: Partial<MatchResults>): void { [match.opponent1, match.opponent2] = [match.opponent2, match.opponent1]; } /** * Updates the scores of a match. * * @param stored A reference to what will be updated in the storage. * @param match Input of the update. * @returns `true` if the status of the match changed, `false` otherwise. */ export function setScores(stored: MatchResults, match: Partial<MatchResults>): boolean { // Skip if no score update. if (match.opponent1?.score === stored.opponent1?.score && match.opponent2?.score === stored.opponent2?.score) return false; const oldStatus = stored.status; stored.status = Status.Running; if (match.opponent1 && stored.opponent1) stored.opponent1.score = match.opponent1.score; if (match.opponent2 && stored.opponent2) stored.opponent2.score = match.opponent2.score; return stored.status !== oldStatus; } /** * Completes a match and handles results and forfeits. * * @param stored A reference to what will be updated in the storage. * @param match Input of the update. */ export function setCompleted(stored: MatchResults, match: Partial<MatchResults>): void { stored.status = Status.Completed; setResults(stored, match, 'win', 'loss'); setResults(stored, match, 'loss', 'win'); setResults(stored, match, 'draw', 'draw'); if (stored.opponent1 && !stored.opponent2) stored.opponent1.result = 'win'; // Win against opponent 2 BYE. if (!stored.opponent1 && stored.opponent2) stored.opponent2.result = 'win'; // Win against opponent 1 BYE. setForfeits(stored, match); } /** * Enforces the symmetry between opponents. * * Sets an opponent's result to something, based on the result on the other opponent. * * @param stored A reference to what will be updated in the storage. * @param match Input of the update. * @param check A result to check in each opponent. * @param change A result to set in each other opponent if `check` is correct. */ export function setResults(stored: MatchResults, match: Partial<MatchResults>, check: Result, change: Result): void { if (match.opponent1 && match.opponent2) { if (match.opponent1.result === 'win' && match.opponent2.result === 'win') throw Error('There are two winners.'); if (match.opponent1.result === 'loss' && match.opponent2.result === 'loss') throw Error('There are two losers.'); if (match.opponent1.forfeit === true && match.opponent2.forfeit === true) throw Error('There are two forfeits.'); } if (match.opponent1?.result === check) { if (stored.opponent1) stored.opponent1.result = check; else stored.opponent1 = { id: null, result: check }; if (stored.opponent2) stored.opponent2.result = change; else stored.opponent2 = { id: null, result: change }; } if (match.opponent2?.result === check) { if (stored.opponent2) stored.opponent2.result = check; else stored.opponent2 = { id: null, result: check }; if (stored.opponent1) stored.opponent1.result = change; else stored.opponent1 = { id: null, result: change }; } } /** * Sets forfeits for each opponent (if needed). * * @param stored A reference to what will be updated in the storage. * @param match Input of the update. */ export function setForfeits(stored: MatchResults, match: Partial<MatchResults>): void { if (match.opponent1?.forfeit === true) { if (stored.opponent1) stored.opponent1.forfeit = true; if (stored.opponent2) stored.opponent2.result = 'win'; else stored.opponent2 = { id: null, result: 'win' }; } if (match.opponent2?.forfeit === true) { if (stored.opponent2) stored.opponent2.forfeit = true; if (stored.opponent1) stored.opponent1.result = 'win'; else stored.opponent1 = { id: null, result: 'win' }; } } /** * Indicates if a seeding is filled with participants' names or IDs. * * @param seeding The seeding. */ export function isSeedingWithIds(seeding: Seeding): boolean { return seeding.some((value: string | number | null) => typeof value === 'number'); } /** * Extracts participants from a seeding, without the byes. * * @param tournamentId ID of the tournament. * @param seeding The seeding. */ export function extractParticipantsFromSeeding(tournamentId: number, seeding: Seeding): OmitId<Participant>[] { const withoutByes = seeding.filter(name => name !== null) as string[]; const participants = withoutByes.map<OmitId<Participant>>(name => ({ tournament_id: tournamentId, name, })); return participants; } /** * Returns participant slots mapped to the instances stored in the database thanks to their name. * * @param seeding The seeding. * @param database The participants stored in the database. * @param positions An optional list of positions (seeds) for a manual ordering. */ export function mapParticipantsNamesToDatabase(seeding: Seeding, database: Participant[], positions?: number[]): ParticipantSlot[] { return mapParticipantsToDatabase('name', seeding, database, positions); } /** * Returns participant slots mapped to the instances stored in the database thanks to their id. * * @param seeding The seeding. * @param database The participants stored in the database. * @param positions An optional list of positions (seeds) for a manual ordering. */ export function mapParticipantsIdsToDatabase(seeding: Seeding, database: Participant[], positions?: number[]): ParticipantSlot[] { return mapParticipantsToDatabase('id', seeding, database, positions); } /** * Returns participant slots mapped to the instances stored in the database thanks to a property of theirs. * * @param prop The property to search participants with. * @param seeding The seeding. * @param database The participants stored in the database. * @param positions An optional list of positions (seeds) for a manual ordering. */ export function mapParticipantsToDatabase(prop: keyof Participant, seeding: Seeding, database: Participant[], positions?: number[]): ParticipantSlot[] { const slots = seeding.map((slot, i) => { if (slot === null) return null; // BYE. const found = database.find(participant => participant[prop] === slot); if (!found) throw Error(`Participant ${prop} not found in database.`); return { id: found.id, position: i + 1 }; }); if (!positions) return slots; if (positions.length !== slots.length) throw Error('Not enough seeds in at least one group of the manual ordering.'); return positions.map(position => slots[position - 1]); // position = i + 1 } /** * Converts a list of matches to a seeding. * * @param matches The input matches. */ export function matchesToSeeding(matches: Match[]): ParticipantSlot[] { const flattened = ([] as ParticipantSlot[]).concat(...matches.map(match => [match.opponent1, match.opponent2])); return sortSeeding(flattened); } /** * Sorts the seeding with the BYEs in the correct position. * * @param slots A list of slots to sort. */ export function sortSeeding(slots: ParticipantSlot[]): ParticipantSlot[] { const withoutByes = slots.filter(v => v !== null); // a and b are not null because of the filter. // The slots are from seeding slots, thus they have a position. withoutByes.sort((a, b) => a!.position! - b!.position!); if (withoutByes.length === slots.length) return withoutByes; // Same for v and position. const placed = Object.fromEntries(withoutByes.map(v => [v!.position! - 1, v])); const sortedWithByes = Array.from({ length: slots.length }, (_, i) => placed[i] || null); return sortedWithByes; } /** * Returns only the non null elements. * * @param array The array to process. */ export function getNonNull<T>(array: Nullable<T>[]): T[] { // Use a TS type guard to exclude null from the resulting type. const nonNull = array.filter((element): element is T => element !== null); return nonNull; } /** * Returns a list of objects which have unique values of a specific key. * * @param array The array to process. * @param key The key to filter by. */ export function uniqueBy<T>(array: T[], key: (obj: T) => unknown): T[] { const seen = new Set(); return array.filter(item => { const value = key(item); if (!value) return true; if (seen.has(value)) return false; seen.add(value); return true; }); } /** * Makes the transition to a major round for duels of the previous round. The duel count is divided by 2. * * @param previousDuels The previous duels to transition from. */ export function transitionToMajor(previousDuels: Duel[]): Duel[] { const currentDuelCount = previousDuels.length / 2; const currentDuels: Duel[] = []; for (let duelIndex = 0; duelIndex < currentDuelCount; duelIndex++) { const prevDuelId = duelIndex * 2; currentDuels.push([ byeWinner(previousDuels[prevDuelId]), byeWinner(previousDuels[prevDuelId + 1]), ]); } return currentDuels; } /** * Makes the transition to a minor round for duels of the previous round. The duel count stays the same. * * @param previousDuels The previous duels to transition from. * @param losers Losers from the previous major round. * @param method The ordering method for the losers. */ export function transitionToMinor(previousDuels: Duel[], losers: ParticipantSlot[], method?: SeedOrdering): Duel[] { const orderedLosers = method ? ordering[method](losers) : losers; const currentDuelCount = previousDuels.length; const currentDuels: Duel[] = []; for (let duelIndex = 0; duelIndex < currentDuelCount; duelIndex++) { const prevDuelId = duelIndex; currentDuels.push([ orderedLosers[prevDuelId], byeWinner(previousDuels[prevDuelId]), ]); } return currentDuels; } /** * Sets the parent match to a completed status if all its child games are completed. * * @param parent The partial parent match to update. * @param childCount Child count of this parent match. * @param inRoundRobin Indicates whether the parent match is in a round-robin stage. */ export function setParentMatchCompleted(parent: Partial<MatchResults>, childCount: number, inRoundRobin: boolean): void { if (parent.opponent1?.score === undefined || parent.opponent2?.score === undefined) throw Error('Either opponent1, opponent2 or their scores are falsy.'); const minToWin = minScoreToWinBestOfX(childCount); if (parent.opponent1.score >= minToWin) { parent.opponent1.result = 'win'; return; } if (parent.opponent2.score >= minToWin) { parent.opponent2.result = 'win'; return; } if (parent.opponent1.score === parent.opponent2.score && parent.opponent1.score + parent.opponent2.score > childCount - 1) { if (inRoundRobin) { parent.opponent1.result = 'draw'; parent.opponent2.result = 'draw'; return; } throw Error('Match games result in a tie for the parent match.'); } } /** * Returns a parent match results based on its child games scores. * * @param storedParent The parent match stored in the database. * @param scores The scores of the match child games. */ export function getParentMatchResults(storedParent: Match, scores: Scores): Partial<MatchResults> { return { opponent1: { id: storedParent.opponent1 && storedParent.opponent1.id, score: scores.opponent1, }, opponent2: { id: storedParent.opponent2 && storedParent.opponent2.id, score: scores.opponent2, }, }; } /** * Gets the values which need to be updated in a match when it's updated on insertion. * * @param match The up to date match. */ export function getUpdatedMatchResults(match: MatchResults): MatchResults { return { status: match.status, opponent1: match.opponent1, opponent2: match.opponent2, }; } /** * Calculates the score of a parent match based on its child games. * * @param games The child games to process. */ export function getChildGamesResults(games: MatchGame[]): Scores { const scores = { opponent1: 0, opponent2: 0, }; for (const game of games) { const result = getMatchResult(game); if (result === 'opponent1') scores.opponent1++; else if (result === 'opponent2') scores.opponent2++; } return scores; } /** * Gets the default list of seeds for a round's matches. * * @param inLoserBracket Whether the match is in the loser bracket. * @param roundNumber The number of the current round. * @param roundCountLB The count of rounds in loser bracket. * @param matchCount The count of matches in the round. */ export function getSeeds(inLoserBracket: boolean, roundNumber: number, roundCountLB: number, matchCount: number): number[] { const seedCount = getSeedCount(inLoserBracket, roundNumber, roundCountLB, matchCount); return Array.from(Array(seedCount), (_, i) => i + 1); } /** * Gets the number of seeds for a round's matches. * * @param inLoserBracket Whether the match is in the loser bracket. * @param roundNumber The number of the current round. * @param roundCountLB The count of rounds in loser bracket. * @param matchCount The count of matches in the round. */ export function getSeedCount(inLoserBracket: boolean, roundNumber: number, roundCountLB: number, matchCount: number): number { ensureOrderingSupported(inLoserBracket, roundNumber, roundCountLB); return roundNumber === 1 ? matchCount * 2 : // Two per match for upper or lower bracket round 1. matchCount; // One per match for loser bracket minor rounds. } /** * Throws if the ordering is not supported on the given round number. * * @param inLoserBracket Whether the match is in the loser bracket. * @param roundNumber The number of the round. * @param roundCountLB The count of rounds in loser bracket. */ export function ensureOrderingSupported(inLoserBracket: boolean, roundNumber: number, roundCountLB: number): void { if (inLoserBracket && !isOrderingSupportedLoserBracket(roundNumber, roundCountLB)) throw Error('This round does not support ordering.'); if (!inLoserBracket && !isOrderingSupportedUpperBracket(roundNumber)) throw Error('This round does not support ordering.'); } /** * Indicates whether the ordering is supported in upper bracket, given the round number. * * @param roundNumber The number of the round. */ export function isOrderingSupportedUpperBracket(roundNumber: number): boolean { return roundNumber === 1; } /** * Indicates whether the ordering is supported in loser bracket, given the round number. * * @param roundNumber The number of the round. * @param roundCount The count of rounds. */ export function isOrderingSupportedLoserBracket(roundNumber: number, roundCount: number): boolean { return roundNumber === 1 || (roundNumber % 2 === 0 && roundNumber < roundCount); } /** * Returns the number of rounds an upper bracket has given the number of participants in the stage. * * @param participantCount The number of participants in the stage. */ export function getUpperBracketRoundCount(participantCount: number): number { return Math.log2(participantCount); } /** * Returns the count of round pairs (major & minor) in a loser bracket. * * @param participantCount The number of participants in the stage. */ export function getRoundPairCount(participantCount: number): number { return getUpperBracketRoundCount(participantCount) - 1; } /** * Determines whether a double elimination stage is really necessary. * * If the size is only two (less is impossible), then a lower bracket and a grand final are not necessary. * * @param participantCount The number of participants in the stage. */ export function isDoubleEliminationNecessary(participantCount: number): boolean { return participantCount > 2; } /** * Returns the real (because of loser ordering) number of a match in a loser bracket. * * @param participantCount The number of participants in a stage. * @param roundNumber Number of the round. * @param matchNumber Number of the match. * @param method The method used for the round. */ export function findLoserMatchNumber(participantCount: number, roundNumber: number, matchNumber: number, method?: SeedOrdering): number { const matchCount = getLoserRoundMatchCount(participantCount, roundNumber); const matchNumbers = Array.from(Array(matchCount), (_, i) => i + 1); const ordered = method ? ordering[method](matchNumbers) : matchNumbers; const actualMatchNumberLB = ordered.indexOf(matchNumber) + 1; return actualMatchNumberLB; } /** * Returns the count of matches in a round of a loser bracket. * * @param participantCount The number of participants in a stage. * @param roundNumber Number of the round. */ export function getLoserRoundMatchCount(participantCount: number, roundNumber: number): number { const roundPairIndex = Math.ceil(roundNumber / 2) - 1; const roundPairCount = getRoundPairCount(participantCount); const matchCount = Math.pow(2, roundPairCount - roundPairIndex - 1); return matchCount; } /** * Returns the ordering method of a round of a loser bracket. * * @param seedOrdering The list of seed orderings. * @param roundNumber Number of the round. */ export function getLoserOrdering(seedOrdering: SeedOrdering[], roundNumber: number): SeedOrdering | undefined { const orderingIndex = 1 + Math.floor(roundNumber / 2); return seedOrdering[orderingIndex]; } /** * Returns the number of rounds a lower bracket has given the number of participants in a double elimination stage. * * @param participantCount The number of participants in the stage. */ export function lowerBracketRoundCount(participantCount: number): number { const roundPairCount = getRoundPairCount(participantCount); return roundPairCount * 2; } /** * Returns the match number of the corresponding match in the next round by dividing by two. * * @param matchNumber The current match number. */ export function getDiagonalMatchNumber(matchNumber: number): number { return Math.ceil(matchNumber / 2); } /** * Returns the nearest power of two **greater than** or equal to the given number. * * @param input The input number. */ export function getNearestPowerOfTwo(input: number): number { return Math.pow(2, Math.ceil(Math.log2(input))); } /** * Returns the minimum score a participant must have to win a Best Of X series match. * * @param x The count of child games in the series. */ function minScoreToWinBestOfX(x: number): number { return (x + 1) / 2; } /** * Checks if a stage is a round-robin stage. * * @param stage The stage to check. */ export function isRoundRobin(stage: Stage): boolean { return stage.type === 'round_robin'; } /** * Throws if a stage is round-robin. * * @param stage The stage to check. */ export function ensureNotRoundRobin(stage: Stage): void { const inRoundRobin = isRoundRobin(stage); if (inRoundRobin) throw Error('Impossible to update ordering in a round-robin stage.'); } /** * Checks if a group is a winner bracket. * * It's not always the opposite of `inLoserBracket()`: it could be the only bracket of a single elimination stage. * * @param stageType Type of the stage. * @param groupNumber Number of the group. */ export function isWinnerBracket(stageType: StageType, groupNumber: number): boolean { return stageType === 'double_elimination' && groupNumber === 1; } /** * Checks if a group is a loser bracket. * * @param stageType Type of the stage. * @param groupNumber Number of the group. */ export function isLoserBracket(stageType: StageType, groupNumber: number): boolean { return stageType === 'double_elimination' && groupNumber === 2; } /** * Checks if a group is a final group (consolation final or grand final). * * @param stageType Type of the stage. * @param groupNumber Number of the group. */ export function isFinalGroup(stageType: StageType, groupNumber: number): boolean { return stageType === 'single_elimination' && groupNumber === 2 || stageType === 'double_elimination' && groupNumber === 3; } /** * Returns the type of group the match is located into. * * @param stageType Type of the stage. * @param groupNumber Number of the group. */ export function getMatchLocation(stageType: StageType, groupNumber: number): BracketKind { if (isWinnerBracket(stageType, groupNumber)) return 'winner_bracket'; if (isLoserBracket(stageType, groupNumber)) return 'loser_bracket'; if (isFinalGroup(stageType, groupNumber)) return 'final_group'; return 'single_bracket'; }
the_stack
import {WriteBatch} from '../batch/write-batch'; import {Connection} from '../connection/connection'; import {DocumentClientBatchTransformer} from '../transformer/document-client-batch-transformer'; import pLimit from 'p-limit'; import { BATCH_READ_MAX_ALLOWED_ATTEMPTS, BATCH_WRITE_CONCURRENCY_LIMIT, BATCH_WRITE_MAX_ALLOWED_ATTEMPTS, INTERNAL_ENTITY_ATTRIBUTE, MANAGER_NAME, STATS_TYPE, } from '@typedorm/common'; import { BatchGetResponseMap, BatchWriteItemRequestMap, DocumentClient, } from 'aws-sdk/clients/dynamodb'; import {isEmptyObject} from '../../helpers/is-empty-object'; import {ReadBatch} from '../batch/read-batch'; import {MetadataOptions} from '../transformer/base-transformer'; import {getUniqueRequestId} from '../../helpers/get-unique-request-id'; export enum REQUEST_TYPE { TRANSACT_WRITE = 'TRANSACT_WRITE', BATCH_WRITE = 'BATCH_WRITE', BATCH_READ = 'BATCH_READ', } /** * Batch manager write options */ export type BatchManagerWriteOptions = BatchManageBaseOptions; /** * Batch manager read options */ export type BatchManagerReadOptions = BatchManageBaseOptions; export interface BatchManageBaseOptions { /** * Max number of retries to perform before returning to client * @default BATCH_WRITE_MAX_ALLOWED_ATTEMPTS */ maxRetryAttempts?: number; /** * Max number of requests to run in parallel * @default BATCH_WRITE_CONCURRENCY_LIMIT */ requestsConcurrencyLimit?: number; /** * Exponential backoff multiplication factor to apply on back off algorithm * @default 1 */ backoffMultiplicationFactor?: number; } export class BatchManager { private _dcBatchTransformer: DocumentClientBatchTransformer; private _errorQueue: { requestInput: any; error: Error; requestType: REQUEST_TYPE; }[]; private limit = pLimit(BATCH_WRITE_CONCURRENCY_LIMIT); constructor(private connection: Connection) { this._dcBatchTransformer = new DocumentClientBatchTransformer(connection); this.resetErrorQueue(); } /** * Writes all given items to dynamodb using either batch or transaction api. * _Note_: Transaction api is always used when item being written is using a unique attribute * @param batch */ async write( batch: WriteBatch, options?: BatchManagerWriteOptions, metadataOptions?: MetadataOptions ) { this.resetErrorQueue(); const requestId = getUniqueRequestId(metadataOptions?.requestId); if (options?.requestsConcurrencyLimit) { this.limit = pLimit(options?.requestsConcurrencyLimit); } this.connection.logger.logInfo({ requestId, scope: MANAGER_NAME.BATCH_MANAGER, log: `Running a batch write request for ${batch.items.length} items`, }); // 0. transform batch request const { batchWriteRequestMapItems, lazyTransactionWriteItemListLoaderItems, transactionListItems, metadata, } = this._dcBatchTransformer.toDynamoWriteBatchItems(batch, { requestId, }); // 1.1. get transaction write items limits const transactionRequests = transactionListItems.map( ({rawInput, transformedInput}) => { // make all promises in pLimitable so their concurrency can be controlled properly return this.toLimited( () => this.connection.transactionManger.writeRaw(transformedInput, { requestId, returnConsumedCapacity: metadataOptions?.returnConsumedCapacity, }), // return original item when failed to process rawInput, REQUEST_TYPE.TRANSACT_WRITE ); } ); // 1.2. get all the lazy loaded promises // these are basically all the delete requests that uses unique keys const lazyTransactionRequests = lazyTransactionWriteItemListLoaderItems.map( ({rawInput, transformedInput}) => { return this.toLimited( async () => { const existingItem = await this.connection.entityManager.findOne( transformedInput.entityClass, transformedInput.primaryKeyAttributes, undefined, { requestId, returnConsumedCapacity: metadataOptions?.returnConsumedCapacity, } ); const deleteTransactionItemList = transformedInput.lazyLoadTransactionWriteItems( existingItem ); return this.connection.transactionManger.writeRaw( deleteTransactionItemList, { requestId, returnConsumedCapacity: metadataOptions?.returnConsumedCapacity, } ); }, // default item to return if failed to process rawInput, REQUEST_TYPE.TRANSACT_WRITE ); } ); // 1.3. get all batch toLimited promises const batchRequests = batchWriteRequestMapItems.map(batchRequestMap => { return this.toLimited( async () => this.connection.documentClient .batchWrite({ RequestItems: {...batchRequestMap}, ReturnConsumedCapacity: metadataOptions?.returnConsumedCapacity, }) .promise(), // for batch requests this returning item will be transformed to // original input items later batchRequestMap, REQUEST_TYPE.BATCH_WRITE ); }); const allRequests = [ ...transactionRequests, ...lazyTransactionRequests, ...batchRequests, ] as | Promise<DocumentClient.TransactWriteItemsOutput>[] | Promise<DocumentClient.BatchWriteItemOutput>[]; // 2. wait for all promises to finish const responses = await Promise.all(allRequests); // log stats responses.forEach((response, index) => { if (response.ConsumedCapacity) { this.connection.logger.logStats({ scope: MANAGER_NAME.BATCH_MANAGER, requestId, requestSegment: index, statsType: STATS_TYPE.CONSUMED_CAPACITY, consumedCapacityData: response.ConsumedCapacity, }); } }); // 3. run retry attempts // process all unprocessed items recursively until all are either done // or reached the retry limit const unprocessedItems = await this.recursiveHandleBatchWriteItemsResponse( responses, 0, // initially set the attempts counter to 0, options, { requestId, returnConsumedCapacity: metadataOptions?.returnConsumedCapacity, } ); // 4.1. reverse parse all failed inputs to original user inputs // filter or drop any empty values const transformedUnprocessedItems = unprocessedItems.flatMap( (unprocessedItemInput: DocumentClient.BatchWriteItemRequestMap) => this._dcBatchTransformer.toWriteBatchInputList( unprocessedItemInput, metadata ) ); // 4.2. reverse parse all unprocessed inputs to original user inputs // parse failed items to original input const failedItemsOriginalInput = this._errorQueue.flatMap(item => { if (item.requestType === REQUEST_TYPE.BATCH_WRITE) { return this._dcBatchTransformer.toWriteBatchInputList( item.requestInput, metadata ); } else if (item.requestType === REQUEST_TYPE.TRANSACT_WRITE) { return item.requestInput; } else { throw new Error( 'Unsupported request type, if this continues please file an issue on github' ); } }); // 5. return unProcessable or failed items to user return { unprocessedItems: transformedUnprocessedItems, failedItems: failedItemsOriginalInput, }; } /** * Reads all items given in batch with default eventually consistent read type * _Note_: Returned items are not guaranteed to be in the same sequence as requested */ async read( batch: ReadBatch, options?: BatchManagerReadOptions, metadataOptions?: MetadataOptions ) { this.resetErrorQueue(); const requestId = getUniqueRequestId(metadataOptions?.requestId); if (options?.requestsConcurrencyLimit) { this.limit = pLimit(options?.requestsConcurrencyLimit); } this.connection.logger.logInfo({ requestId, scope: MANAGER_NAME.BATCH_MANAGER, log: `Running a batch read request for ${batch.items.length} items`, }); // 0. transform batch request const { batchRequestItemsList, metadata, } = this._dcBatchTransformer.toDynamoReadBatchItems(batch, { requestId, }); // 1. get items requests with concurrency applied const batchRequests = batchRequestItemsList.map(batchRequestItems => { return this.toLimited( async () => this.connection.documentClient .batchGet({ RequestItems: {...batchRequestItems}, ReturnConsumedCapacity: metadataOptions?.returnConsumedCapacity, }) .promise(), batchRequestItems, REQUEST_TYPE.BATCH_READ ); }); // 2. wait for all promises to finish, either failed or hit the limit const initialResponses = await Promise.all(batchRequests); // log stats initialResponses.forEach((response, index) => { if (response.ConsumedCapacity) { this.connection.logger.logStats({ scope: MANAGER_NAME.BATCH_MANAGER, requestId, requestSegment: index, statsType: STATS_TYPE.CONSUMED_CAPACITY, consumedCapacityData: response.ConsumedCapacity, }); } }); // 3. run retries const { items, unprocessedItemsList, } = await this.recursiveHandleBatchReadItemsResponse( initialResponses, 0, options, [], { requestId, returnConsumedCapacity: metadataOptions?.returnConsumedCapacity, } ); // 4.1 transform responses to look like model const transformedItems = items.map(item => { const entityPhysicalName = item[INTERNAL_ENTITY_ATTRIBUTE.ENTITY_NAME]; if (!entityPhysicalName) { this.connection.logger.logWarn({ requestId, scope: MANAGER_NAME.ENTITY_MANAGER, log: `Item ${JSON.stringify( item )} is not known to TypeDORM there for transform was not run`, }); return item; } const {target} = this.connection.getEntityByPhysicalName( entityPhysicalName ); return this._dcBatchTransformer.fromDynamoEntity(target, item, { requestId, }); }) as unknown[]; // 4.2 transform unprocessed items const unprocessedTransformedItems = unprocessedItemsList?.flatMap( (item: DocumentClient.BatchGetRequestMap) => this._dcBatchTransformer.toReadBatchInputList(item, metadata) ); // 4.3 transform failed items const failedTransformedItems = this._errorQueue.flatMap(item => { this.connection.logger.logError({ requestId, scope: MANAGER_NAME.BATCH_MANAGER, log: item.error, }); return this._dcBatchTransformer.toReadBatchInputList( item.requestInput, metadata ); }); // 5. return all items return { items: transformedItems ?? [], unprocessedItems: unprocessedTransformedItems ?? [], failedItems: failedTransformedItems ?? [], }; } /** * Recursively parse batch requests until either all items are in or has reached retry limit * @param batchWriteItemOutputItems */ private async recursiveHandleBatchWriteItemsResponse( batchWriteItemOutputItems: DocumentClient.BatchWriteItemOutput[], totalAttemptsSoFar: number, options?: BatchManagerWriteOptions, metadataOptions?: MetadataOptions ): Promise<DocumentClient.BatchWriteItemRequestMap[]> { const unProcessedListItems = batchWriteItemOutputItems .filter( (response: DocumentClient.BatchWriteItemOutput) => response.UnprocessedItems && !isEmptyObject(response.UnprocessedItems) ) .map(item => item.UnprocessedItems!); // if there are no unprocessed items, return if (!unProcessedListItems.length) { return unProcessedListItems; } // abort when reached max attempts count // if no retry attempts are given, use default attempts limit if ( totalAttemptsSoFar === (options?.maxRetryAttempts ?? BATCH_WRITE_MAX_ALLOWED_ATTEMPTS) ) { this.connection.logger.logInfo({ scope: MANAGER_NAME.BATCH_MANAGER, log: `Reached max allowed attempts ${totalAttemptsSoFar}, aborting...`, requestId: metadataOptions?.requestId, }); return unProcessedListItems; } // backoff for x ms before retrying for unprocessed items await this.waitForExponentialBackoff( totalAttemptsSoFar, undefined, metadataOptions ); // organize unprocessed items into single "tableName-item" map const sortedUnprocessedItems = unProcessedListItems.reduce( (acc, unprocessedItems) => { Object.entries(unprocessedItems!).forEach( ([tableName, unprocessedRequests]) => { if (!acc[tableName]) { acc[tableName] = []; } // merge all items by tableName acc[tableName] = [...acc[tableName], ...unprocessedRequests]; } ); return acc; }, {} as BatchWriteItemRequestMap ); const batchRequestsItems = this._dcBatchTransformer.mapTableWriteItemsToBatchWriteItems( sortedUnprocessedItems ); // apply limit on all parallel requests const batchRequests = batchRequestsItems.map(batchRequestMap => { return this.toLimited( async () => this.connection.documentClient .batchWrite({ RequestItems: {...batchRequestMap}, ReturnItemCollectionMetrics: metadataOptions?.returnConsumedCapacity, }) .promise(), batchRequestMap, REQUEST_TYPE.BATCH_WRITE ); }); const batchRequestsResponses = (await Promise.all( batchRequests )) as DocumentClient.BatchWriteItemOutput[]; // log stats batchRequestsResponses.forEach((response, index) => { if (response.ConsumedCapacity) { this.connection.logger.logStats({ requestId: metadataOptions?.requestId, scope: MANAGER_NAME.BATCH_MANAGER, requestSegment: index, statsType: STATS_TYPE.CONSUMED_CAPACITY, consumedCapacityData: response.ConsumedCapacity, }); } }); return this.recursiveHandleBatchWriteItemsResponse( batchRequestsResponses, ++totalAttemptsSoFar, options, metadataOptions ); } private async recursiveHandleBatchReadItemsResponse( batchReadItemOutputList: DocumentClient.BatchGetItemOutput[], totalAttemptsSoFar: number, options?: BatchManagerReadOptions, responsesStore: DocumentClient.ItemList = [], metadataOptions?: MetadataOptions ): Promise<{ items: DocumentClient.ItemList; unprocessedItemsList?: DocumentClient.BatchGetRequestMap[]; }> { // save all responses from api to responses store const batchReadResponses = batchReadItemOutputList .filter( (response: DocumentClient.BatchGetItemOutput) => response.Responses && !isEmptyObject(response.Responses) ) .map( (response: DocumentClient.BatchGetItemOutput) => response.Responses! ); if (batchReadResponses.length) { const mappedResponsesItemList = batchReadResponses.flatMap( batchGetResponse => this.mapBatchGetResponseToItemList(batchGetResponse) ); responsesStore.push(...mappedResponsesItemList); } // recursively process all unprocessed items const unprocessedItemsList = batchReadItemOutputList.filter( (response: DocumentClient.BatchGetItemOutput) => response.UnprocessedKeys && !isEmptyObject(response.UnprocessedKeys) ); // if all items were successfully processed, return if (!unprocessedItemsList.length) { return { items: responsesStore, }; } // abort when reached max attempt count // if no retries provided use default BATCH_READ_MAX_ALLOWED_ATTEMPTS if ( totalAttemptsSoFar === (options?.maxRetryAttempts ?? BATCH_READ_MAX_ALLOWED_ATTEMPTS) ) { this.connection.logger.logInfo({ requestId: metadataOptions?.requestId, scope: MANAGER_NAME.BATCH_MANAGER, log: `Reached max allowed attempts ${totalAttemptsSoFar}, aborting...`, }); return { items: responsesStore, unprocessedItemsList: unprocessedItemsList.map( item => item.UnprocessedKeys! ), }; } // backoff before retrying await this.waitForExponentialBackoff( totalAttemptsSoFar, undefined, metadataOptions ); // aggregate all requests by table name const sortedUnprocessedItems = unprocessedItemsList.reduce( (acc, {UnprocessedKeys}: DocumentClient.BatchGetItemOutput) => { Object.entries(UnprocessedKeys!).forEach( ([tableName, unprocessedRequests]) => { if (!acc[tableName]) { acc[tableName] = { Keys: [], }; } acc[tableName].Keys.push(...unprocessedRequests.Keys); } ); return acc; }, {} as DocumentClient.BatchGetRequestMap ); const batchRequestsItemsList = this._dcBatchTransformer.mapTableReadItemsToBatchReadItems( sortedUnprocessedItems ); // apply limit const batchRequests = batchRequestsItemsList.map(batchRequestMap => { return this.toLimited( async () => this.connection.documentClient .batchGet({ RequestItems: {...batchRequestMap}, ReturnConsumedCapacity: metadataOptions?.returnConsumedCapacity, }) .promise(), batchRequestMap, REQUEST_TYPE.BATCH_READ ); }); const batchRequestsResponses = (await Promise.all( batchRequests )) as DocumentClient.BatchGetItemOutput[]; // log stats batchRequestsResponses.forEach((response, index) => { if (response.ConsumedCapacity) { this.connection.logger.logStats({ requestId: metadataOptions?.requestId, scope: MANAGER_NAME.BATCH_MANAGER, requestSegment: index, statsType: STATS_TYPE.CONSUMED_CAPACITY, consumedCapacityData: response.ConsumedCapacity, }); } }); return this.recursiveHandleBatchReadItemsResponse( batchRequestsResponses, ++totalAttemptsSoFar, options, // responses store containing responses from all requests responsesStore, metadataOptions ); } private resetErrorQueue() { this._errorQueue = []; } private mapBatchGetResponseToItemList(batchGetResponse: BatchGetResponseMap) { return Object.entries(batchGetResponse).flatMap( ([, batchResponse]) => batchResponse ); } /** * Returns promise that is Promise.all safe and also can be managed by p-limit * @param anyPromiseFactory * @param requestItem // request item input * @param requestType // request type */ private toLimited<T>( anyPromiseFactory: () => Promise<T>, requestItem: any, requestType: REQUEST_TYPE ) { return this.limit(async () => { try { const response = await anyPromiseFactory(); return response; } catch (err) { this._errorQueue.push({ requestInput: requestItem, error: err, requestType, }); // when any error is thrown while promises are running, return it // instead of throwing it to have other requests run as is without // interruptions return err as T; } }); } private waitForExponentialBackoff( attempts: number, multiplicationFactor = 1, metadataOptions?: MetadataOptions ) { multiplicationFactor = multiplicationFactor < 1 ? 1 : multiplicationFactor; return new Promise(resolve => { const backoffTime = this.exponentialBackoff( attempts, multiplicationFactor ); this.connection.logger.logInfo({ requestId: metadataOptions?.requestId, scope: MANAGER_NAME.BATCH_MANAGER, log: `${attempts} attempts so far, sleeping ${backoffTime}ms before retrying...`, }); setTimeout(resolve, backoffTime); }); } /** * @param attempts */ private exponentialBackoff(attempts: number, multiplicationFactor: number) { return Math.floor( Math.random() * 10 * Math.pow(2, attempts || 1) * multiplicationFactor ); } }
the_stack
import { Transformations, Environment, ConstructName, TypeSuffix, CTypeMap, GType, GenerateConfig } from './types' import Path from 'path' import { Utils } from './utils' import { Logger } from './logger' export const POD_TYPE_MAP_ARRAY = (environment: Environment): { guint8: string; gint8: string; gunichar: string } => { return { guint8: environment === 'gjs' ? 'Uint8Array' : 'any', // TODO // Int8Array would probably be more appropriate for gint8, but Uint8Array is better supported gint8: environment === 'gjs' ? 'Uint8Array' : 'any', // TODO gunichar: 'string', } } export const POD_TYPE_MAP = { utf8: 'string', none: 'void', double: 'number', guint32: 'number', guint16: 'number', gint16: 'number', gunichar: 'number', gint8: 'number', gint32: 'number', gushort: 'number', gfloat: 'number', gboolean: 'boolean', gpointer: 'object', gchar: 'number', guint: 'number', glong: 'number', gulong: 'number', gint: 'number', guint8: 'number', guint64: 'number', gint64: 'number', gdouble: 'number', gssize: 'number', gsize: 'number', long: 'number', object: 'any', gshort: 'number', filename: 'string', va_list: 'any', } export const C_TYPE_MAP = (targetFullName?: string, suffix: TypeSuffix = ''): CTypeMap => { return { 'char*': 'string', 'gchar*': 'string', 'gchar**': 'any', // FIXME GType: ((targetFullName === 'GObject-2.0' ? 'Type' : 'GObject.Type') + suffix) as GType, } } interface FullTypeMap { 'GObject.Value': string 'GObject.Closure': string 'GLib.ByteArray': string 'GLib.Bytes'?: string } // Gjs is permissive for byte-array in parameters but strict for out/return // See <https://discourse.gnome.org/t/gjs-bytearray-vs-glib-bytes/4900> export const FULL_TYPE_MAP = (environment: Environment, out = true): FullTypeMap => { let ba: string let gb: string | undefined if (environment === 'gjs') { ba = 'Uint8Array' if (out === false) { ba += ' | Gjs.byteArray.ByteArray' gb = 'GLib.Bytes | Uint8Array | Gjs.byteArray.ByteArray' } else { gb = undefined // No transformation } } else { // TODO ba = 'any' gb = 'any' } return { 'GObject.Value': 'any', 'GObject.Closure': 'Function', 'GLib.ByteArray': ba, 'GLib.Bytes': gb, } } export const RESERVED_VARIABLE_NAMES = [ 'in', 'function', 'true', 'false', 'break', 'arguments', 'eval', 'default', 'new', 'extends', 'with', 'var', 'class', 'delete', 'return', ] export const RESERVED_CLASS_NAMES = [ 'break', 'boolean', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'number', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'string', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield', ] export const RESERVED_FUNCTION_NAMES = ['false', 'true', 'break'] export const RESERVED_NAMESPACE_NAMES = {} export class Transformation { /** * Rules for the name conventions * For node-gtk naming conventions see https://github.com/romgrk/node-gtk#naming-conventions * For gjs see https://gjs-docs.gnome.org/ and https://wiki.gnome.org/Attic/Gjs */ private transformations: Transformations = { functionName: { node: { transformation: 'lowerCamelCase', }, gjs: { transformation: 'original', }, }, enumName: { node: { transformation: 'original', }, gjs: { transformation: 'original', }, }, enumValue: { node: { transformation: 'upperCase', }, gjs: { transformation: 'upperCase', }, }, signalName: { node: { transformation: 'original', }, gjs: { transformation: 'original', }, }, // GJS always re-writes - to _ (I think?) propertyName: { node: { transformation: 'lowerCamelCase', }, gjs: { transformation: 'underscores', }, }, parameterName: { node: { transformation: 'lowerCamelCase', }, gjs: { transformation: 'underscores', }, }, fieldName: { node: { transformation: 'lowerCamelCase', }, gjs: { transformation: 'underscores', }, }, constantName: { node: { transformation: 'original', }, gjs: { transformation: 'original', }, }, importName: { node: { transformation: 'upperCamelCase', }, gjs: { transformation: 'upperCamelCase', }, }, } private log: Logger constructor(moduleName = 'Transformation', private readonly config: GenerateConfig) { this.log = new Logger(config.environment, config.verbose, moduleName) } public transformModuleNamespaceName(name: string): string { name = this.transformNumericName(name) name = this.transform('importName', name) if (RESERVED_NAMESPACE_NAMES[name]) { name = `${name}_` } return name } public transformClassName(name: string): string { const originalName = `${name}` name = this.transformNumericName(name) if (RESERVED_CLASS_NAMES.includes(name)) { name = `${name}_` } if (originalName !== name) { this.log.warn(`Class name renamed from '${originalName}' to '${name}'`) } return name } public transformEnumName(name: string): string { name = this.transform('enumName', name) const originalName = `${name}` // For an example enum starting with a number see https://gjs-docs.gnome.org/nm10~1.20.8/nm.80211mode name = this.transformNumericName(name) if (RESERVED_CLASS_NAMES.includes(name)) { name = `${name}_` } if (originalName !== name) { this.log.warn(`Enum name renamed from '${originalName}' to '${name}'`) } return name } public transformFunctionName(name: string): string { name = this.transform('functionName', name) const originalName = `${name}` name = this.transformNumericName(name) if (RESERVED_FUNCTION_NAMES.includes(name)) { name = `${name}_TODO` } if (originalName !== name) { this.log.warn(`Function name renamed from '${originalName}' to '${name}'`) } return name } /** * E.g. GstVideo-1.0 has a class `VideoScaler` with a method called `2d` * or NetworkManager-1.0 has methods starting with `80211` */ public transformPropertyName(name: string, allowQuotes: boolean): string { name = this.transform('propertyName', name) const originalName = `${name}` if (RESERVED_VARIABLE_NAMES.includes(name)) { if (allowQuotes) name = `"${name}"` else name = `${name}_` } name = this.transformNumericName(name, allowQuotes) if (originalName !== name) { // this.log.warn(`Property name renamed from '${originalName}' to '${name}'`) } return name } public transformConstantName(name: string, allowQuotes: boolean): string { name = this.transform('constantName', name) const originalName = `${name}` if (RESERVED_VARIABLE_NAMES.includes(name)) { if (allowQuotes) name = `"${name}"` else name = `${name}_` } name = this.transformNumericName(name, allowQuotes) if (originalName !== name) { this.log.warn(`Constant name renamed from '${originalName}' to '${name}'`) } return name } public transformFieldName(name: string, allowQuotes: boolean): string { name = this.transform('fieldName', name) const originalName = `${name}` if (RESERVED_VARIABLE_NAMES.includes(name)) { if (allowQuotes) name = `"${name}"` else name = `${name}_` } name = this.transformNumericName(name, allowQuotes) if (originalName !== name) { this.log.warn(`Field name renamed from '${originalName}' to '${name}'`) } return name } public transformParameterName(name: string, allowQuotes: boolean): string { // Such a variable name exists in `GConf-2.0.d.ts` class `Engine` method `change_set_from_current` if (name === '...') { return '...args' } name = this.transform('parameterName', name) const originalName = `${name}` if (RESERVED_VARIABLE_NAMES.includes(name)) { if (allowQuotes) name = `"${name}"` else name = `${name}_` } name = this.transformNumericName(name, allowQuotes) if (originalName !== name) { this.log.warn(`Parameter name renamed from '${originalName}' to '${name}'`) } return name } /** * Fixes type names, e.g. Return types or enum definitions can not start with numbers * @param typeName */ public transformTypeName(name: string): string { name = this.transformNumericName(name) return name } public transform(construct: ConstructName, transformMe: string): string { const transformations = this.transformations[construct][this.config.environment].transformation if (transformations === 'original') { return transformMe } if (transformations === 'lowerCamelCase') { return Utils.lowerCamelCase(transformMe) } if (transformations === 'upperCamelCase') { return Utils.upperCamelCase(transformMe) } if (transformations === 'upperCase') { return transformMe.toUpperCase() } if (transformations === 'lowerCase') { return transformMe.toLowerCase() } if (transformations === 'underscores') { return transformMe.replace(/-|_/g, '_') } return transformMe } /** * In JavaScript there can be no variables, methods, class names or enum names that start with a number. * This method converts such names. * TODO ala prepends an `@` to numeric starting names how does gjs and node-gtk do that? * @param name * @param allowQuotes */ private transformNumericName(name: string, allowQuotes = false): string { if (Utils.isFirstCharNumeric(name)) { if (allowQuotes) name = `"${name}"` else name = `TODO_${name}` } return name } static getEnvironmentDir(environment: Environment, baseDir: string): string { if (environment == 'gjs') { return Path.join(baseDir, 'Gjs') } if (environment == 'node') { return Path.join(baseDir, 'node-gtk') } return baseDir } getEnvironmentDir(baseDir: string): string { return Transformation.getEnvironmentDir(this.config.environment, baseDir) } }
the_stack
import PencilIcon from '@geist-ui/react-icons/edit2'; import XIcon from '@geist-ui/react-icons/x'; import { Menu, Transition } from '@headlessui/react'; import clsx from 'clsx'; import { NextRouter, useRouter } from 'next/router'; import React, { Fragment, useState } from 'react'; import { Button } from '$/components/button'; import { Link } from '$/components/link'; import { appliedFilters, navigateToQuery, formattedFilters, Query, FilterPair } from './query'; import { FILTER_GROUPS, formatFilterGroup, filterGroupForFilter, FilterGroupKey, } from './stats/modals/filter'; import { Site } from './type'; function removeFilter(router: NextRouter, key: string, query: any) { const newOpts: any = { [key]: false, }; if (key === 'goal') { newOpts.props = false; } if (key === 'country') { newOpts.country_name = false; } if (key === 'region') { newOpts.region_name = false; } if (key === 'city') { newOpts.city_name = false; } navigateToQuery(router, query, newOpts); } function clearAllFilters(router: NextRouter, query: Query) { // eslint-disable-next-line unicorn/prefer-object-from-entries const newOpts = Object.keys(query.filters).reduce((acc, red) => ({ ...acc, [red]: false }), {}); navigateToQuery(router, query, newOpts); } function filterType(val: string) { if (typeof val === 'string' && val.startsWith('!')) { return ['is not', val.slice(1)]; } return ['is', val]; } function filterText(key: keyof typeof formattedFilters, rawValue: string, query: Query) { const [type, value] = filterType(rawValue); if (key === 'goal') { return ( <> Completed goal <b>{value}</b> </> ); } if (key === 'props') { const [metaKey, metaValue] = Object.entries(value)[0]; const eventName = query.filters.goal ? query.filters.goal : 'event'; return ( <> {eventName}.{metaKey} is <strong>{metaValue}</strong> </> ); } if (key === 'browser_version') { const browserName = query.filters.browser ? query.filters.browser : 'Browser'; return ( <> {browserName}.Version {type} <strong>{value}</strong> </> ); } if (key === 'os_version') { const osName = query.filters.os ? query.filters.os : 'OS'; return ( <> {osName}.Version {type} <strong>{value}</strong> </> ); } if (key === 'country') { const q = new URLSearchParams(window.location.search); const countryName = q.get('country_name'); return ( <> Country {type} <strong>{countryName}</strong> </> ); } if (key === 'region') { const q = new URLSearchParams(window.location.search); const regionName = q.get('region_name'); return ( <> Region {type} <strong>{regionName}</strong> </> ); } if (key === 'city') { const q = new URLSearchParams(window.location.search); const cityName = q.get('city_name'); return ( <> City {type} <strong>{cityName}</strong> </> ); } const formattedFilter = formattedFilters[key]; if (formattedFilter) { return ( <> {formattedFilter} {type} <strong>{value}</strong> </> ); } throw new Error(`Unknown filter: ${key}`); } function renderDropdownFilter( router: NextRouter, site: Site, [key, value]: FilterPair, query: Query, ) { if (key === 'props') { return ( <Menu.Item key={key}> <div className="flex items-center justify-between px-4 py-3 text-sm leading-tight sm:py-2" key={key + value} > <span className="inline-block w-full truncate">{filterText(key, value, query)}</span> <strong title={`Remove filter: ${formattedFilters[key]}`} className="ml-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500" onClick={() => removeFilter(router, key, query)} > <XIcon className="h-4 w-4" /> </strong> </div> </Menu.Item> ); } return ( <Menu.Item key={key}> <div className="flex items-center justify-between px-3 py-3 text-sm leading-tight sm:py-2 md:px-4" key={key + value} > <Link disabled title={`Edit filter: ${formattedFilters[key]}`} href={`/${encodeURIComponent(site.domain)}/filter/${filterGroupForFilter(key)}${ window.location.search }`} className="group flex w-full items-center justify-between" style={{ width: 'calc(100% - 1.5rem)' }} variant="plain" > <span className="inline-block w-full truncate">{filterText(key, value, query)}</span> <PencilIcon className="ml-1 h-4 w-4 cursor-pointer group-hover:text-indigo-700 dark:group-hover:text-indigo-500" /> </Link> <strong title={`Remove filter: ${formattedFilters[key]}`} className="ml-2 cursor-pointer hover:text-indigo-700 dark:hover:text-indigo-500" onClick={() => removeFilter(router, key, query)} > <XIcon className="h-4 w-4" /> </strong> </div> </Menu.Item> ); } function filterDropdownOption(site: Site, option: FilterGroupKey) { return ( <Menu.Item key={option}> {({ active }) => ( <Link disabled href={`/${encodeURIComponent(site.domain)}/filter/${option}${window.location.search}`} className={clsx( active ? `bg-gray-100 text-gray-1100` : `text-gray-1100`, `block px-4 py-2 text-sm font-medium`, )} > {formatFilterGroup(option)} </Link> )} </Menu.Item> ); } type DropdownContentProps = Pick<FiltersProps, 'query' | 'site'> & Pick<FiltersState, 'wrapped'>; function DropdownContent({ site, query, wrapped }: DropdownContentProps): JSX.Element { const [addingFilter, setAddingFilter] = useState(false); const router = useRouter(); if (wrapped === 0 || addingFilter) { return ( <> {(Object.keys(FILTER_GROUPS) as FilterGroupKey[]).map((option: FilterGroupKey) => filterDropdownOption(site, option), )} </> ); } return ( <> <Button variant="text" className="border-b border-gray-200 px-4 py-3 text-sm leading-tight hover:text-indigo-700 dark:border-gray-500 dark:hover:text-indigo-500 sm:py-2" onClick={() => setAddingFilter(true)} > + Add filter </Button> {appliedFilters(query).map((filter) => renderDropdownFilter(router, site, filter, query))} <Menu.Item key="clear"> <div className="border-t border-gray-200 px-4 py-3 text-sm leading-tight hover:cursor-pointer hover:text-indigo-700 dark:border-gray-500 dark:hover:text-indigo-500 sm:py-2" onClick={() => clearAllFilters(router, query)} > Clear All Filters </div> </Menu.Item> </> ); } export interface FiltersProps { className?: string; site: Site; query: Query; router: NextRouter; } interface FiltersState { viewport: number; // 0=unwrapped, 1=waiting to check, 2=wrapped wrapped: 0 | 1 | 2; } class Filters extends React.Component<FiltersProps, FiltersState> { constructor(props: FiltersProps) { super(props); this.state = { wrapped: 1, viewport: 1080, }; this.renderDropDown = this.renderDropDown.bind(this); this.handleResize = this.handleResize.bind(this); this.handleKeyup = this.handleKeyup.bind(this); } componentDidMount() { // document.addEventListener('mousedown', this.handleClick, false); window.addEventListener('resize', this.handleResize, false); document.addEventListener('keyup', this.handleKeyup); this.handleResize(); this.rewrapFilters(); } componentDidUpdate(prevProps: FiltersProps, prevState: FiltersState) { const { query } = this.props; const { viewport, wrapped } = this.state; if ( JSON.stringify(query) !== JSON.stringify(prevProps.query) || viewport !== prevState.viewport ) { // eslint-disable-next-line react/no-did-update-set-state this.setState({ wrapped: 1 }); } if (wrapped === 1 && prevState.wrapped !== 1) { this.rewrapFilters(); } } componentWillUnmount() { // document.removeEventListener('mousedown', this.handleClick, false); document.removeEventListener('keyup', this.handleKeyup); window.removeEventListener('resize', this.handleResize, false); } handleKeyup(e: KeyboardEvent) { const { query, router } = this.props; if (e.ctrlKey || e.metaKey || e.altKey) return; if (e.key === 'Escape') { clearAllFilters(router, query); } } handleResize() { this.setState({ viewport: window.innerWidth || 639 }); } // Checks if the filter container is wrapping items rewrapFilters() { const items = document.querySelector<HTMLElement>('#filters'); const { wrapped, viewport } = this.state; // Always wrap on mobile if (appliedFilters(this.props.query).length > 0 && viewport <= 768) { this.setState({ wrapped: 2 }); return; } this.setState({ wrapped: 0 }); // Don't rewrap if we're already properly wrapped, there are no DOM children, or there is only filter if (wrapped !== 1 || !items || appliedFilters(this.props.query).length === 1) { return; } let prevItem: DOMRect | null = null; // For every filter DOM Node, check if its y value is higher than the previous (this indicates a wrap) [...(items.childNodes as unknown as HTMLElement[])].forEach((item) => { const currItem = item.getBoundingClientRect(); if (prevItem && prevItem?.top < currItem.top) { this.setState({ wrapped: 2 }); } prevItem = currItem; }); } renderListFilter([key, value]: FilterPair, query: Query) { return ( <span key={key} title={value} className="mr-2 flex items-center rounded bg-white text-sm text-gray-700 shadow dark:bg-gray-600 dark:text-gray-300" > {key === 'props' ? ( <span className="flex h-full w-full items-center py-2 pl-3"> <span className="inline-block max-w-2xs truncate md:max-w-xs"> {filterText(key, value, query)} </span> </span> ) : ( <> <Link disabled title={`Edit filter: ${formattedFilters[key]}`} className="flex h-full w-full items-center py-2 pl-3 text-gray-1200" href={`/${encodeURIComponent(this.props.site.domain)}/filter/${filterGroupForFilter( key, )}${window.location.search}`} variant="plain" > <span className="inline-block max-w-2xs truncate md:max-w-xs"> {filterText(key, value, query)} </span> </Link> </> )} <span title={`Remove filter: ${formattedFilters[key]}`} className="flex h-full w-full cursor-pointer items-center px-2 text-gray-800 hover:text-indigo-900" onClick={() => removeFilter(this.props.router, key, query)} > <XIcon className="h-4 w-4" /> </span> </span> ); } // TODO: Add filter dropdown renderDropdownButton() { return null; // if (this.state.wrapped === 2) { // const filterCount = appliedFilters(this.props.query).length; // return ( // <> // <AdjustmentsIcon className="-ml-1 mr-1 h-4 w-4" aria-hidden="true" /> // {filterCount} Filter{filterCount === 1 ? '' : 's'} // </> // ); // } // return ( // <> // <PlusIcon className="-ml-1 mr-1 h-4 w-4 md:h-5 md:w-5" aria-hidden="true" /> // {/* This would have been a good use-case for JSX! But in the interest of keeping the breakpoint width logic with TailwindCSS, this is a better long-term way to deal with it. */} // <span className="sm:hidden">Filter</span> // <span className="hidden sm:inline-block">Add filter</span> // </> // ); } renderDropDown() { const { query, site } = this.props; return ( <Menu as="div" className="ml-auto md:relative"> {({ open }) => ( <> <div> <Menu.Button className="ml-auto flex cursor-pointer items-center rounded px-3 py-2 text-xs font-medium leading-tight text-gray-1100 hover:bg-gray-200 dark:hover:bg-gray-900 md:text-sm"> {this.renderDropdownButton()} </Menu.Button> </div> <Transition show={open} as={Fragment} enter="transition ease-out duration-100" enterFrom="opacity-0 scale-95" enterTo="opacity-100 scale-100" leave="transition ease-in duration-75" leaveFrom="opacity-100 scale-100" leaveTo="opacity-0 scale-95" > <Menu.Items static className="absolute left-0 right-0 z-10 mt-2 w-full origin-top-right md:absolute md:top-auto md:left-auto md:right-0 md:w-72" > <div className="rounded-md bg-white font-medium text-gray-800 shadow-lg ring-1 ring-black ring-opacity-5 dark:bg-gray-800 dark:text-gray-200" > <DropdownContent query={query} site={site} wrapped={this.state.wrapped} /> </div> </Menu.Items> </Transition> </> )} </Menu> ); } renderFilterList() { const { query } = this.props; if (this.state.wrapped !== 2) { return ( <div id="filters" className="flex flex-wrap"> {appliedFilters(query).map((filter) => this.renderListFilter(filter, query))} </div> ); } return null; } render() { return ( <> {this.renderFilterList()} {this.renderDropDown()} </> ); } } export default Filters;
the_stack
import { FileManager } from '../../../src/file-manager/base/file-manager'; import { NavigationPane } from '../../../src/file-manager/layout/navigation-pane'; import { DetailsView } from '../../../src/file-manager/layout/details-view'; import { Toolbar } from '../../../src/file-manager/actions/toolbar'; import { createElement, Browser, EventHandler, isNullOrUndefined, select } from '@syncfusion/ej2-base'; import { toolbarItems, toolbarItems1, data1, data2, data3, data4, data5, data6, data7, data8, data9, data12, data14, UploadData, data15, accessData1, accessDetails1, accessData2 } from '../data'; import { MenuOpenEventArgs } from '../../../src'; FileManager.Inject(Toolbar, NavigationPane, DetailsView); describe('FileManager control single selection LargeIcons view', () => { describe('context menu testing', () => { let mouseEventArgs: any, tapEvent: any; let feObj: any; let ele: HTMLElement; let originalTimeout: any; let type: string = ""; let count: number = 0; function menuopened(eventArgs: MenuOpenEventArgs) { count++; type = eventArgs.menuType; } beforeEach((done: Function): void => { jasmine.Ajax.install(); feObj = undefined; ele = createElement('div', { id: 'file' }); document.body.appendChild(ele); feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000; mouseEventArgs = { preventDefault: (): void => { }, stopImmediatePropagation: (): void => { }, target: null, type: null, shiftKey: false, ctrlKey: false, originalEvent: { target: null } }; tapEvent = { originalEvent: mouseEventArgs, tapCount: 1 }; setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; done(); }, 500); }); afterEach((): void => { count = 0; jasmine.Ajax.uninstall(); if (feObj) feObj.destroy(); ele.remove(); jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); it('setmodel context menu testing', () => { feObj.contextMenuSettings.visible = false; feObj.dataBind(); let el: any = document.getElementById(feObj.element.id + '_contextmenu'); expect(el !== null).toBe(true); expect(isNullOrUndefined((feObj as FileManager).contextmenuModule)).toBe(true); feObj.contextMenuSettings.visible = true; feObj.dataBind(); el = document.getElementById(feObj.element.id + '_contextmenu'); expect(el !== null).toBe(true); expect(isNullOrUndefined((feObj as FileManager).contextmenuModule)).toBe(false); }); // it('mouse click on refresh button', (done: Function) => { // let ele: any = document.getElementById(feObj.element.id + '_contextmenu'); // let menuObj: any = ele.ej2_instances[0]; // let lgli: any = document.getElementById('file_largeicons').querySelectorAll('li'); // mouseEventArgs.target = lgli[1]; // feObj.largeiconsviewModule.clickObj.tap(tapEvent); // mouseEventArgs.ctrlKey = true; // mouseEventArgs.target = lgli[2]; // feObj.largeiconsviewModule.clickObj.tap(tapEvent); // document.getElementById('file_tree').querySelectorAll('li')[1].remove(); // lgli[0].remove(); // document.getElementsByClassName('e-addressbar-ul')[0].querySelector('li').remove(); // let li: any = document.getElementById('file_tree').querySelectorAll('li'); // let tr: any = document.getElementById('file_largeicons').querySelectorAll('li'); // let ar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); // expect(li.length).toEqual(4); // expect(tr.length).toEqual(4); // expect(ar.length).toEqual(0); // expect(tr[0].classList.contains('e-active')).toBe(false); // expect(tr[0].querySelector('.e-frame')).toBe(null); // expect(tr[1].classList.contains('e-active')).toBe(true); // expect(tr[1].querySelector('.e-frame')).toBe(null); // let largeWrap: Element = feObj.largeiconsviewModule.element.children[0]; // let evt = document.createEvent('MouseEvents'); // evt.initEvent('contextmenu', true, true); // largeWrap.dispatchEvent(evt); // setTimeout(function () { // menuObj.element.querySelector('.e-fe-refresh').click(); // this.request = jasmine.Ajax.requests.mostRecent(); // this.request.respondWith({ // status: 200, // responseText: JSON.stringify(data1) // }); // jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; // setTimeout(function () { // let nli: any = document.getElementById('file_tree').querySelectorAll('li'); // let ntr: any = document.getElementById('file_largeicons').querySelectorAll('li'); // let nar: any = document.getElementsByClassName('e-addressbar-ul')[0].querySelectorAll('li'); // expect(nli.length).toEqual(5); // expect(ntr.length).toEqual(5); // expect(nar.length).toEqual(1); // expect(ntr[1].classList.contains('e-active')).toBe(false); // expect(ntr[1].querySelector('.e-frame')).toBe(null); // expect(ntr[2].classList.contains('e-active')).toBe(true); // expect(ntr[2].querySelector('.e-frame')).toBe(null); // done(); // }, 500); // }, 100); // }); it('folder context menu - menuType', () => { feObj.menuOpen = menuopened; feObj.dataBind(); var li = document.getElementById('file_largeicons').querySelectorAll('li'); mouseEventArgs.target = li[0]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); var evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); li[0].dispatchEvent(evt); expect(count).toBe(1); expect(type).toBe("folder"); }); it('file context menu - menuType', (done: Function) => { feObj.menuOpen = menuopened; feObj.dataBind(); document.getElementById('file_tb_refresh').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); setTimeout(function () { let li_file: any = document.getElementById('file_largeicons').querySelectorAll('li'); mouseEventArgs.target = li_file[4]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li_file[4].dispatchEvent(evt); expect(count).toBe(1); expect(type).toBe("file"); done(); }, 500); }); it('treeView - contextmenu menuType', () => { feObj.menuOpen = menuopened; feObj.dataBind(); var li = document.getElementById('file_tree').querySelectorAll('li'); mouseEventArgs.target = li[0]; var evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); li[0].dispatchEvent(evt); expect(count).toBe(1); expect(type).toBe('folder'); }) it('layout - contextmenu menuType', () => { feObj.menuOpen = menuopened; feObj.dataBind(); var layout = document.querySelector('#file_largeicons'); mouseEventArgs.target = layout; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); var evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); layout.dispatchEvent(evt); expect(count).toBe(1); expect(type).toBe('layout'); }) it("Contextmenu - custom menu items in folder", () => { feObj.contextMenuSettings = { file: ['Open', '|', 'Delete', 'Download', 'Rename', '|', 'Details', "Openinnewwindow", "OpeninVS", "|", "Giveaccessto"], folder: ['Open', '|', 'Delete', 'Rename', 'Download', '|', 'Details', "Custom1", "Custom2", "Custom3"], layout: ['SortBy', 'View', 'Refresh', '|', 'NewFolder', 'Upload', '|', 'Details', '|', 'SelectAll', "Custom1", "Custom2", "Custom3"] }; feObj.menuOpen = menuopened; feObj.dataBind(); var Li = document.querySelectorAll("#file_largeicons .e-large-icon")[2]; mouseEventArgs.target = Li; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); var evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); Li.dispatchEvent(evt); var menuItems = document.querySelectorAll("#file_contextmenu .e-menu-item").length; expect(menuItems).toBe(10); expect(count).toBe(1); expect(type).toBe('folder'); }); it("Contextmenu - custom menu items in file", (done: Function) => { feObj.contextMenuSettings = { file: ['Open', '|', 'Delete', 'Download', 'Rename', '|', 'Details', "Openinnewwindow", "OpeninVS", "|", "Giveaccessto"], folder: ['Open', '|', 'Delete', 'Rename', 'Download', '|', 'Details', "Custom1", "Custom2", "Custom3"], layout: ['SortBy', 'View', 'Refresh', '|', 'NewFolder', 'Upload', '|', 'Details', '|', 'SelectAll', "Custom1", "Custom2", "Custom3"] }; feObj.menuOpen = menuopened; feObj.dataBind(); document.getElementById('file_tb_refresh').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(data1) }); setTimeout(function () { let li_file: any = document.getElementById('file_largeicons').querySelectorAll('li'); mouseEventArgs.target = li_file[4]; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); li_file[4].dispatchEvent(evt); var menuItems = document.querySelectorAll("#file_contextmenu .e-menu-item").length; expect(menuItems).toBe(11); expect(count).toBe(1); expect(type).toBe("file"); done(); }, 500); }); it("Contextmenu - custom menu items in layout", () => { feObj.contextMenuSettings = { file: ['Open', '|', 'Delete', 'Download', 'Rename', '|', 'Details', "Openinnewwindow", "OpeninVS", "|", "Giveaccessto"], folder: ['Open', '|', 'Delete', 'Rename', 'Download', '|', 'Details', "Custom1", "Custom2", "Custom3"], layout: ['SortBy', 'View', 'Refresh', '|', 'NewFolder', 'Upload', '|', 'Details', '|', 'SelectAll', "Custom1", "Custom2", "Custom3"] }; feObj.menuOpen = menuopened; feObj.dataBind(); var layout = document.querySelector('#file_largeicons'); mouseEventArgs.target = layout; tapEvent.tapCount = 1; feObj.largeiconsviewModule.clickObj.tap(tapEvent); var evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); layout.dispatchEvent(evt); var menuItems = document.querySelectorAll("#file_contextmenu .e-menu-item").length; expect(menuItems).toBe(13); expect(count).toBe(1); expect(type).toBe("layout"); }); }); describe('access control context menu testing', () => { let feObj: any; let ele: HTMLElement; let originalTimeout: any; let mouseEventArgs: any, tapEvent: any; beforeEach((): void => { jasmine.Ajax.install(); feObj = undefined; ele = createElement('div', { id: 'file' }); document.body.appendChild(ele); originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000; mouseEventArgs = { preventDefault: (): void => { }, stopImmediatePropagation: (): void => { }, target: null, type: null, shiftKey: false, ctrlKey: false, originalEvent: { target: null } }; tapEvent = { originalEvent: mouseEventArgs, tapCount: 1 }; }); afterEach((): void => { jasmine.Ajax.uninstall(); if (feObj) feObj.destroy(); ele.remove(); jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; }); it('mouse click on new folder button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); document.getElementById('file_largeicons').dispatchEvent(evt); document.getElementById('file_cm_newfolder').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(5); expect(largeLi1.length).toEqual(9); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(4); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi1[1].classList.contains('e-fe-hidden')).toBe(true); done(); }, 500); }); it('mouse click on upload button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); document.getElementById('file_largeicons').dispatchEvent(evt); document.getElementById('file_cm_upload').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(5); expect(largeLi1.length).toEqual(9); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(4); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi1[1].classList.contains('e-fe-hidden')).toBe(true); done(); }, 500); }); it('mouse click on refresh button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); document.getElementById('file_largeicons').dispatchEvent(evt); document.getElementById('file_cm_refresh').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(5); expect(largeLi1.length).toEqual(9); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(4); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi1[1].classList.contains('e-fe-hidden')).toBe(true); done(); }, 500); }, 500); }); it('mouse click on rename button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_rename').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); done(); }, 500); }); it('mouse click on delete button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_delete').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(5); expect(largeLi1.length).toEqual(9); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(4); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi1[1].classList.contains('e-fe-hidden')).toBe(true); done(); }, 500); }); it('mouse click on download button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_download').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); done(); }, 500); }); it('mouse click on details button', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents') evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_details').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessDetails1) }); setTimeout(function () { let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerHTML).toEqual("Downloads"); expect(dialogObj.element.querySelectorAll('td')[8].innerHTML).toEqual("Permission"); done(); }, 500); }, 500); }); it('mouse click on delete button with two items selected', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[0]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); mouseEventArgs.target = largeLi[1]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_delete').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(5); expect(largeLi1.length).toEqual(9); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(4); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi1[1].classList.contains('e-fe-hidden')).toBe(true); done(); }, 500); }); it('mouse click on download button with two items selected', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[0]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); mouseEventArgs.target = largeLi[1]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_download').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); done(); }, 500); }); it('mouse click on details button with two items selected', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[0]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); mouseEventArgs.target = largeLi[1]; mouseEventArgs.ctrlKey = true; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_details').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessDetails1) }); setTimeout(function () { let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerHTML).toEqual("Downloads"); expect(dialogObj.element.querySelectorAll('td')[8].innerHTML).toEqual("Permission"); done(); }, 500); }, 500); }); it('mouse click on open button with non access folder/files', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[1]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[1].dispatchEvent(evt); document.getElementById('file_cm_open').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); dialogObj.element.querySelector('.e-primary').click(); mouseEventArgs.target = largeLi[7]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt1 = document.createEvent('MouseEvents'); evt1.initEvent('contextmenu', true, true); largeLi[7].dispatchEvent(evt1); document.getElementById('file_cm_open').click(); expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); done(); }, 500); }); it('mouse click on open button with access folder/files', (done: Function) => { feObj = new FileManager({ view: 'LargeIcons', allowMultiSelection: false, ajaxSettings: { url: '/FileAccessOperations', uploadUrl: '/Upload', downloadUrl: '/Download', getImageUrl: '/GetImage' }, showThumbnail: false }); feObj.appendTo('#file'); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData1) }); setTimeout(function () { let menuObj: any = (document.getElementById(feObj.element.id + '_contextmenu') as any).ej2_instances[0]; menuObj.animationSettings = { effect: 'None' }; menuObj.dataBind(); let treeObj: any = (document.getElementById("file_tree") as any).ej2_instances[0]; let treeLi: any = treeObj.element.querySelectorAll('li'); let largeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi.length).toEqual(5); expect(largeLi.length).toEqual(9); let aTreeLi: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi.length).toEqual(2); expect(aLargeLi.length).toEqual(4); expect(treeLi[2].classList.contains('e-fe-hidden')).toBe(true); expect(largeLi[1].classList.contains('e-fe-hidden')).toBe(true); mouseEventArgs.target = largeLi[0]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt = document.createEvent('MouseEvents'); evt.initEvent('contextmenu', true, true); largeLi[0].dispatchEvent(evt); document.getElementById('file_cm_open').click(); this.request = jasmine.Ajax.requests.mostRecent(); this.request.respondWith({ status: 200, responseText: JSON.stringify(accessData2) }); setTimeout(function () { let treeLi1: any = treeObj.element.querySelectorAll('li'); let largeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item'); expect(treeLi1.length).toEqual(7); expect(largeLi1.length).toEqual(12); let aTreeLi1: any = treeObj.element.querySelectorAll('li.e-fe-hidden'); let aLargeLi1: any = document.getElementById('file_largeicons').querySelectorAll('.e-list-item.e-fe-hidden'); expect(aTreeLi1.length).toEqual(2); expect(aLargeLi1.length).toEqual(5); expect(treeLi1[2].classList.contains('e-fe-hidden')).toBe(false); expect(largeLi1[2].classList.contains('e-fe-hidden')).toBe(true); let evt1 = document.createEvent('MouseEvents'); evt1.initEvent('contextmenu', true, true); largeLi1[2].dispatchEvent(evt1); document.getElementById('file_cm_open').click(); let dialogObj: any = (document.getElementById("file_dialog") as any).ej2_instances[0]; expect(dialogObj.element.querySelector('.e-dlg-header').innerText).toEqual("Access Denied"); dialogObj.element.querySelector('.e-primary').click(); mouseEventArgs.target = largeLi1[7]; feObj.largeiconsviewModule.clickObj.tap(tapEvent); let evt2 = document.createEvent('MouseEvents'); evt2.initEvent('contextmenu', true, true); largeLi1[7].dispatchEvent(evt2); document.getElementById('file_cm_open').click(); let dialogObj1: any = (document.getElementById("file_img_dialog") as any).ej2_instances[0]; expect(dialogObj1.element.querySelector('.e-dlg-header').innerHTML).toEqual("4.jpg"); done(); }, 500); }, 500); }); }); });
the_stack
import * as vscode from "vscode"; import * as WebSocket from 'ws'; import { Constants } from "./constants"; import { LeoBridgePackage, LeoAction } from "./types"; import { LeoIntegration } from "./leoIntegration"; import { LeoAsync } from "./leoAsync"; /** * * Handles communication with the leobridgeserver.py python script via websockets * This implements a bridge-facing action stack, (push on top, remove bottom) * 'actions' get sent to Leo, and resolve a promise with the result when the answer comes back. * This 'stack' concept is similar to the 'CommandStack' class used for vscode's user interactions. */ export class LeoBridge { private _callStack: LeoAction[] = []; private _actionBusy: boolean = false; // Action was started from the bottom, but has yet to resolve private _leoBridgeSerialId: number = 0; // TODO : Error checking (should be Constants.STARTING_PACKAGE_ID or 0 or 2...?) private _readyPromise: Promise<LeoBridgePackage> | undefined; private _websocket: WebSocket | null = null; private _leoAsync: LeoAsync; private _receivedTotal: number = 0; // TODO : #10 @boltex See if this can help with anaconda/miniconda issues // private _hasbin = require('hasbin'); constructor( private _context: vscode.ExtensionContext, private _leoIntegration: LeoIntegration ) { this._leoAsync = new LeoAsync(_context, _leoIntegration); } /** * * Places an action on top of a stack, to be resolved from the bottom * @param p_action Command string to be performed by Leo via leobridgeserver.py * @param p_jsonParam Optional JSON parameter for the specified action * @param p_deferredPayload Used to build this._readyPromise that resolves itself at startup * @param p_preventCall Flag for special action used to build this._readyPromise that resolves itself at startup * @returns a Promise that will contain the JSON package answered back by leobridgeserver.py */ public action(p_action: string, p_jsonParam = "null", p_deferredPayload?: LeoBridgePackage, p_preventCall?: boolean): Promise<LeoBridgePackage> { return new Promise((p_resolve, p_reject) => { const w_action: LeoAction = { parameter: this._buildActionParameter(p_action, p_jsonParam), deferredPayload: p_deferredPayload ? p_deferredPayload : undefined, resolveFn: p_resolve, rejectFn: p_reject }; this._callStack.push(w_action); if (!p_preventCall) { this._callAction(); } }); } /** * * Busy state of the leoBridge's command stack * @returns true if leoBridge's command stack still has unresolved actions */ public isBusy(): boolean { return this._actionBusy || !!this._callStack.length; } /** * * Actions invoked by Leo that can be called asynchronously at any time * @param w_parsedData that contains an 'async' string member, * that was parsed from a _websocket.onmessage package */ private _asyncAction(w_parsedData: any): void { if (w_parsedData && w_parsedData.async && (typeof w_parsedData.async === "string")) { switch (w_parsedData.async) { case Constants.ASYNC_ACTIONS.ASYNC_LOG: { this._leoAsync.log(w_parsedData.log, w_parsedData.color); break; } case Constants.ASYNC_ACTIONS.ASYNC_REFRESH: { this._leoAsync.refresh(w_parsedData); break; } case Constants.ASYNC_ACTIONS.ASYNC_ASK: { this._leoAsync.showAskModalDialog(w_parsedData); break; } case Constants.ASYNC_ACTIONS.ASYNC_WARN: { this._leoAsync.showWarnModalMessage(w_parsedData); break; } case Constants.ASYNC_ACTIONS.ASYNC_INFO: { this._leoAsync.showChangesDetectedInfoMessage(w_parsedData); break; } case Constants.ASYNC_ACTIONS.ASYNC_INTERVAL: { console.log("interval ", w_parsedData); // 'ping' interval for debugging break; } default: { console.error("[leoIntegration] Unknown async action ", w_parsedData); break; } } } else { console.error("[leoIntegration] Unknown async command from leoBridge"); } } /** * * Build JSON string for action parameter to the leoBridge * @param p_action Action string to be invoked as command by Leo in the leobridgeserver.py script * @param p_jsonParam Optional JSON string to be added as a 'param' to the action sent to Leo * @returns the JSON string built from the action string and the parameters */ private _buildActionParameter(p_action: string, p_jsonParam?: string): string { return "{\"id\":" + (++this._leoBridgeSerialId) + // no quotes, serial id is a number, pre incremented ", \"action\": \"" + p_action + // action is string so surround with quotes "\", \"param\":" + p_jsonParam + // param is already json, no need for added quotes "}"; } /** * * Resolves promises with the answers from an action that was finished * @param p_object Parsed data that was given as the answer by the Leo command that finished */ private _resolveBridgeReady(p_object: any): void { let w_bottomAction = this._callStack.shift(); if (w_bottomAction) { if (w_bottomAction.deferredPayload) { // Used when the action already has a return value ready but is also waiting for python's side // We check if it's really the initial first, then replace the id and pass the results. if (w_bottomAction.deferredPayload.id === Constants.STARTING_PACKAGE_ID) { p_object.id = Constants.STARTING_PACKAGE_ID; } w_bottomAction.resolveFn(p_object); // given back with id=1 ! } else { w_bottomAction.resolveFn(p_object); } this._actionBusy = false; } else { console.error("[leoBridge] Error stack empty"); } } /** * * Rejects an action from the bottom of the stack * @param p_reason Given rejection 'reason' */ private _rejectAction(p_reason: string): void { const w_bottomAction = this._callStack.shift(); if (w_bottomAction) { w_bottomAction.rejectFn(p_reason); } } /** * * Sends an action from the bottom of the stack */ private _callAction(): void { if (this._callStack.length && !this._actionBusy) { this._actionBusy = true; // launch / resolve bottom one const w_action = this._callStack[0]; this._send(w_action.parameter + "\n"); } } /** * * JSON.parse encased in a Try/Catch block * @param p_jsonStr The JSON string to be parsed * @returns The resulting object or 'false' if unsuccessful */ private _tryParseJSON(p_jsonStr: string): boolean | any { try { var w_object = JSON.parse(p_jsonStr); // JSON.parse(null) returns null, and typeof null === "object", null is falsy, so this suffices: if (w_object && typeof w_object === "object") { return w_object; } } catch (e) { console.error('[leoBridge] JSON was invalid: ' + p_jsonStr); } return false; } /** * * Process data that came from the Leo process * @param p_data given JSON data */ private _processAnswer(p_data: string): void { // console.log('got data', p_data); const w_parsedData = this._tryParseJSON(p_data); if (w_parsedData && (w_parsedData.id === 0 || w_parsedData.id)) { this._resolveBridgeReady(w_parsedData); this._callAction(); } else if (w_parsedData && w_parsedData.async) { // * Check for async messages such as log pane entries or other this._asyncAction(w_parsedData); } else { // unprocessed/unknown python output console.error("[leoBridge] Unprocessed or unknown JSON received: ", p_data); } } /** * * Create a websocket connection to a Leo server * @param p_port optional port number to override config port * @returns A promise for a LeoBridgePackage object containing only an 'id' member of 1 that will resolve when the 'leoBridge' is established */ public initLeoProcess(p_port?: number): Promise<LeoBridgePackage> { this._websocket = new WebSocket( Constants.TCPIP_DEFAULT_PROTOCOL + this._leoIntegration.config.connectionAddress + ":" + (p_port ? p_port : this._leoIntegration.config.connectionPort) ); // * Capture the python process output this._websocket.onmessage = (p_event) => { this._receivedTotal++; if (p_event.data) { this._processAnswer(p_event.data.toString()); } }; this._websocket.onerror = (p_event: WebSocket.ErrorEvent) => { console.error(`Websocket error: ${p_event.message}`); }; this._websocket.onclose = (p_event: WebSocket.CloseEvent) => { // * Disconnected from server // console.log(`Websocket closed, code: ${p_event.code}`); if (!this._leoIntegration.activated) { return; } this._rejectAction(`Websocket closed, code: ${p_event.code}`); // TODO : Implement a better connection error handling if (this._leoIntegration.leoStates.leoBridgeReady) { this._leoIntegration.cancelConnect(`Websocket closed, code: ${p_event.code}`); } }; // * Start first with 'preventCall' set to true: no need to call anything for the first 'ready' this._readyPromise = this.action("", "", { id: Constants.STARTING_PACKAGE_ID }, true); return this._readyPromise; // This promise will resolve when the started python process starts } /** * * Closes the websocket connection */ public closeLeoProcess(): void { if (this._websocket) { this._websocket.close(1001, "Quitting LeoInteg"); // console.log('websocket closed'); } else { // console.warn('LeoInteg websocket close called without websocket active'); } } /** * * Send into the python process input * @param p_data JSON Message string to be sent to leobridgeserver.py */ private _send(p_data: string): void { if (this._readyPromise) { this._readyPromise.then(() => { // using '.then' that was surely resolved already: to be buffered in case process isn't ready. if (this._websocket && this._websocket.OPEN) { this._websocket.send(p_data); // p_message should be json } }); } } }
the_stack
type UnicodeBlockLookup = {[key: string]: (char: number) => boolean}; const unicodeBlockLookup: UnicodeBlockLookup = { // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F, 'Latin-1 Supplement': (char) => char >= 0x0080 && char <= 0x00FF, // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F, // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F, // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF, // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF, // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F, // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF, // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF, // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F, // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F, //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF, 'Arabic': (char) => char >= 0x0600 && char <= 0x06FF, //'Syriac': (char) => char >= 0x0700 && char <= 0x074F, 'Arabic Supplement': (char) => char >= 0x0750 && char <= 0x077F, // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF, // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF, // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F, // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F, // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F, 'Arabic Extended-A': (char) => char >= 0x08A0 && char <= 0x08FF, // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F, // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF, // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F, // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF, // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F, // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF, // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F, // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF, // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F, // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF, // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F, // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF, // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF, // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F, // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF, 'Hangul Jamo': (char) => char >= 0x1100 && char <= 0x11FF, // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F, // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F, // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF, 'Unified Canadian Aboriginal Syllabics': (char) => char >= 0x1400 && char <= 0x167F, // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F, // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF, // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F, // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F, // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F, // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F, 'Khmer': (char) => char >= 0x1780 && char <= 0x17FF, // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF, 'Unified Canadian Aboriginal Syllabics Extended': (char) => char >= 0x18B0 && char <= 0x18FF, // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F, // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F, // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF, // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF, // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F, // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF, // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF, // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F, // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF, // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF, // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F, // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F, // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F, // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF, // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF, // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF, // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F, // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF, // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF, // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF, // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF, 'General Punctuation': (char) => char >= 0x2000 && char <= 0x206F, // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F, // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF, // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF, 'Letterlike Symbols': (char) => char >= 0x2100 && char <= 0x214F, 'Number Forms': (char) => char >= 0x2150 && char <= 0x218F, // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF, // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF, 'Miscellaneous Technical': (char) => char >= 0x2300 && char <= 0x23FF, 'Control Pictures': (char) => char >= 0x2400 && char <= 0x243F, 'Optical Character Recognition': (char) => char >= 0x2440 && char <= 0x245F, 'Enclosed Alphanumerics': (char) => char >= 0x2460 && char <= 0x24FF, // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F, // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F, 'Geometric Shapes': (char) => char >= 0x25A0 && char <= 0x25FF, 'Miscellaneous Symbols': (char) => char >= 0x2600 && char <= 0x26FF, // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF, // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF, // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF, // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF, // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F, // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF, // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF, 'Miscellaneous Symbols and Arrows': (char) => char >= 0x2B00 && char <= 0x2BFF, // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F, // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F, // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF, // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F, // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F, // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF, // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF, // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F, 'CJK Radicals Supplement': (char) => char >= 0x2E80 && char <= 0x2EFF, 'Kangxi Radicals': (char) => char >= 0x2F00 && char <= 0x2FDF, 'Ideographic Description Characters': (char) => char >= 0x2FF0 && char <= 0x2FFF, 'CJK Symbols and Punctuation': (char) => char >= 0x3000 && char <= 0x303F, 'Hiragana': (char) => char >= 0x3040 && char <= 0x309F, 'Katakana': (char) => char >= 0x30A0 && char <= 0x30FF, 'Bopomofo': (char) => char >= 0x3100 && char <= 0x312F, 'Hangul Compatibility Jamo': (char) => char >= 0x3130 && char <= 0x318F, 'Kanbun': (char) => char >= 0x3190 && char <= 0x319F, 'Bopomofo Extended': (char) => char >= 0x31A0 && char <= 0x31BF, 'CJK Strokes': (char) => char >= 0x31C0 && char <= 0x31EF, 'Katakana Phonetic Extensions': (char) => char >= 0x31F0 && char <= 0x31FF, 'Enclosed CJK Letters and Months': (char) => char >= 0x3200 && char <= 0x32FF, 'CJK Compatibility': (char) => char >= 0x3300 && char <= 0x33FF, 'CJK Unified Ideographs Extension A': (char) => char >= 0x3400 && char <= 0x4DBF, 'Yijing Hexagram Symbols': (char) => char >= 0x4DC0 && char <= 0x4DFF, 'CJK Unified Ideographs': (char) => char >= 0x4E00 && char <= 0x9FFF, 'Yi Syllables': (char) => char >= 0xA000 && char <= 0xA48F, 'Yi Radicals': (char) => char >= 0xA490 && char <= 0xA4CF, // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF, // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F, // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F, // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF, // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F, // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF, // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F, // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F, // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F, // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF, // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF, // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F, // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F, 'Hangul Jamo Extended-A': (char) => char >= 0xA960 && char <= 0xA97F, // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF, // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF, // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F, // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F, // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF, // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF, // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F, // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F, // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF, // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF, 'Hangul Syllables': (char) => char >= 0xAC00 && char <= 0xD7AF, 'Hangul Jamo Extended-B': (char) => char >= 0xD7B0 && char <= 0xD7FF, // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F, // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF, // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF, 'Private Use Area': (char) => char >= 0xE000 && char <= 0xF8FF, 'CJK Compatibility Ideographs': (char) => char >= 0xF900 && char <= 0xFAFF, // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F, 'Arabic Presentation Forms-A': (char) => char >= 0xFB50 && char <= 0xFDFF, // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F, 'Vertical Forms': (char) => char >= 0xFE10 && char <= 0xFE1F, // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F, 'CJK Compatibility Forms': (char) => char >= 0xFE30 && char <= 0xFE4F, 'Small Form Variants': (char) => char >= 0xFE50 && char <= 0xFE6F, 'Arabic Presentation Forms-B': (char) => char >= 0xFE70 && char <= 0xFEFF, 'Halfwidth and Fullwidth Forms': (char) => char >= 0xFF00 && char <= 0xFFEF // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF, // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F, // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF, // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F, // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F, // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF, // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF, // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F, // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF, // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF, // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F, // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F, // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F, // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F, // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF, // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F, // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F, // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF, // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF, // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F, // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F, // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F, // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F, // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F, // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F, // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF, // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF, // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F, // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F, // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F, // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF, // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F, // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F, // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F, // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF, // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F, // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F, // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F, // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF, // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F, // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF, // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F, // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F, // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F, // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F, // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF, // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F, // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF, // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF, // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F, // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F, // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF, // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF, // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F, // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF, // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF, // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F, // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F, // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF, // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF, // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F, // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F, // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF, // 'Ahom': (char) => char >= 0x11700 && char <= 0x1173F, // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F, // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF, // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF, // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F, // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF, // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF, // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F, // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF, // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F, // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF, // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF, // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF, // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF, // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F, // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F, // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F, // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1343F, // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F, // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F, // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F, // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF, // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F, // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F, // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F, // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF, // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF, // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF, // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF, // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F, // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F, // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF, // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F, // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF, // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF, // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF, // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F, // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF, // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F, // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F, // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF, // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF, // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F, // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F, // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF, // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF, // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F, // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF, // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F, // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF, // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F, // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F, // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF, // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF, // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF, // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF, // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F, // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F, // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF, // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F, // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF, // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF, // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF, // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F, // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF, // 'CJK Unified Ideographs Extension B': (char) => char >= 0x20000 && char <= 0x2A6DF, // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F, // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F, // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF, // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF, // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F, // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F, // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF, // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF, // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF, }; export default unicodeBlockLookup;
the_stack
export const dictionary = [ ['break', 'харэ'], ['case', 'лещ'], ['case', 'аеслинайду'], ['catch', 'гоп'], ['catch', 'аченетак'], ['catch', 'аченитак'], ['catch', 'ачёнетак'], ['continue', 'двигай'], ['debugger', 'логопед'], ['delete', 'ёбнуть'], ['delete', 'ебнуть'], ['do', 'крч'], ['else', 'иливжопураз'], ['finally', 'тюряжка'], ['for', 'го'], ['function', 'йопта'], ['function*', 'пиздюли'], ['if', 'вилкойвглаз'], ['in', 'чоунастут'], ['default', 'пахану'], ['default', 'апохуй'], ['default', 'наотыбись'], ['instanceof', 'шкура'], ['new', 'гыйбать'], ['new', 'захуярить'], ['return', 'отвечаю'], ['yield', 'поебалу'], ['yield*', 'поебалуна'], ['switch', 'естьчо'], ['this', 'тырыпыры'], ['throw', 'пнх'], ['try', 'хапнуть'], ['try', 'побратски'], ['try', 'пабрацки'], ['try', 'пабратски'], ['typeof', 'чезажижан'], ['var', 'гыы'], ['let', 'участковый'], ['void', 'куку'], ['while', 'потрещим'], ['with', 'хзйопт'], ['Abstract', 'Говнойбать'], ['abstract', 'говнойбать'], ['Boolean', 'Пацан'], ['boolean', 'пацан'], ['Byte', 'Семка'], ['byte', 'семка'], ['Char', 'Эээ'], ['char', 'эээ'], ['class', 'клёво'], ['class', 'клево'], ['Const', 'ЯсенХуй'], ['const', 'ясенХуй'], ['Double', 'Двойные'], ['double', 'двойные'], ['Enum', 'Еээ'], ['enum', 'еээ'], ['extends', 'батя'], ['final', 'бачок'], ['Float', 'Плавник'], ['float', 'плавник'], ['goto', 'пиздуй'], ['implements', 'силикон'], ['import', 'спиздить'], ['Int', 'Хуйня'], ['int', 'хуйня'], ['interface', 'хуёво'], ['interface', 'хуево'], ['Long', 'Колонна'], ['long', 'колонна'], ['native', 'чорт'], ['package', 'клеёнка'], ['package', 'клеенка'], ['private', 'мой'], ['protected', 'подкрыша'], ['public', 'ебанное'], ['Short', 'Пипин'], ['short', 'пипин'], ['static', 'попонятия'], ['super', 'яга'], ['synchronized', 'вписон'], ['throws', 'плюнуть'], ['transient', 'ахз'], ['volatile', 'вписос'], ['null', 'нуллио'], ['null', 'порожняк'], ['NaN', 'нихуя'], ['undefined', 'неибу'], ['true', 'трулио'], ['true', 'чётко'], ['true', 'четко'], ['true', 'чотко'], ['false', 'нетрулио'], ['false', 'пиздишь'], ['false', 'нечётко'], ['false', 'нечетко'], ['false', 'нечотко'], ['eval', 'ебал'], // ['\'use strict\'', '\'далиСтрогача\''], Баг: global.yopta("'use strict'", 'js') возвращает 'use strict' // Операторы сравнения и логические операторы, синтаксические ['\\{', 'жЫ'], ['\\}', 'есть'], ['\\=\\=', 'эквалио'], ['\\=\\=', 'однахуйня'], ['\\=\\=', 'ровно'], ['\\=\\=', 'типа'], ['\\=\\=', 'блясука'], ['\\=\\=\\=', 'блябуду'], ['\\=\\=\\=', 'чёткоровно'], ['\\=\\=\\=', 'четкоровно'], ['\\=\\=\\=', 'чоткоровно'], ['\\=\\=\\=', 'конкретно'], ['\\>\\=', 'поцик'], ['\\<\\=', 'поц'], ['\\&\\&', 'ичо'], ['\\|\\|', 'иличо'], ['\\>', 'пизже'], ['\\<', 'хуёвей'], ['\\<', 'хуевей'], ['\\=', 'сука'], ['\\=', 'внатуре'], ['\\;', ' нах'], ['\\;', ' нахуй'], ['\\;', ' бля'], ['\\!', 'чобля'], ['\\+\\+', 'плюсуюНа'], ['\\-\\-', 'слилсяНа'], // Document methods ['document', 'ксива'], ['captureEvents', 'зафотатьШняги'], ['createAttribute', 'намутитьЯжку'], ['createDocumentFragment', 'намутитьКусокМалявы'], ['createEvent', 'намутитьШнягу'], ['createNodeIterator', 'намутитьГовнодыратор'], ['createRange', 'намутитьОпапа'], ['createTextNode', 'намутитьМалявуГовнодскую'], ['createTouch', 'намутитьЛеща'], ['createElement', 'намутитьЛошка'], ['createTreeWalker', 'намутитьБуратино'], ['elementFromPoint', 'терпилаИзПараши'], ['elementsFromPoint', 'терпилыИзПараши'], ['enableStyleSheetsForSet', 'намутитьСтруйкуДляХабара'], ['getAnimations', 'вычислитьДвижуху'], ['getElementsByClassName', 'вычислитьТерпилПоКлассу'], ['getElementsByTagName', 'вычислитьТерпилПоТегу'], ['importNode', 'влабазУзел'], ['registerElement', 'зашитьДело'], ['releaseCapture', 'зафотатьХуякХуяк'], ['getElementById', 'вычислитьЛохаПоНомеру'], ['querySelector', 'хулиВыёбываешься'], ['querySelector', 'хулиВыебываешься'], ['querySelectorAll', 'хулиТутВсеВыёбываются'], ['querySelectorAll', 'хулиТутВсеВыебываются'], ['createExpression', 'намутитьБазар'], ['evaluate', 'заценить'], ['clear', 'урыть'], ['close', 'завали'], ['execCommand', 'идиРаботайБля'], ['getElementsByName', 'вычислитьТерпилПоИмени'], ['getSelection', 'сестьНаДваСтула'], ['hasFocus', 'имеетЧёткость'], ['hasFocus', 'имеетЧеткость'], ['hasFocus', 'имеетЧоткость'], ['open', 'отрыть'], ['queryCommandEnabled', 'хулиЧикаДоступная'], ['queryCommandState', 'хулиЧикаОтдыхает'], ['queryCommandSupported', 'хулиЧикаБезАйфона'], ['queryCommandIndeterm', 'хулиЧикаОйВсё'], ['queryCommandIndeterm', 'хулиЧикаОйВсе'], ['queryCommandValue', 'хулиЧикаВалио'], ['write', 'малява'], ['writeln', 'малявагоп'], // Document Properties ['characterSet', 'слышТыЧоЁба'], ['characterSet', 'слышТыЧоЕба'], ['charset', 'слышЁба'], ['charset', 'слышЕба'], ['contentType', 'ухтыжёптыжТипчик'], ['contentType', 'ухтыжептыжТипчик'], ['doctype', 'типКсивы'], ['documentElement', 'ксиваТерпилы'], ['documentURI', 'ксиваНаХате'], ['domConfig', 'чёткоДерзко'], ['domConfig', 'четкоДерзко'], ['domConfig', 'чоткоДерзко'], ['hidden', 'кроить'], ['inputEncoding', 'эйтыэтоПиздиш'], ['pointerLockElement', 'тырколкуНаАнусТерпилы'], ['scrollingElement', 'намазиТерпила'], ['timeline', 'всяЖиза'], ['visibilityState', 'мутныйСюжет'], ['children', 'пездюки'], ['firstElementChild', 'первыйПездюкШняги'], ['lastElementChild', 'последнийПездюкШняги'], ['childElementCount', 'моиШняжныеПездюки'], ['activeElement', 'активнаяШняга'], ['alinkColor', 'петухЗоныКрасиво'], ['anchors', 'якоряЁпт'], ['anchors', 'якоряЕпт'], ['bgColor', 'охуеннаяЖопа'], ['body', 'висяк'], ['cookie', 'семки'], ['defaultView', 'моргалаВыколю'], ['designMode', 'хуйРисуйМод'], ['dir', 'буратино'], ['domain', 'домойБлядь'], ['embeds', 'мразоты'], ['forms', 'еблища'], ['head', 'залупка'], ['height', 'длинный'], ['images', 'мазни'], ['lastModified', 'когдаПетухомСтал'], ['linkColor', 'зонаКрасиво'], ['links', 'зоны'], ['location', 'райончик'], ['plugins', 'выебоны'], ['readyState', 'газуемБля'], ['referrer', 'корешСтарый'], ['scripts', 'гыебаты'], ['title', 'вася'], ['URL', 'хата'], ['vlinkColor', 'когдаОткинулсяПослеЗоны'], ['width', 'жирный'], ['value', 'валио'], // Document event handlers ['onafterscriptexecute', 'послеВыполненияЙопты'], ['onbeforescriptexecute', 'доВыполненияЙопты'], ['oncopy', 'какВсунул'], ['oncut', 'какВысунул'], ['onpaste', 'какВставил'], ['onselectionchange', 'покаДваСтулаМахнуть'], ['onfullscreenchange', 'покаЕбальникПоказал'], ['onwheel', 'какНаХуюВертел'], // Global event handlers ['onabort', 'когдаУронилМыло'], ['onblur', 'опаНичотка'], ['onerror', 'наПапандос'], ['onfocus', 'опаЧотка'], ['oncancel', 'покаТруханул'], ['onchange', 'опаЧозанахуй'], ['onclick', 'какПырну'], ['onclose', 'ебалоОфф'], ['oncontextmenu', 'какПоЛбуЁбну'], ['oncontextmenu', 'какПоЛбуЕбну'], ['ondblclick', 'какПырнуДваждыНахуй'], ['ondrag', 'опаОчкоДёрнул'], ['ondrag', 'опаОчкоДернул'], ['ondragend', 'покаХарэОчкоДёргать'], ['ondragend', 'покаХарэОчкоДергать'], ['ondragenter', 'покаДёргалкаНарисовалась'], ['ondragenter', 'покаДергалкаНарисовалась'], ['ondragexit', 'анусСебеДёрниПёс'], ['ondragexit', 'анусСебеДерниПес'], ['ondragleave', 'покаДергунСлинял'], ['ondragover', 'покаДёрнулПодошла'], ['ondragover', 'покаДернулПодошла'], ['ondragstart', 'покаДёрнулКмон'], ['ondragstart', 'покаДернулКмон'], ['ondrop', 'опаМабилкаЁбнулась'], ['ondrop', 'опаМабилкаЕбнулась'], ['oninput', 'покаЭйтыэтоПишибля'], ['oninvalid', 'гыйбатьИнвалидНахуй'], ['onkeydown', 'гыйбатьЛещДаун'], ['onkeypress', 'гыйбатьВмялЛеща'], ['onkeyup', 'гыйбатьЛещАут'], ['onloadstart', 'покаНесуСемки'], ['onmousedown', 'всунулНаРайоне'], ['onmouseenter', 'вошёлНаРайон'], ['onmouseenter', 'вошелНаРайон'], ['onmouseleave', 'съебалсяИзРайона'], ['onmousemove', 'хожуПоРайону'], ['onmouseout', 'покаТырколкаСъебала'], ['onmouseover', 'покаТырколкаПодошла'], ['onmouseup', 'вынулНаРайоне'], ['onmousewheel', 'вертелНаРайоне'], ['onpause', 'покаСтопэ'], ['onplay', 'покаЖиви'], ['onplaying', 'покаЖивой'], ['onpointerdown', 'покаТыркнулДауна'], ['onpointermove', 'покаХожуТырколйПоРайону'], ['onpointerup', 'покаТыркнулАута'], ['onpointercancel', 'покаСтрелаТруханула'], ['onpointerover', 'покаСтрелаПодошла'], ['onpointerout', 'покаСтрелаСъебала'], ['onpointerenter', 'покаСрелкаНарисовалась'], ['onpointerleave', 'покаСтрелаСлиняла'], ['onprogress', 'покаМатаетсяСрок'], ['onreset', 'покаПравим'], ['onscroll', 'покаКолесим'], ['onseeked', 'когдаОбоссал'], ['onseeking', 'когдаОбоссался'], ['onselect', 'опаДваСтула'], ['onshow', 'опаТуса'], ['onsort', 'опаСидор'], ['onstalled', 'опаНефартануло'], ['onsubmit', 'опаХуйВГовне'], ['onsuspend', 'опаПодфартило'], ['ontimeupdate', 'опаНуЭтоКогдаЭто'], ['onvolumechange', 'покаТишеБудь'], ['ontouchcancel', 'покаЛещТруханул'], ['ontouchend', 'покаЛещКончил'], ['ontouchmove', 'опаДвигайОтСюдаЛещ'], ['ontouchstart', 'опаЩаЛещаПоЩамДам'], ['onwaiting', 'покаМотаюСрок'], // Window properties ['window', 'ебало'], ['closed', 'завалено'], ['console', 'красноглазое'], ['controllers', 'мусора'], ['crypto', 'пиздишбля'], ['devicePixelRatio', 'типАйфона'], ['dialogArguments', 'тыэтаТавоэта'], ['frameElement', 'кадрОпущенный'], ['frames', 'кадры'], ['fullScreen', 'воВсёЕбало'], ['fullScreen', 'воВсеЕбало'], ['history', 'фон'], ['innerHeight', 'внутриДлинный'], ['innerWidth', 'внутриЖирный'], ['length', 'писькомер'], ['location', 'белыйЛебедь'], ['name', 'погоняло'], ['navigator', 'главпетух'], ['opener', 'открывашка'], ['outerHeight', 'вокругДлинные'], ['outerWidth', 'вокругЖирные'], ['pageXOffset', 'статьяПоЭксу'], ['pageYOffset', 'статьяПоУгам'], ['sessionStorage', 'хабрИзОтсидки'], ['parent', 'родаки'], ['returnValue', 'ответитьЗаВалио'], ['performance', 'сестьНахуй'], ['screen', 'всёЕбало'], ['screen', 'всеЕбало'], ['screenX', 'всёЕбалоПоЭксу'], ['screenX', 'всеЕбалоПоЭксу'], ['screenY', 'всёЕбалоПоУгам'], ['screenY', 'всеЕбалоПоУгам'], ['scrollbars', 'колеситьПоПивларькам'], ['scrollMaxX', 'колеситьПоГлавЭксу'], ['scrollMaxY', 'колеситьПоГлавУгам'], ['scrollX', 'колеситьПоЭксу'], ['scrollY', 'колеситьПоУгам'], ['self', 'пельмень'], ['sidebar', 'стенкаЙбать'], ['top', 'КрышаЙбать'], // Window methods ['addEventListener', 'добавитьВертухай'], ['alert', 'шухер'], ['blur', 'размытьЕбало'], ['cancelIdleCallback', 'харэПиздеть'], ['clearInterval', 'отсидетьСизо'], ['clearTimeout', 'отсидетьСрок'], ['confirm', 'канает'], ['dispatchEvent', 'послатьНахуйШнягу'], ['dump', 'мусорка'], ['find', 'сигиЕсть'], ['focus', 'хуёкус'], ['focus', 'хуекус'], ['getAttention', 'посвистеть'], ['getComputedStyle', 'нассыМнеВалиоСтруйкой'], ['matchMedia', 'феняНаШару'], ['maximize', 'распидорась'], ['minimize', 'спидорась'], ['moveBy', 'щаТяПодвину'], ['moveTo', 'нахуйЭтоТуда'], ['openDialog', 'побазарить'], ['postMessage', 'намутитьКсиву'], ['print', 'наПечать'], ['prompt', 'поясниЗаБазар'], ['removeEventListener', 'урытьВертухая'], ['resizeBy', 'распидораситьПоХуйне'], ['resizeTo', 'распидораситьОтносительно'], ['scroll', 'колесить'], ['scrollBy', 'колеситьНа'], ['scrollByLines', 'колеситьНаЛинии'], ['scrollByPages', 'колеситьНаМалявах'], ['scrollTo', 'колеситьНахуйНа'], ['setInterval', 'посетитьСизо'], ['setResizable', 'датьПопидорасить'], ['setTimeout', 'получитьСрок'], ['sizeToContent', 'ухтыжёптыжбляПодгони'], ['sizeToContent', 'ухтыжептыжбляПодгони'], ['stop', 'стопээ'], ['Promise', 'СловоПацана'], ['updateCommands', 'новыйАйфонДляЧики'], // Window event handlers ['onbeforeunload', 'покаСемкиКрутятся'], ['ondevicelight', 'покаХуйДлинный'], ['onhashchange', 'покаШнягаИзменяет'], ['oninstall', 'покаХуйСтоитКакКолонна'], ['onload', 'опаСемкиНесу'], ['onoffline', 'покаОффнусь'], ['ononline', 'опаТутачки'], ['onpagehide', 'покаКсиваНаМалине'], ['onpageshow', 'опаКсивуПоказал'], ['onpaint', 'опаНарисовался'], ['onpopstate', 'покаИсторияМаляется'], ['onstorage', 'опаХабар'], ['onunload', 'опаСемкиКрутятся'], // Node properties ['baseURI', 'наХатеТип'], ['baseURIObject', 'мразотыНаХатеКрч'], ['childNodes', 'пездюкГовнод'], ['firstChild', 'первыйПездюк'], ['lastChild', 'последнийПездюк'], ['nextSibling', 'следующийПездюк'], ['nodeName', 'погонялоПездюка'], ['nodeType', 'типичныйПездюк'], ['nodeValue', 'валиоПездюка'], ['ownerDocument', 'главныйАвторитет'], ['parentNode', 'братишка'], ['parentElement', 'братишкаЭлемент'], ['previousSibling', 'старыйПездюк'], ['textContent', 'ухтыжёптыжМалява'], ['textContent', 'ухтыжептыжМалява'], // Node methods ['appendChild', 'заделатьПездюка'], ['cloneNode', 'клонГовнод'], ['compareDocumentPosition', 'сравниСтатусМалявы'], ['contains', 'яТвойОтецЕбуОвец'], ['getRootNode', 'дайБатеГовнод'], ['hasChildNodes', 'батяИмеетПездюков'], ['insertBefore', 'вставитьПездюкаДо'], ['isDefaultNamespace', 'деткаТыПростоКосмос'], ['isEqualNode', 'эквалиоГовнод'], ['normalize', 'нормандэ'], ['removeChild', 'уебатьПездюка'], ['replaceChild', 'сделатьАборт'], // String properties ['prototype', 'проточелик'], // String methods ['fromCharCode', 'хуйняИзЁба'], ['fromCharCode', 'хуйняИзЕба'], ['fromCodePoint', 'хуйняИзЭтоТуданахНутыпоэл'], ['raw', 'полоса'], ['charAt', 'обаЁба'], ['charAt', 'обаЕба'], ['charCodeAt', 'обаЁбаХуйня'], ['charCodeAt', 'обаЕбаХуйня'], ['codePointAt', 'хуйняНутыпоэлОткуда'], ['concat', 'заебеньВсе'], ['includes', 'лучшеНетВлагалищаЧемОчкоТоварища'], ['endsWith', 'отЗалупки'], ['indexOf', 'поТюряге'], ['lastIndexOf', 'последняяОтсидка'], ['localeCompare', 'сравнитьГовор'], ['match', 'футбик'], ['padEnd', 'залупныйПадик'], ['padStart', 'начальныйПадик'], ['repeat', 'непоэлПовтори'], ['replace', 'пивасПодмени'], ['search', 'семкиЕсть'], ['slice', 'поделитьСемки'], ['split', 'поделитьЯгу'], ['startsWith', 'начатьЗалупку'], ['substr', 'спиздитьМеждуБукв'], ['substring', 'спиздитьМеждуСтрок'], ['toLocaleLowerCase', 'поРайонуНеКапсом'], ['toLocaleUpperCase', 'поРайонуКапсом'], ['toLowerCase', 'неКапсом'], ['toString', 'поПацански'], ['toUpperCase', 'капсомБля'], ['trim', 'вырезатьОчко'], ['trimLeft', 'вырезатьОчкоСлева'], ['trimRight', 'вырезатьОчкоСправа'], ['valueOf', 'валиоОф'], // String HTML wrapper methods ['anchor', 'якорьЁпт'], ['anchor', 'якорьЕпт'], ['big', 'большойЁпт'], ['big', 'большойЕпт'], ['bold', 'жирныйЁпт'], ['bold', 'жирныйЕпт'], ['fixed', 'ПМС'], ['fontcolor', 'говномПоСтенеКрасиво'], ['fontsize', 'говномПоСтенеСочно'], ['italics', 'понаехавший'], ['link', 'зона'], ['small', 'малорик'], ['strike', 'въебиОчко'], // Canvas properties ['currentTransform', 'этотЕбальник'], ['direction', 'лесТам'], ['filter', 'фильтруй'], ['font', 'говномПоСтене'], ['fillStyle', 'кончитьСтруйкой'], ['globalAlpha', 'главныйАльфач'], ['imageSmoothingEnabled', 'включитьРазмытиеЕбала'], ['lineCap', 'выбратьКонец'], ['lineDashOffset', 'пятнистыйХуй'], ['lineJoin', 'формаШишкана'], ['lineWidth', 'толщинаХуя'], ['miterLimit', 'скрестимСтруйки'], ['shadowBlur', 'наняРазмытьЕбало'], ['shadowColor', 'наняКрасиво'], ['shadowOffsetX', 'наняХатаПоЭксу'], ['shadowOffsetY', 'наняХатаПоУгам'], ['strokeStyle', 'стильНаколок'], ['textAlign', 'выровнитьБазар'], ['textBaseline', 'поставитьБазар'], // Canvas methods ['addHitRegion', 'создатьПроблемы'], ['getContext', 'снятьСкальп'], ['arc', 'прогиб'], ['arcTo', 'прогибНа'], ['bezierCurveTo', 'кривоНахуй'], ['clearHitRegions', 'убитьПроблему'], ['clearRect', 'урытьШкаф'], ['clip', 'запретка'], ['closePath', 'тупикНахуй'], ['createImageData', 'намутитьМазнюЙопта'], ['createLinearGradient', 'намутитьЧоткуюМазнюПодливой'], ['createPattern', 'намутитьТипчика'], ['createRadialGradient', 'намутитьПоКругуМазнюПодливой'], ['ellipse', 'очко'], ['fill', 'обкончать'], ['fillRect', 'обкончатьДоску'], ['fillText', 'обкончатьБуквы'], ['getImageData', 'чоТутНамалёвано'], ['getImageData', 'чоТутНамалевано'], ['getLineDash', 'сококПятен'], ['isPointInPath', 'естьЛиКуполаНаГруди'], ['isPointInStroke', 'естьЛиКуполаНаНаколках'], ['lineTo', 'прямоНахуй'], ['measureText', 'вместитьБазар'], ['moveTo', 'щемитьНа'], ['putImageData', 'намалюйЧоТут'], ['quadraticCurveTo', 'криваяЗавелаНахуй'], ['rect', 'доска'], ['removeHitRegion', 'избавитьсяОтПроблемы'], ['resetTransform', 'поправитьЕбальник'], ['restore', 'выздоравливай'], ['rotate', 'вертетьНаХую'], ['save', 'схоронить'], ['scale', 'чётчеНа'], ['scale', 'четчеНа'], ['scale', 'чотчеНа'], ['scrollPathIntoView', 'колеситьПоДорогеНахуй'], ['setLineDash', 'заебенитьПятнистыйХуй'], ['setTransform', 'перекоситьЕбальник'], ['stroke', 'наколка'], ['strokeText', 'текстНаколки'], ['transform', 'перекосить'], ['translate', 'дисюдаПиксел'], // Number properties ['EPSILON', 'ХУЕПСИЛОН'], ['MAX_SAFE_INTEGER', 'ЛУЧШИЙ_ГАНДОН'], ['MAX_VALUE', 'ОХУЕННОЕ_ВАЛИО'], ['MIN_SAFE_INTEGER', 'ХУЁВЫЙ_ГАНДОН'], ['MIN_SAFE_INTEGER', 'ХУЕВЫЙ_ГАНДОН'], ['MIN_VALUE', 'ХУЁВОЕ_ВАЛИО'], ['MIN_VALUE', 'ХУЕВОЕ_ВАЛИО'], ['NEGATIVE_INFINITY', 'НИХУЯ_ДОХУЯ'], ['POSITIVE_INFINITY', 'ОХУЕТЬ_ДОХУЯ'], // Number methods ['isFinite', 'оноКонченое'], ['isInteger', 'этоХуйня'], ['isNaN', 'этоНихуя'], ['isSafeInteger', 'этоОхуеннаяХуйня'], ['parseFloat', 'шнырятьПоПлавникам'], ['parseInt', 'шнырятьПоКарманам'], ['toExponential', 'наХуекспоненту'], ['toFixed', 'наПМС'], ['toLocaleString', 'кПацанамНаРайоне'], ['toPrecision', 'кЧёткости'], ['toPrecision', 'кЧеткости'], ['toPrecision', 'кЧоткости'], // Console methods ['assert', 'найтиСтукача'], ['count', 'которыйСрок'], ['dirxml', 'йбатьБуратиноНахуй'], ['error', 'папандос'], ['group', 'банда'], ['groupCollapsed', 'свернутьБанду'], ['groupEnd', 'съебатьсяИзБанды'], ['info', 'инфо'], ['log', 'чмо'], ['profile', 'личка'], ['profileEnd', 'вЛичкуПрописали'], ['table', 'таблом'], ['time', 'срок'], ['timeEnd', 'конецСрока'], ['timeStamp', 'началоСрока'], ['trace', 'складЧмошников'], ['warn', 'тыЭтоНуЭто'], // XMLHttpRequest properties ['XMLHttpRequest', 'запросПоЩам'], ['onreadystatechange', 'опаГотовЙоптЧозанахуй'], ['readyState', 'готовностьЙопт'], ['timeout', 'длительностьСрока'], ['upload', 'заебенить'], ['withCredentials', 'зашкварить'], // XMLHttpRequest methods ['abort', 'уронилМыло'], ['getResponseHeader', 'дайКепарикПолосатого'], ['send', 'всёПиздуй'], ['send', 'всеПиздуй'], // XMLHttpRequest Inheritance ['XMLHttpRequestEventTarget', 'запросСоШнягойПоЩам'], ['EventTarget', 'очкоНаПрицеле'], // XMLHttpRequest events ['loadstart', 'началТаскатьСемки'], ['progress', 'сколькоСемокДонёс'], ['progress', 'сколькоСемокДонес'], ['load', 'нестиСемки'], ['loadend', 'семкиДонёс'], ['loadend', 'семкиДонес'], ['readystatechange', 'готовЙоптЧозанахуй'], // Arrays properties ['Array', 'Помойка'], // Arrays methods ['from', 'спиздитьИз'], ['isArray', 'этоПомойка'], ['of', 'сашаГрей'], ['copyWithin', 'вынестиГовно'], ['entries', 'вычислитьЛохов'], ['every', 'пошерстим'], ['findIndex', 'найдиБомжа'], ['forEach', 'пероПодРебро'], ['join', 'вписаться'], ['keys', 'отмычки'], ['map', 'засратьВсё'], ['map', 'засратьВсе'], ['pop', 'попка'], ['push', 'пупок'], ['reduce', 'редиска'], ['reduceRight', 'редискаПравая'], ['reverse', 'шухильмеМухильме'], ['shift', 'первыйБачок'], ['splice', 'въебатьГовна'], ['sort', 'сидор'], ['some', 'нарываешься'], ['unshift', 'верниБачок'], ['values', 'валиоси'], // Math properties ['Math', 'Гопец'], ['Math', 'Ботан'], ['Math', 'Батан'], ['Math', 'Очканавт'], ['Math', 'Очконавт'], ['E', 'ГОПСПАНЕНТА'], ['LN10', 'ГОПОРИФМ10'], ['LN2', 'ГОПОРИФМ2'], ['LOG10E', 'СЛОЖНЫЙ_ГОПОРИФМ10'], ['LOG2E', 'СЛОЖНЫЙ_ГОПОРИФМ2'], ['PI', 'ПИЗДЕЦ'], ['SQRT1_2', 'сквиртНаПолшишечки'], ['SQRT2', 'двойнойСквирт'], // Math methods ['abs', 'абсолютли'], ['acos', 'агопосинус'], ['acosh', 'агопосинусКупчинский'], ['asin', 'агопинус'], ['asinh', 'агопинусКупчинский'], ['atan', 'агопангенс'], ['atan2', 'агопангенсПо2'], ['atanh', 'агопангенсКупчинский'], ['cbrt', 'кубоСквирт'], ['ceil', 'чирикГони'], ['clz32', 'поводырь32петухов'], ['cos', 'гопосинос'], ['cosh', 'гопосиносКолпинский'], ['exp', 'гопспанента'], ['expm1', 'топГопспонента'], ['floor', 'бабкиГони'], ['fround', 'мелочьТожеГони'], ['hypot', 'вКореньЗыришь'], ['imul', 'петухПетухаВидитИздалека'], ['log10', 'гопорифмПо10'], ['log1p', 'чистыйГопорифмПо1'], ['log2', 'гопорифмПо2'], ['max', 'хуйло'], ['min', 'хуйчик'], ['pow', 'гопень'], ['random', 'шара'], ['round', 'подрезать'], ['sign', 'сиськи'], ['sin', 'гопинус'], ['sinh', 'гопинусКолпинский'], ['sqrt', 'сквирт'], ['tan', 'гопангенс'], ['tanh', 'гопангенсКолпинский'], ['trunc', 'верниЧирик'], // RegExp properties ['RegExp', 'фильтруйБазар'], ['input', 'тыЭтоПишибля'], ['flags', 'флагМнеВанус'], ['global', 'глобалкаЙопта'], ['ignoreCase', 'игнорщикЕбаный'], ['multiline', 'стулБезПик'], ['source', 'обоснуй'], ['sticky', 'петухОпущенный'], ['unicode', 'хуйняНахуй'], ['lastIndex', 'доКонцаОтсидки'], // RegExp methods ['exec', 'работайМразь'], ['test', 'ответыБудутЭээ'], // async/await functions, methods and objects ['async', 'ассо'], ['await', 'сидетьНахуй'], ['resolveAfter2Seconds', 'паруСекНеГомосек'], ['AsyncFunction', 'АссоЙопта'], // Promise methods ['all', 'пацанСделал'], ['then', 'атоэто'], ['race', 'пацанСказал'], ['reject', 'пацанЗабыл'], ['resolve', 'щащаНамутитьКактоНадо'], // Object properties ['Object', 'Петух'], ['Object', 'Кент'], ['constructor', 'стрельнутьБычки'], // Object methods ['assign', 'тащиВсёНаХату'], ['assign', 'тащиВсеНаХату'], ['create', 'намутить'], ['defineProperties', 'ващеЧоткиеЧелики'], ['defineProperty', 'вотЭтоЗаебись'], ['freeze', 'датьЛеща'], ['getOwnPropertyDescriptor', 'вычислиЕблоКрысы'], ['getOwnPropertyDescriptors', 'вычислиСходкуКрыс'], ['getOwnPropertyNames', 'вычислиПогонялаКрыс'], ['getOwnPropertySymbols', 'выучиАлфавитМразь'], ['getPrototypeOf', 'чоЗаПроточелик'], ['isExtensible', 'жратьБудешь'], ['isFrozen', 'далЛеща'], ['isSealed', 'теЧоЕбалоРазбить'], ['hasOwnProperty', 'соСвоейТемой'], ['isPrototypeOf', 'чейПроточелик'], ['propertyIsEnumerable', 'лютаяТема'], ['unwatch', 'съебись'], ['watch', 'смотрюСюда'], ['seal', 'сдохниНахуй'], ['setPrototypeOf', 'замутитьПроточелика'], // NodeJS/modules support ['module', 'братва'], ['exports', 'предъявляет'], ['export', 'предъявa'], ['global', 'общак'], ];
the_stack
import * as assert from "assert" import { execSync } from "child_process" import * as fs from "fs" import * as os from "os" import * as path from "path" import * as shell from "shelljs" import * as rimraf from "rimraf" import { getCompletionElement, getTemporaryFolder } from "./../ci/Common" import { getDistPath, getRootPath } from "./DemoCommon" import { remote } from "electron" const BASEDELAY = 18 const RANDOMDELAY = 8 const EmptyConfigPath = path.join(getTemporaryFolder(), "config.js") const getProjectRootPath = () => { const root = getRoot(__dirname) return os.platform() === "win32" ? root : os.homedir() } const ReactProjectName = "oni-react-app" const getRoot = (dir: string): string => { const parent = path.dirname(dir) if (parent === dir) { return parent } else { return getRoot(parent) } } const createReactAppProject = oni => { const oniReactApp = path.join(getProjectRootPath(), ReactProjectName) // rimraf.sync(oniReactApp) // const output = execSync('create-react-app "' + oniReactApp + '"') const oniLogoPath = path.join(getRootPath(), "images", "256x256.png") const oniLogoDestinationPath = path.join(oniReactApp, "src", "oni.png") const oniLogoComponentPath = path.join(oniReactApp, "src", "OniLogo.js") fs.writeFileSync( oniLogoComponentPath, ` import React, { Component } from 'react'; import logo from './oni.png'; export class OniLogo extends Component { render() { return <img src={logo} className="App-logo" alt="logo" />; } } `, "utf8", ) // Delete the 'App.test.js' so it doesn't mess up fuzzy find results rimraf.sync(path.join(oniReactApp, "src", "App.test.js")) shell.cp(oniLogoPath, oniLogoDestinationPath) shell.cp(path.join(oniReactApp, "src", "Old.js"), path.join(oniReactApp, "src", "App.js")) return oniReactApp } export const test = async (oni: any) => { const reactAppPath = createReactAppProject(oni) await oni.automation.waitForEditors() oni.workspace.changeDirectory(reactAppPath) const isMac = process.platform === "darwin" const shortDelay = async () => oni.automation.sleep(BASEDELAY * 25) const longDelay = async () => oni.automation.sleep(BASEDELAY * 50) const simulateTyping = async (keys: string, baseDelay: number = BASEDELAY) => { for (const key of keys) { oni.automation.sendKeysV2(key) await oni.automation.sleep(baseDelay + Math.random() * RANDOMDELAY) } await shortDelay() } const pressEscape = async () => { await shortDelay() oni.automation.sendKeysV2("<esc>") await shortDelay() } const pressTab = async () => { await shortDelay() oni.automation.sendKeysV2("<tab>") await shortDelay() } const pressShiftTab = async () => { await shortDelay() oni.automation.sendKeysV2("<s-tab>") await shortDelay() } const pressEnter = async () => { await shortDelay() oni.automation.sendKeysV2("<cr>") await shortDelay() } const openCommandPalette = async () => { await shortDelay() const keys = isMac ? "<m-s-p>" : "<c-s-p>" oni.automation.sendKeysV2(keys) await shortDelay() } const openFindInFiles = async () => { await shortDelay() const keys = isMac ? "<m-s-f>" : "<c-s-f>" oni.automation.sendKeysV2(keys) await shortDelay() } const openQuickOpen = async () => { await shortDelay() const keys = isMac ? "<m-p>" : "<c-p>" oni.automation.sendKeysV2(keys) await shortDelay() } const splitHorizontal = async (fileName: string) => { await shortDelay() oni.automation.sendKeysV2("<c-w>") oni.automation.sendKeysV2("<c-s>") await shortDelay() await simulateTyping(":tabnew VIM.md") } const waitForCompletion = async () => { return oni.automation.waitFor(() => !!getCompletionElement()) } const showWelcomeAchievement = async () => { oni.achievements.clearAchievements() // Create our own 'mock' achievement, because // the welcome one won't be tracked if it has been completed oni.achievements.registerAchievement({ uniqueId: "oni.achievement.automation", name: "Welcome to Oni!", description: "Launch Oni for the first time", goals: [ { name: null, goalId: "oni.automation.goal", count: 1, }, ], }) oni.achievements.notifyGoal("oni.automation.goal") await longDelay() await longDelay() } const intro = async () => { await simulateTyping(":tabnew Hello.md") await pressEnter() await simulateTyping( "iOni is a new kind of editor: combining the best of Vim, Atom, and VSCode.", ) await pressEnter() await simulateTyping( "Built with web tech, featuring a high performance canvas renderer, with (neo)vim handling the heavy lifting.", ) await pressEnter() await simulateTyping("Available for Windows, OSX, and Linux.") await pressEscape() } const navigateToSneakWithTag = async (tag: string) => { oni.automation.sendKeysV2("<c-g>") await shortDelay() const targetSneak = oni.sneak.getSneakMatchingTag(tag) const triggerKeys = targetSneak.triggerKeys as string await simulateTyping(triggerKeys) await shortDelay() } const showKeyboardNavigation = async () => { await splitHorizontal("VIM.md") await pressEnter() await simulateTyping("i") await simulateTyping("Use your Vim muscle memory to be productive without a mouse...") await pressEscape() oni.automation.sendKeysV2("<c-w>") oni.automation.sendKeysV2("<c-h>") await shortDelay() oni.automation.sendKeysV2("G") await longDelay() oni.automation.sendKeysV2("gg") await longDelay() oni.automation.sendKeysV2("<c-w>") oni.automation.sendKeysV2("<c-h>") await shortDelay() oni.automation.sendKeysV2("<c-w>") oni.automation.sendKeysV2("<c-l>") await shortDelay() oni.automation.sendKeysV2("<c-w>") oni.automation.sendKeysV2("<c-l>") await shortDelay() oni.automation.sendKeysV2("<c-w>") oni.automation.sendKeysV2("<c-j>") await shortDelay() await simulateTyping("o") await simulateTyping("..but enjoy the conveniences of a modern UI editor.") await pressEscape() await shortDelay() await navigateToSneakWithTag("oni.sidebar.search") await navigateToSneakWithTag("oni.sidebar.learning") await navigateToSneakWithTag("oni.sidebar.explorer") oni.automation.sendKeysV2("<esc>") await simulateTyping(":qa!") oni.automation.sendKeysV2("<cr>") await shortDelay() oni.automation.sendKeysV2("<esc>") } const showDevelopment = async () => { await pressEscape() await openCommandPalette() await simulateTyping("brovsp") await pressEnter() await pressEscape() await openCommandPalette() await simulateTyping("termhzsp") await pressEnter() await longDelay() await simulateTyping("A") await simulateTyping("npm run start") await pressEnter() await pressEscape() oni.automation.sendKeysV2("<c-w>") oni.automation.sendKeysV2("<c-h>") await shortDelay() await openQuickOpen() await simulateTyping("Appjs") await pressEnter() await navigateToSneakWithTag("browser.address") await shortDelay() await simulateTyping("http://localhost:3000") await pressEnter() // The popped up browser can steal focus, causing our bindings to fail.. require("electron") .remote.getCurrentWindow() .focus() await simulateTyping("10j") await shortDelay() await simulateTyping("cit") await shortDelay() await simulateTyping("Welcome to Oni") await pressEscape() await simulateTyping(":w") await pressEnter() await shortDelay() await simulateTyping("7k") await simulateTyping("O") await simulateTyping("impsnip") await waitForCompletion() await pressEnter() await shortDelay() await simulateTyping("./Oni") await waitForCompletion() await pressEnter() await pressTab() await simulateTyping("Oni") await waitForCompletion() await pressEnter() await pressTab() await simulateTyping("7j") await simulateTyping("b") await simulateTyping("C") await simulateTyping("OniLogo />") await pressEscape() await simulateTyping(":w") await pressEnter() await longDelay() await longDelay() oni.automation.sendKeysV2("<c-w>") oni.automation.sendKeysV2("<c-l>") await shortDelay() oni.automation.sendKeysV2("<c-w>") oni.automation.sendKeysV2("<c-j>") await shortDelay() await simulateTyping(":q") await pressEnter() await shortDelay() await simulateTyping(":q") await pressEnter() await shortDelay() } const showConfig = async () => { await pressEscape() await openCommandPalette() await simulateTyping("configuser") await longDelay() await pressEnter() await longDelay() oni.automation.sendKeysV2("/") await shortDelay() await simulateTyping("fontSize") await shortDelay() oni.automation.sendKeysV2("<cr>") await shortDelay() await simulateTyping("gcc") await shortDelay await simulateTyping("fp") await longDelay() await simulateTyping("ciw") await longDelay() await simulateTyping("16px") await pressEscape() await simulateTyping(":w") await pressEscape() // HACK - Configuration doesn't use the same file, so we need to set this directly here oni.configuration.setValues({ "editor.fontSize": "16px" }) await longDelay() await simulateTyping("b") await longDelay() await simulateTyping("ciw") await longDelay() await simulateTyping("14px") await pressEscape() await simulateTyping(":w") await pressEnter() oni.configuration.setValues({ "editor.fontSize": "14px" }) await longDelay() await pressEscape() await simulateTyping("gg") oni.automation.sendKeysV2("/") await shortDelay() await simulateTyping("activate") await pressEnter() await simulateTyping("n") await simulateTyping("o") await pressEnter() await simulateTyping("// We can also use Oni's extensibility API here!") await pressEnter() await simulateTyping("Let's add a status bar item") await pressEscape() await simulateTyping("o") oni.automation.sendKeysV2("<c-w>") await pressEnter() await simulateTyping("const statusBarItem = oni.s") await shortDelay() await simulateTyping("tatusBar.c") await shortDelay() await simulateTyping("reateItem(1)") await pressEnter() await simulateTyping("statusBarItem.s") await shortDelay() await simulateTyping("etContents(") await shortDelay() oni.automation.sendKeys("<lt>") await simulateTyping("div>Hello World") oni.automation.sendKeys("<lt>") await simulateTyping("/div>)") await pressEnter() await simulateTyping("statusBarItem.") await shortDelay() await simulateTyping("show()") await pressEnter() await pressEscape() await simulateTyping(":w") await pressEnter() // const item = oni.statusBar.createItem(1) // item.setContents("Hello World") // item.show() await longDelay() await simulateTyping(":q") await pressEnter() await simulateTyping(":q") await pressEnter() } const showComingSoon = async () => { await shortDelay() await simulateTyping(":tabnew SOON.md") await shortDelay() await pressEnter() await shortDelay() await simulateTyping("i") await simulateTyping("This is just the beginning! Lots more to come:") await pressEnter() await simulateTyping("* Live Preview") await pressEnter() await simulateTyping("* Plugin Management") await pressEnter() await simulateTyping("* More tutorials ") await pressEnter() await simulateTyping("* Debuggers") await pressEnter() await simulateTyping("* Version Control Integration") await longDelay() await pressEnter() await pressEnter() await simulateTyping("Thanks for watching! Download Oni today.") await pressEscape() } const showLanguageServices = async () => { await simulateTyping(":tabnew test.js") oni.automation.sendKeysV2("<cr>") await simulateTyping("i") await simulateTyping("// Oni integrates with language servers, and includes several...") oni.automation.sendKeysV2("<cr>") await simulateTyping("...but you can hook up your own, too!") await shortDelay() oni.automation.sendKeysV2("<cr>") oni.automation.sendKeysV2("<c-w>") await shortDelay() await simulateTyping("const myArray = [1, 2, 3]") await pressEnter() await pressEnter() await pressEscape() await simulateTyping("O") await simulateTyping("const newArray = my") await waitForCompletion() await shortDelay() await simulateTyping("Array.") await simulateTyping("m") await longDelay() await simulateTyping("ap(") await longDelay() await simulateTyping("(val) => val + 1") await pressEscape() await simulateTyping("o") await pressEnter() await simulateTyping("// Oni also has snippet support:") await pressEnter() oni.automation.sendKeysV2("<c-w>") await pressEnter() await simulateTyping("forsnip") await pressEnter() await pressTab() await pressShiftTab() await simulateTyping("idx") await pressTab() await simulateTyping("myArray") await pressTab() await pressTab() await pressEscape() } const showTutorials = async () => { await oni.editors.activeEditor.neovim.command(":tabnew TUTORIAL") await simulateTyping("i") await simulateTyping( "If you're new to modal editing, Oni comes with interactive tutorials to get you up to speed!", ) await pressEscape() await navigateToSneakWithTag("oni.sidebar.learning") const firstTutorialId = oni.tutorials.getNextTutorialId() await oni.tutorials.startTutorial(firstTutorialId) await shortDelay() await pressEscape() await simulateTyping("i") await shortDelay() await simulateTyping("hello") await shortDelay() await pressEscape() await shortDelay() await simulateTyping("o") await shortDelay() await simulateTyping("world") await shortDelay() await pressEscape() await longDelay() await oni.editors.activeEditor.neovim.command(":q!") } // Prime the typescript language service prior to recording await simulateTyping(":tabnew") await pressEnter() await openQuickOpen() await simulateTyping("App.js") await pressEnter() await simulateTyping("owindow.") await waitForCompletion() await longDelay() await pressEscape() await simulateTyping(":q!") await pressEnter() oni.configuration.setValues({ "ui.fontSize": "14px", "editor.fontSize": "14px", }) // Set window size remote.getCurrentWindow().setSize(1920, 1080) oni.recorder.startRecording() await showWelcomeAchievement() oni.tutorials.clearProgress() oni.commands.executeCommand("keyDisplayer.show") oni.configuration.setValues({ "keyDisplayer.showInInsertMode": false, "editor.split.mode": "oni", "browser.defaultUrl": "https://github.com/onivim/oni", }) await intro() await showKeyboardNavigation() await showDevelopment() // --- await showLanguageServices() // --- // oni.automation.sendKeysV2("<c-w>") // oni.automation.sendKeysV2("<c-k>") // await simulateTyping("o") // await simulateTyping("...or the embedded file finder.") // await shortDelay() // await pressEscape() // await shortDelay() // await openQuickOpen() // await simulateTyping("NeovimEditor") // await shortDelay() // oni.automation.sendKeysV2("<cr>") // await longDelay() // oni.automation.sendKeysV2("<c-o>") // await shortDelay() // await simulateTyping("G") // await simulateTyping("o") // await simulateTyping("...use the built in command palette to discover functionality.") // await pressEscape() await showTutorials() await showConfig() await showComingSoon() await simulateTyping(":q") await longDelay() oni.configuration.setValues({ "recorder.outputPath": getDistPath() }) oni.recorder.stopRecording(`demo-${process.platform}.webm`) await pressEscape() } export const settings = { configPath: EmptyConfigPath, }
the_stack
import { errorHandler, getVoidLogger, PluginEndpointDiscovery, } from '@backstage/backend-common'; import { CatalogClient } from '@backstage/catalog-client'; import { ConfigReader } from '@backstage/config'; import { NotModifiedError } from '@backstage/errors'; import { GeneratorBuilder, PreparerBuilder, PublisherBase, } from '@backstage/techdocs-common'; import express, { Response } from 'express'; import request from 'supertest'; import { DocsSynchronizer, DocsSynchronizerSyncOpts } from './DocsSynchronizer'; import { createEventStream, createHttpResponse, createRouter } from './router'; jest.mock('@backstage/catalog-client'); jest.mock('@backstage/config'); jest.mock('./DocsSynchronizer'); const MockedConfigReader = ConfigReader as jest.MockedClass< typeof ConfigReader >; const MockCatalogClient = CatalogClient as jest.MockedClass< typeof CatalogClient >; const MockDocsSynchronizer = DocsSynchronizer as jest.MockedClass< typeof DocsSynchronizer >; describe('createRouter', () => { const entity = { apiVersion: 'backstage.io/v1alpha1', kind: 'Component', metadata: { uid: '0', name: 'test', }, }; const entityWithoutMetadata = { ...entity, metadata: { ...entity.metadata, uid: undefined, }, }; const preparers: jest.Mocked<PreparerBuilder> = { register: jest.fn(), get: jest.fn(), }; const generators: jest.Mocked<GeneratorBuilder> = { register: jest.fn(), get: jest.fn(), }; const publisher: jest.Mocked<PublisherBase> = { docsRouter: jest.fn(), fetchTechDocsMetadata: jest.fn(), getReadiness: jest.fn(), hasDocsBeenGenerated: jest.fn(), publish: jest.fn(), }; const discovery: jest.Mocked<PluginEndpointDiscovery> = { getBaseUrl: jest.fn(), getExternalBaseUrl: jest.fn(), }; let app: express.Express; beforeEach(() => { jest.resetAllMocks(); }); beforeEach(async () => { publisher.docsRouter.mockReturnValue(() => {}); discovery.getBaseUrl.mockImplementation(async type => { return `http://backstage.local/api/${type}`; }); const outOfTheBoxRouter = await createRouter({ preparers, generators, publisher, config: new ConfigReader({}), logger: getVoidLogger(), discovery, }); const recommendedRouter = await createRouter({ publisher, config: new ConfigReader({}), logger: getVoidLogger(), discovery, }); app = express(); app.use(outOfTheBoxRouter); app.use('/recommended', recommendedRouter); app.use(errorHandler()); }); describe('GET /sync/:namespace/:kind/:name', () => { describe('accept application/json', () => { it('should return not found if entity is not found', async () => { MockCatalogClient.prototype.getEntityByName.mockResolvedValue( undefined, ); const response = await request(app) .get('/sync/default/Component/test') .send(); expect(response.status).toBe(404); }); it('should return not found if entity has no uid', async () => { MockCatalogClient.prototype.getEntityByName.mockResolvedValue( entityWithoutMetadata, ); const response = await request(app) .get('/sync/default/Component/test') .send(); expect(response.status).toBe(404); }); it('should not check for an update without local builder', async () => { MockedConfigReader.prototype.getString.mockReturnValue('external'); MockCatalogClient.prototype.getEntityByName.mockResolvedValue(entity); const response = await request(app) .get('/sync/default/Component/test') .send(); expect(response.status).toBe(304); }); it('should error if missing builder', async () => { MockedConfigReader.prototype.getString.mockReturnValue('local'); MockCatalogClient.prototype.getEntityByName.mockResolvedValue(entity); const response = await request(app) .get('/recommended/sync/default/Component/test') .send(); expect(response.status).toBe(500); expect(response.text).toMatch( /Invalid configuration\. 'techdocs\.builder' was set to 'local' but no 'preparer' was provided to the router initialization/, ); expect(MockDocsSynchronizer.prototype.doSync).toBeCalledTimes(0); }); it('should execute synchronization', async () => { MockedConfigReader.prototype.getString.mockReturnValue('local'); MockCatalogClient.prototype.getEntityByName.mockResolvedValue(entity); MockDocsSynchronizer.prototype.doSync.mockImplementation( async ({ responseHandler }) => responseHandler.finish({ updated: true }), ); await request(app).get('/sync/default/Component/test').send(); expect(MockDocsSynchronizer.prototype.doSync).toBeCalledTimes(1); expect(MockDocsSynchronizer.prototype.doSync).toBeCalledWith({ responseHandler: { log: expect.any(Function), error: expect.any(Function), finish: expect.any(Function), }, entity, generators, preparers, }); }); it('should return on updated', async () => { MockedConfigReader.prototype.getString.mockReturnValue('local'); MockCatalogClient.prototype.getEntityByName.mockResolvedValue(entity); MockDocsSynchronizer.prototype.doSync.mockImplementation( async ({ responseHandler }) => { const { log, finish } = responseHandler; log('Some log'); finish({ updated: true }); }, ); const response = await request(app) .get('/sync/default/Component/test') .send(); expect(response.status).toBe(201); expect(response.get('content-type')).toMatch(/application\/json/); expect(response.text).toEqual( '{"message":"Docs updated or did not need updating"}', ); }); }); describe('accept text/event-stream', () => { it('should return not found if entity is not found', async () => { MockCatalogClient.prototype.getEntityByName.mockResolvedValue( undefined, ); const response = await request(app) .get('/sync/default/Component/test') .set('accept', 'text/event-stream') .send(); expect(response.status).toBe(404); }); it('should return not found if entity has no uid', async () => { MockCatalogClient.prototype.getEntityByName.mockResolvedValue( entityWithoutMetadata, ); const response = await request(app) .get('/sync/default/Component/test') .set('accept', 'text/event-stream') .send(); expect(response.status).toBe(404); }); it('should not check for an update without local builder', async () => { MockedConfigReader.prototype.getString.mockReturnValue('external'); MockCatalogClient.prototype.getEntityByName.mockResolvedValue(entity); const response = await request(app) .get('/sync/default/Component/test') .set('accept', 'text/event-stream') .send(); expect(response.status).toBe(200); expect(response.get('content-type')).toBe('text/event-stream'); expect(response.text).toEqual( `event: finish data: {"updated":false} `, ); }); it('should error if missing builder', async () => { MockedConfigReader.prototype.getString.mockReturnValue('local'); MockCatalogClient.prototype.getEntityByName.mockResolvedValue(entity); const response = await request(app) .get('/recommended/sync/default/Component/test') .set('accept', 'text/event-stream') .send(); expect(response.status).toBe(200); expect(response.get('content-type')).toBe('text/event-stream'); expect(response.text).toEqual( `event: error data: "Invalid configuration. 'techdocs.builder' was set to 'local' but no 'preparer' was provided to the router initialization." `, ); expect(MockDocsSynchronizer.prototype.doSync).toBeCalledTimes(0); }); it('should execute synchronization', async () => { MockedConfigReader.prototype.getString.mockReturnValue('local'); MockCatalogClient.prototype.getEntityByName.mockResolvedValue(entity); MockDocsSynchronizer.prototype.doSync.mockImplementation( async ({ responseHandler }) => responseHandler.finish({ updated: true }), ); await request(app) .get('/sync/default/Component/test') .set('accept', 'text/event-stream') .send(); expect(MockDocsSynchronizer.prototype.doSync).toBeCalledTimes(1); expect(MockDocsSynchronizer.prototype.doSync).toBeCalledWith({ responseHandler: { log: expect.any(Function), error: expect.any(Function), finish: expect.any(Function), }, entity, generators, preparers, }); }); it('should return an event-stream', async () => { MockedConfigReader.prototype.getString.mockReturnValue('local'); MockCatalogClient.prototype.getEntityByName.mockResolvedValue(entity); MockDocsSynchronizer.prototype.doSync.mockImplementation( async ({ responseHandler }) => { const { log, finish } = responseHandler; log('Some log'); log('Another log'); finish({ updated: true }); }, ); const response = await request(app) .get('/sync/default/Component/test') .set('accept', 'text/event-stream') .send(); expect(response.status).toBe(200); expect(response.get('content-type')).toBe('text/event-stream'); expect(response.text).toEqual( `event: log data: "Some log" event: log data: "Another log" event: finish data: {"updated":true} `, ); }); }); }); }); describe('createEventStream', () => { const res: jest.Mocked<Response> = { writeHead: jest.fn(), write: jest.fn(), end: jest.fn(), } as any; let handlers: DocsSynchronizerSyncOpts; beforeEach(() => { handlers = createEventStream(res); }); afterEach(() => { jest.resetAllMocks(); }); it('should return correct event stream', async () => { // called in beforeEach expect(res.writeHead).toBeCalledTimes(1); expect(res.writeHead).toBeCalledWith(200, { 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'Content-Type': 'text/event-stream', }); }); it('should flush after write if defined', async () => { res.flush = jest.fn(); handlers.log('A Message'); expect(res.write).toBeCalledTimes(1); expect(res.write).toBeCalledWith(`event: log data: "A Message" `); expect(res.flush).toBeCalledTimes(1); }); it('should write log', async () => { handlers.log('A Message'); expect(res.write).toBeCalledTimes(1); expect(res.write).toBeCalledWith(`event: log data: "A Message" `); expect(res.end).toBeCalledTimes(0); }); it('should write error and end the connection', async () => { handlers.error(new Error('Some Error')); expect(res.write).toBeCalledTimes(1); expect(res.write).toBeCalledWith(`event: error data: "Some Error" `); expect(res.end).toBeCalledTimes(1); }); it('should finish and end the connection', async () => { handlers.finish({ updated: true }); expect(res.write).toBeCalledTimes(1); expect(res.write).toBeCalledWith(`event: finish data: {"updated":true} `); expect(res.end).toBeCalledTimes(1); }); }); describe('createHttpResponse', () => { const res: jest.Mocked<Response> = { status: jest.fn(), json: jest.fn(), } as any; let handlers: DocsSynchronizerSyncOpts; beforeEach(() => { res.status.mockImplementation(() => res); handlers = createHttpResponse(res); }); afterEach(() => { jest.resetAllMocks(); }); it('should return CREATED if updated', async () => { handlers.finish({ updated: true }); expect(res.status).toBeCalledTimes(1); expect(res.status).toBeCalledWith(201); expect(res.json).toBeCalledTimes(1); expect(res.json).toBeCalledWith({ message: 'Docs updated or did not need updating', }); }); it('should return NOT_MODIFIED if not updated', async () => { expect(() => handlers.finish({ updated: false })).toThrowError( NotModifiedError, ); }); it('should throw custom error', async () => { expect(() => handlers.error(new Error('Some Error'))).toThrowError( /Some Error/, ); }); it('should ignore logs', async () => { expect(() => handlers.log('Some Message')).not.toThrow(); }); });
the_stack
import {isString} from '../../../core'; import {liftToEspObservable} from 'esp-js-rx'; import {Guard, observeEvent, Router, utils, Logger} from 'esp-js'; import {ModelBase} from '../../modelBase'; import {IdFactory} from '../../idFactory'; import {RegionItem} from './regionItem'; import {getViewFactoryMetadataFromModelInstance, ViewFactoryEntry, ViewFactoryMetadata, ViewRegistryModel, RegionRecordState, StateUtils} from '../../viewFactory'; import {EspUiEventNames} from '../../espUiEventNames'; import {RegionItemRecord} from './regionItemRecord'; import {SelectedItemChangedEvent} from './events'; import {RegionManager} from './regionManager'; import {RegionState} from './regionState'; import {SingleModuleLoader} from '../../modules'; import {SystemContainerConst} from '../../dependencyInjection'; import * as uuid from 'uuid'; import {filter, take} from 'rxjs/operators'; const _log = Logger.create('RegionsModelBase'); export enum RegionChangeType { /** * The record was added via via a non-state-load related operation */ RecordAdded, /** * The record was added as part of a state load operation */ RecordAddedFromState, RecordRemoved, RecordUpdated, RecordSelected, } export abstract class RegionBase<TCustomState = any> extends ModelBase { // Helper to kep our underlying state collections immutable. // This is really best effort, if a caller modifies this then not much we can do. // An additional step would be to always maintain a master copy and expose a public copy, but they perhaps we should just pull in an immutable library // At least for now anything that's rendering these lists can rely on the array instance only changing when the data changes. private _state = { _regionRecordsByRecordId: new Map<string, RegionItemRecord>(), _regionRecords: [] as RegionItemRecord[], _selectedRecord: null as RegionItemRecord, _isUnloading: false, get selectedRecord(): RegionItemRecord { return this._selectedRecord; }, get regionRecordsById(): Map<string, RegionItemRecord> { return this._regionRecordsByRecordId; }, get regionRecords(): RegionItemRecord[] { return this._regionRecords; }, has(regionRecordId: string): boolean { const regionItemRecord: RegionItemRecord = this.findRecordById(regionRecordId); return !!regionItemRecord; }, getByRecordId(id): RegionItemRecord { return this._regionRecordsByRecordId.get(id); }, setSelected(item: RegionItemRecord | RegionItem) { let record: RegionItemRecord; if ('regionRecordId' in item) { record = this.findRecordById(item.regionRecordId); } else { record = item; } Guard.isTruthy(this._regionRecordsByRecordId.has(record.id), `record not found`); this._selectedRecord = record; }, addRecord(record: RegionItemRecord) { Guard.isDefined(record, `record must be defined`); Guard.isFalsey(this._regionRecordsByRecordId.has(record.id), `record not found`); this._regionRecordsByRecordId = new Map<string, RegionItemRecord>(this._regionRecordsByRecordId.set(record.id, record)); this._setRecordsArrayAndSelectedItem(); }, updateRecord(record: RegionItemRecord) { Guard.isDefined(record, `record must be defined`); this._deleteByRecordId(record.id); this.addRecord(record); }, removeByRecordId(id: string): RegionItemRecord { Guard.isString(id, `id must be defined and be a string`); Guard.isTruthy(this._regionRecordsByRecordId.has(id), `record not found`); const record = this._regionRecordsByRecordId.get(id); this._deleteByRecordId(record.id); this._setRecordsArrayAndSelectedItem(); return record; }, unload(): RegionItemRecord[] { Guard.isFalsey(this._isUnloading, 'Already unloading'); this._isUnloading = true; const removedItems = []; this._regionRecordsByRecordId.forEach((regionItemRecord: RegionItemRecord) => { if (regionItemRecord.modelCreated && utils.isFunction(regionItemRecord.model.dispose)) { regionItemRecord.model.dispose(); } regionItemRecord.dispose(); removedItems.push(regionItemRecord); }); this._regionRecordsByRecordId = new Map(); this._setRecordsArrayAndSelectedItem(); this._isUnloading = false; return removedItems; }, _setRecordsArrayAndSelectedItem() { this._regionRecords = Array.from<RegionItemRecord>(this._regionRecordsByRecordId.values()); if (this._regionRecords.length === 0) { this._selectedRecord = null; } else { if (this._selectedRecord) { // will either clear (if it no longer exists) or re-set (if instance has changed) this._selectedRecord = this._regionRecordsByRecordId.get(this._selectedRecord.id); } let nothingSelected = !!!this._selectedRecord; if (nothingSelected) { this._selectedRecord = this._regionRecords[0]; } } }, _deleteByRecordId(id: string) { Guard.isTruthy(this._regionRecordsByRecordId.has(id), `record not found`); this._regionRecordsByRecordId.delete(id); this._regionRecordsByRecordId = new Map<string, RegionItemRecord>(this._regionRecordsByRecordId); }, findRecordById(recordId: string) { return Array .from<RegionItemRecord>(this._regionRecordsByRecordId.values()) .find(r => r.id === recordId); } }; protected constructor( protected _regionName : string, router: Router, protected _regionManager: RegionManager, protected _viewRegistry: ViewRegistryModel, modelId = IdFactory.createId(`region-${_regionName}`) ) { super(modelId, router); Guard.isString(_regionName, `_regionName required`); Guard.isDefined(router, `router required`); Guard.isDefined(_regionManager, `_regionManager required`); Guard.isDefined(_viewRegistry, `_viewRegistry required`); } protected get state() { return this._state; } public abstract get stateSavingEnabled(): boolean; /** * A version which will be associated with any state saved for this region. */ public get stateVersion() { return 1; } public get name() { return this._regionName; } /** * Returns the underlying models currently registered with the region (keyed by modelId). * * This is useful if you need to readonly query them (perhaps to save state). * You should not modify these, if you meed to modify raise an event to the model via the Router. */ public get regionRecords(): RegionItemRecord[] { return this._state.regionRecords; } public get selectedRecord(): RegionItemRecord { return this._state.selectedRecord; } public observeEvents() { super.observeEvents(); _log.verbose('starting. Adding model and observing events'); this._registerWithRegionManager(this._regionName); } public getRegionState(): RegionState<TCustomState> { const regionRecordStates = Array .from(this._state.regionRecordsById.values()) .map<RegionRecordState>(regionItemRecord => this.getRegionRecordState(regionItemRecord) ) .filter(c => c != null); return { regionName: this._regionName, stateVersion: this.stateVersion, customState: this.createCustomState(), regionRecordStates: regionRecordStates, }; } /** * Creates a TCustomState which stores any additional data a derived type may want to store for this region. * */ protected createCustomState(): TCustomState { return null; } /** * Called any time a RegionItemRecord is added/removed and/or if the RegionItemRecord 'model creation' state changes (i.e. the record is updated) * @param type * @param change */ protected onStateChanged(type: RegionChangeType, change: RegionItemRecord) { } public existsInRegionByModelId(modelId: string): boolean { return this._state.regionRecords .filter(r => r.modelCreated) .some(r => r.modelId === modelId); } public existsInRegionByRegionItem(regionItem: RegionItem): boolean { return this._state.regionRecordsById.has(regionItem.regionRecordId); } public existsInRegionByRecordId(regionRecordId: string): boolean { return this._state.regionRecordsById.has(regionRecordId); } public existsInRegion(predicate: (regionItemRecord: RegionItemRecord) => boolean): boolean { // This is read only hence can perform the call on any dispatch loop for (let x of this._state.regionRecordsById.values()) { const match = predicate(x); if (match) { return true; } } return false; } @observeEvent(EspUiEventNames.regions_selectedItemChanged) private _onRegionSelectedItemChanged(ev: SelectedItemChangedEvent) { this.setSelected(ev.regionItemRecord); } /** * Set the selected item * @param item: a RegionItemRecord, RegionItem or a string representing the RegionItemRecord.id */ public setSelected(item: RegionItemRecord | string) { if (!this.isOnDispatchLoop()) { this.setSelected(item); return; } if (isString(item)) { item = this._state.findRecordById(item); } this._state.setSelected(item); this.onStateChanged(RegionChangeType.RecordSelected, item); } /** * @deprecated use addToRegion */ public addRegionItem(regionItem: RegionItem): void { this.addToRegion(regionItem); } public addToRegion(regionItem: RegionItem): void { if (!this.isOnDispatchLoop()) { this.ensureOnDispatchLoop(() => this.addToRegion(regionItem)); return; } _log.info(`Adding ${regionItem.toString()} to region ${this._regionName}`); Guard.isFalsey(this._state.has(regionItem.regionRecordId), `Model ${regionItem.modelId} already in region against region record ${regionItem.regionRecordId}`); // We get the initial model and store a reference to it. // In esp the top level model instance never changes. // This is true even for immutable models, they always have a parent that doesn't change, the store that hangs off that parent will change. let model = this._router.getModel(regionItem.modelId); const viewFactoryMetadata: ViewFactoryMetadata = getViewFactoryMetadataFromModelInstance(model); const viewFactoryEntry = this._viewRegistry.getViewFactoryEntry(viewFactoryMetadata.viewKey); let regionItemRecord = RegionItemRecord.createForExistingItem(regionItem.regionRecordId, viewFactoryEntry, model, regionItem.displayOptions); this._addRegionRecord(regionItemRecord); } /** * @deprecated use removeFromRegion */ public removeRegionItem(regionItem: RegionItem): void { this.removeFromRegion(regionItem); } public removeFromRegion(regionRecordId: string): void; public removeFromRegion(regionItem: RegionItem): void; public removeFromRegion(...args: (string|RegionItem)[]): void { if (!this.isOnDispatchLoop()) { this.ensureOnDispatchLoop(() => this._removeFromRegion(args)); return; } this._removeFromRegion(args); } // I have to pull this out as typescript overloads don't allow for a reentrant call as is required via the `isOnDispatchLoop` check. private _removeFromRegion(args: (string|RegionItem)[]): void { let regionRecordId: string; if (typeof args[0] === 'string') { regionRecordId = <string>args[0]; } else { regionRecordId = (<RegionItem>args[0]).regionRecordId; } let regionItemRecord = this._state.findRecordById(regionRecordId); if (regionItemRecord) { this._removeRegionRecord(regionItemRecord); } } private _addRegionRecord(regionItemRecord: RegionItemRecord, recordState?: RegionRecordState): RegionItemRecord { if (!regionItemRecord.modelCreated) { _log.verbose(`Region ${this._regionName}. Adding record [${regionItemRecord.toString()}]. Model not created so will wait for it's module to load.`); const singleModuleLoader = regionItemRecord.viewFactoryEntry.container.resolve<SingleModuleLoader>(SystemContainerConst.single_module_loader); if (singleModuleLoader.hasLoaded) { const model = regionItemRecord.viewFactoryEntry.factory.createView(recordState); regionItemRecord = regionItemRecord.updateWithModel(model); } else { regionItemRecord.addDisposable(singleModuleLoader.loadResults .pipe( filter(lr => lr.hasCompletedLoaded), take(1), liftToEspObservable(this.router, this.modelId), ) .subscribe( () => { if (!this.existsInRegionByRecordId(regionItemRecord.id)) { _log.verbose(`Region [${this._regionName}]. Region Item [${regionItemRecord.toString()}] no longer exists in Region. View will not be created.`); return; } _log.verbose(`Region [${this._regionName}]. Model now created for record [${regionItemRecord.toString()}].`); try { const model = regionItemRecord.viewFactoryEntry.factory.createView(recordState); regionItemRecord = regionItemRecord.updateWithModel(model); } catch (err) { _log.error(`Region [${this._regionName}]. Error calling ViewFactory (${regionItemRecord.viewFactoryEntry.viewFactoryKey}) to create view, Record [${regionItemRecord.toString()}].`, err); regionItemRecord = regionItemRecord.updateWithError(err); } this._state.updateRecord(regionItemRecord); this.onStateChanged(RegionChangeType.RecordUpdated, regionItemRecord); }, (err: any) => { _log.error(`Region [${this._regionName}]. Error waiting for module to load inorder to create view from factory ${recordState.viewFactoryKey}, record [${regionItemRecord.toString()}].`, err); // flag view as error } ) ); } } else { _log.verbose(`Region ${this._regionName}. Adding record [${regionItemRecord.toString()}].`); } this._state.addRecord(regionItemRecord); if (recordState && recordState.isSelected) { this._state.setSelected(regionItemRecord); } const changeType = recordState ? RegionChangeType.RecordAddedFromState : RegionChangeType.RecordAdded; this.onStateChanged(changeType, regionItemRecord); return regionItemRecord; } private _removeRegionRecord(regionItemRecord: RegionItemRecord): void { _log.verbose(`Region ${this._regionName}. Removing record [${regionItemRecord.toString()}].`); this._state.removeByRecordId(regionItemRecord.id); this.onStateChanged(RegionChangeType.RecordRemoved, regionItemRecord); } protected getRegionRecordState(regionItemRecord: RegionItemRecord): RegionRecordState { if (!regionItemRecord.modelCreated) { // If the model isn't created yet for some reason, we just return any initial associated with the item as that's effectively the current state. return regionItemRecord.initialRecordState; // might be null, that's ok } if (regionItemRecord.viewFactoryEntry.isLegacyViewFactory) { // If the view was created by an older version of esp it won't support state being saved in regions. // The old state code relied on the modules saved state for views. return null; } const model = regionItemRecord.model; let viewState: any = null; try { viewState = StateUtils.tryGetState(model); if (viewState) { return { viewFactoryKey: regionItemRecord.viewFactoryMetadata.viewKey, stateVersion: regionItemRecord.viewFactoryMetadata.stateVersion, regionRecordId: regionItemRecord.id, viewState: viewState, isSelected: this.selectedRecord.id === regionItemRecord.id }; } } catch (err) { _log.error(`Region [${this._regionName}]. Error getting state for model with id ${regionItemRecord.modelId}`, err); } return null; } public load(regionState: RegionState<TCustomState>) { Guard.isDefined(regionState, `regionState not defined`); Guard.isArray(regionState.regionRecordStates, `regionState.regionRecordStates is not an array`); this.ensureOnDispatchLoop(() => { _log.debug(`Region ${this._regionName}. Loading state. Item count: ${regionState.regionRecordStates.length}.`); regionState.regionRecordStates.forEach((recordState: RegionRecordState) => { this.loadView(recordState); }); }); } public unload() { if (!this.isOnDispatchLoop()) { this.ensureOnDispatchLoop(() => this.unload()); return; } _log.debug(`Region ${this._regionName}. Unloading.`); const unloadedItems = this._state.unload(); unloadedItems.forEach(record => { this.onStateChanged(RegionChangeType.RecordRemoved, record); }); } protected loadView(recordState: RegionRecordState): RegionItemRecord { Guard.isTruthy(this._router.isOnDispatchLoopFor(this.modelId), `Protected methods should be called on correct dispatch loop`); // At this point the view factories should have been loaded, however each module may not have finished loading. // ViewFactories assume the module is loaded, it would be complicated to push this concern to them, really that's a higher level concern. // The only mid ground is the regions whereby they can try load views for modules that are ready and show some spinning UI for views belonging to modules that are not ready. // We have to do that here and model it via RegionItem. if (this._viewRegistry.hasViewFactory(recordState.viewFactoryKey)) { const viewFactoryEntry: ViewFactoryEntry = this._viewRegistry.getViewFactoryEntry(recordState.viewFactoryKey); let regionRecordId = recordState.regionRecordId || uuid.v4(); const regionItemRecord = RegionItemRecord.createForStateLoadedItem(regionRecordId, viewFactoryEntry, recordState); this._addRegionRecord(regionItemRecord, recordState); return regionItemRecord; } else { // It's possible the component factory isn't loaded, perhaps old state had a component which the users currently isn't entitled to see ATM. _log.warn(`Skipping load for view as it's factory of type [${recordState.viewFactoryKey}] is not registered`); return null; } } private _registerWithRegionManager(regionName) { this._regionManager.registerRegion(regionName, this,); this.addDisposable(() => { this._regionManager.unregisterRegion(regionName); }); } }
the_stack
import { mockProfileBoxerFloydMayweatherJr, mockProfileBoxerGGG, mockProfileBoxerRJJ, mockProfileDoctorAnthonyRuggeroli, mockProfileInspectorMichaelBuchato, mockProfileJudgeDaveMoretti, mockProfileManagerMichaelMcSorleyJr, mockProfileMatchmakerVeliPekkaMaeki, mockProfilePromoterLeonardEllerbe, mockProfileRefereeRobertByrd, mockProfileSupervisorSammyMacias } from "boxrec-mocks"; import {BoxrecRole} from "boxrec-requests/dist/boxrec-requests.constants"; import {WinLossDraw} from "../boxrec.constants"; import {BoxrecPageProfileBoxer} from "./boxrec.page.profile.boxer"; import { BoxrecProfileBoxerBoutOutput, BoxrecProfileBoxerOutput, BoxrecProfileManagerOutput, BoxrecProfileOtherOutput, BoxrecProfilePromoterOutput } from "./boxrec.page.profile.constants"; import {BoxrecPageProfileEventRow} from "./boxrec.page.profile.event.row"; import {BoxrecPageProfileEvents} from "./boxrec.page.profile.events"; import {BoxrecPageProfileManager} from "./boxrec.page.profile.manager"; import {BoxrecPageProfileManagerBoxerRow} from "./boxrec.page.profile.manager.boxer.row"; import {BoxrecPageProfileOtherCommon} from "./boxrec.page.profile.other.common"; import {BoxrecPageProfileOtherCommonBoutRow} from "./boxrec.page.profile.other.common.bout.row"; import {BoxrecPageProfilePromoter} from "./boxrec.page.profile.promoter"; import {BoxrecProfileTable} from "./boxrec.profile.constants"; describe("class BoxrecPageProfile", () => { describe("class BoxrecPageProfile", () => { let boxerGGG: BoxrecPageProfileBoxer; let boxerFloydMayweatherJr: BoxrecPageProfileBoxer; let judgeDaveMoretti: BoxrecPageProfileOtherCommon; let doctorAnthonyRuggeroli: BoxrecPageProfileEvents; let promoterLeonardEllerbe: BoxrecPageProfilePromoter; let refereeRobertByrd: BoxrecPageProfileOtherCommon; let inspectorMichaelBuchato: BoxrecPageProfileEvents; let managerMichaelMcSorleyJr: BoxrecPageProfileManager; let matchmakerVeliPekkaMaeki: BoxrecPageProfileEvents; let supervisorSammyMacias: BoxrecPageProfileOtherCommon; beforeAll(() => { boxerGGG = new BoxrecPageProfileBoxer(mockProfileBoxerGGG); boxerFloydMayweatherJr = new BoxrecPageProfileBoxer(mockProfileBoxerFloydMayweatherJr); judgeDaveMoretti = new BoxrecPageProfileOtherCommon(mockProfileJudgeDaveMoretti); doctorAnthonyRuggeroli = new BoxrecPageProfileEvents(mockProfileDoctorAnthonyRuggeroli); promoterLeonardEllerbe = new BoxrecPageProfilePromoter(mockProfilePromoterLeonardEllerbe); refereeRobertByrd = new BoxrecPageProfileOtherCommon(mockProfileRefereeRobertByrd); inspectorMichaelBuchato = new BoxrecPageProfileEvents(mockProfileInspectorMichaelBuchato); managerMichaelMcSorleyJr = new BoxrecPageProfileManager(mockProfileManagerMichaelMcSorleyJr); matchmakerVeliPekkaMaeki = new BoxrecPageProfileEvents(mockProfileMatchmakerVeliPekkaMaeki); supervisorSammyMacias = new BoxrecPageProfileOtherCommon(mockProfileSupervisorSammyMacias); }); describe("role boxer", () => { describe("getter output", () => { let outputRJJ: BoxrecProfileBoxerOutput; let outputGGG: BoxrecProfileBoxerOutput; beforeAll(() => { outputRJJ = new BoxrecPageProfileBoxer(mockProfileBoxerRJJ).output; outputGGG = new BoxrecPageProfileBoxer(mockProfileBoxerGGG).output; }); it("should return the name", () => { expect(outputRJJ.name).toBe("Roy Jones Jr"); }); it("should return null if they are not suspended", () => { expect(outputRJJ.suspended).toBe(null); }); it("should return the boxer globalId", () => { expect(outputRJJ.globalId).toBe(774820); expect(outputGGG.globalId).toBe(356831); }); it("should return the boxer's star rating", () => { expect(outputGGG.rating).toEqual(jasmine.any(Number)); }); it("should return boxer's record", () => { expect(outputRJJ.record.win).toBeGreaterThanOrEqual(66); expect(outputRJJ.record.draw).toBeGreaterThanOrEqual(0); expect(outputRJJ.record.loss).toBeGreaterThanOrEqual(9); }); it("should return the URL of the person's profile picture", () => { // was previously "https://static.boxrec.com/thumb" expect(outputRJJ.picture) .toContain("https://boxrec.com/media/images"); }); it("should return the number of bouts this boxer has been in, not including scheduled bouts", () => { expect(outputRJJ.numberOfBouts).toBeGreaterThanOrEqual(75); }); describe("getter roles", () => { it("should return an array of the person's roles if they have one role", () => { // todo need a person with one role }); it("should not include `All Sports`", () => { // todo }); it("should return an array of the person's roles (sorted by id, name ASC)", () => { expect(outputRJJ.role).toEqual([{ id: 774820, name: BoxrecRole.proBoxer, }, { id: 774820, name: BoxrecRole.promoter, }]); }); }); it("should return the number of professionally fought rounds this boxer has been in", () => { expect(outputRJJ.rounds).toBeGreaterThanOrEqual(495); }); it("should return the number of KOs/TKOs this boxer has dealt out", () => { expect(outputRJJ.KOs).toBeGreaterThanOrEqual(47); }); it("should return the status of the person", () => { expect(outputRJJ.status).toBe("inactive"); }); it("should return the birth name of the person", () => { expect(outputRJJ.birthName).toBe("Roy Levesta Jones"); }); it("should give the nickname or alias of the boxer", () => { expect(outputRJJ.alias).toBe(null); }); it("should return the date this person was born", () => { expect(outputRJJ.born).toBe("1969-01-16"); }); it("should return the date of this person's debut into the sport of boxing", () => { expect(outputRJJ.debut).toBe("1989-05-06"); }); it("should return the nationality of this person", () => { expect(outputRJJ.nationality).toBe("USA"); }); it("should return the division the last division this boxer fought in", () => { expect(outputRJJ.division).toBe("light heavyweight"); }); describe("getter height", () => { it("should return the height of the boxer", () => { expect(outputRJJ.height).toEqual([5, 11, 180]); }); it("should convert any heights with fractional numbers into decimals", () => { expect(outputGGG.height).toEqual([5, 10.5, 179]); }); }); it("should return the reach of the boxer", () => { expect(outputRJJ.reach).toEqual([74, 188]); }); it("should return the current residence of the person", () => { expect(outputRJJ.residence).toBe("Pensacola, Florida, USA"); }); describe("getter vadacbp", () => { it("should return boolean if VADA is on profile", () => { expect(outputGGG.vadacbp).toEqual(jasmine.any(Boolean)); }); it("should return false if VADA is not on profile", () => { expect(outputRJJ.vadacbp).toBe(false); }); }); describe("getter ranking", () => { it("should return the boxer's ranking", () => { expect(outputGGG.ranking).toEqual([ [jasmine.any(Number), jasmine.any(Number)], [jasmine.any(Number), jasmine.any(Number)], ]); }); it("should return null if the boxer is not ranked", () => { expect(outputRJJ.ranking).toBeNull(); }); }); it("should return the currently held titles", () => { expect(outputGGG.titlesHeld).toEqual(jasmine.any(Array)); }); it("should return the birth place of the person", () => { expect(outputRJJ.birthPlace).toBe("Pensacola, Florida, USA"); }); describe("getter bouts", () => { let gggCanelo: BoxrecProfileBoxerBoutOutput; let rjjLacy: BoxrecProfileBoxerBoutOutput; let judgeDaveMorettiLatestBout: BoxrecPageProfileOtherCommonBoutRow; let refereeRobertByrdLatestBout: BoxrecPageProfileOtherCommonBoutRow; let supervisorSammyMaciasLatestBout: BoxrecPageProfileOtherCommonBoutRow; beforeAll(() => { gggCanelo = outputGGG.bouts[37]; rjjLacy = outputRJJ.bouts[58]; judgeDaveMorettiLatestBout = judgeDaveMoretti.bouts[0]; refereeRobertByrdLatestBout = refereeRobertByrd.bouts[0]; supervisorSammyMaciasLatestBout = supervisorSammyMacias.bouts[0]; }); it("should have all bouts to offset the ad that BoxRec has in the list of profile bouts", () => { expect(outputGGG.bouts.length).toBeGreaterThanOrEqual(40); }); it("should have bouts for people other than boxers", () => { expect(judgeDaveMoretti.bouts.length).toBeGreaterThan(0); }); describe("getter links", () => { it("should parse out `javascript` dropdown open links", () => { supervisorSammyMaciasLatestBout.links.other.forEach(link => { expect(link).not.toContain("javascript"); }); }); it("should return an object of links", () => { expect(supervisorSammyMaciasLatestBout.links).toEqual({ bio: 2056855, bout: "726555/2056855", event: 726555, other: [], }); }); }); describe("getter rating", () => { it("should return the rating of the bout", () => { expect(gggCanelo.rating).toBe(100); }); }); describe("getter date", () => { it("should return the date if it is known", () => { expect(gggCanelo.date).toBe("2017-09-16"); }); it("should return the date of the judged/refereed bout", () => { expect(judgeDaveMorettiLatestBout.date).toMatch(/^\d{4}-\d{2}-\d{2}$/); expect(refereeRobertByrdLatestBout.date).toMatch(/^\d{4}-\d{2}-\d{2}$/); }); }); describe("getter location", () => { it("should return the location", () => { expect(refereeRobertByrdLatestBout.location).toEqual({ country: {id: "US", name: "USA"}, region: {id: "NV", name: "Nevada"}, town: {id: 20388, name: "Las Vegas"}, }); }); }); describe("getter firstBoxerWeight (other role)", () => { it("should return the first boxer's weight", () => { expect(refereeRobertByrdLatestBout.firstBoxerWeight).toBeGreaterThan(110); }); }); describe("getter rating (other role)", () => { it("should return the rating of the bout", () => { expect(refereeRobertByrdLatestBout.rating).toBeGreaterThanOrEqual(0); }); }); describe("getter secondBoxerWeight (other role)", () => { it("should return the first boxer's weight", () => { expect(refereeRobertByrdLatestBout.secondBoxerWeight).toBeGreaterThan(110); }); }); describe("getter firstBoxerWeight", () => { it("should return the first boxer's weight", () => { expect(gggCanelo.firstBoxerWeight).toBe(160); }); }); describe("getter secondBoxer", () => { it("should return name", () => { expect(gggCanelo.secondBoxer.name).toBe("Saul Alvarez"); }); }); describe("getter secondBoxerWeight", () => { it("should return the second boxer's weight", () => { expect(gggCanelo.secondBoxerWeight).toBe(160); }); }); describe("getter secondBoxerRecord", () => { it("should return the second boxer's record at that time", () => { expect(gggCanelo.secondBoxerRecord.win).toBe(49); }); }); describe("getter secondBoxerLast6", () => { it("should return the second boxer's last 6", () => { expect(gggCanelo.secondBoxerLast6).toEqual([WinLossDraw.win, WinLossDraw.win, WinLossDraw.win, WinLossDraw.win, WinLossDraw.win, WinLossDraw.win]); }); }); describe("getter bouts", () => { it("should have an equal length or greater of bouts/scheduled bouts compared against bouts they've completed", () => { expect(outputGGG.bouts.length).toBeGreaterThanOrEqual(outputGGG.numberOfBouts); }); }); describe("getter location", () => { it("should give the venue information", () => { expect(gggCanelo.location).toBe("T-Mobile Arena, Las Vegas"); }); it("should be a string since there are no links in the locations", () => { expect(rjjLacy.location).toBe("Coast Coliseum, Biloxi"); }); }); describe("getter links", () => { it("should return links in an object", () => { expect(gggCanelo.links).toEqual({ bio: 2160855, bout: "751017/2160855", event: 751017, other: [], }); }); it("should return the event id", () => { expect(gggCanelo.links.event).toBe(751017); }); }); describe("getter judges", () => { it("should list the judges names", () => { expect(gggCanelo.judges[0].name).toBe("Adalaide Byrd"); }); }); describe("getter referee", () => { it("should list the referee", () => { expect(gggCanelo.referee.name).toBe("Kenny Bayless"); }); }); describe("getter numberOfRounds", () => { it("should return the number of rounds the bout was", () => { expect(gggCanelo.numberOfRounds).toEqual([12, 12]); }); }); describe("getter outcome", () => { it("should return the outcome of the bout", () => { expect(gggCanelo.outcome).toEqual(WinLossDraw.draw); }); }); describe("getter result", () => { it("should return how the bout ended", () => { expect(gggCanelo.result).toEqual(["draw", "SD", "split decision"]); }); }); describe("getter titles", () => { it("should return what titles were on the line (in order by id)", () => { expect(gggCanelo.titles).toEqual([ { id: "6/Middleweight", name: "World Boxing Council World Middleweight Title" }, { id: "43/Middleweight", name: "World Boxing Association Super World Middleweight Title" }, { id: "75/Middleweight", name: "International Boxing Federation World Middleweight Title" }, { id: "189/Middleweight", name: "International Boxing Organization World Middleweight Title", supervisor: { id: 403048, name: "Ed Levine", }, }, ]); }); it("should convert the short divisions to full division for consistency", () => { expect(rjjLacy.titles[0].name) .toBe("World Boxing Organisation NABO Light Heavyweight Title"); }); it("should be able to parse weight divisions with spaces (ex. Light%20Heavyweight)", () => { expect(rjjLacy.titles).toEqual([{ id: "96/Light%20Heavyweight", name: "World Boxing Organisation NABO Light Heavyweight Title", }]); }); }); it("should return the first fighter weight", () => { expect(rjjLacy.firstBoxerWeight).toEqual(174); }); it("should return the number of rounds", () => { expect(rjjLacy.numberOfRounds).toEqual([10, 12]); }); it("should return the second fighter weight", () => { expect(rjjLacy.secondBoxerWeight).toEqual(172); }); it("should return the bout date", () => { expect(rjjLacy.date).toMatch(/^\d{4}-\d{2}-\d{2}$/); }); it("should return the outcome/result of the fight", () => { expect(rjjLacy.outcome).toBe(WinLossDraw.win); }); it("should return the bout date", () => { // todo }); it("should return the second boxer", () => { expect(rjjLacy.secondBoxer).toEqual({ id: 31593, name: "Jeff Lacy" }); }); it("should return the second boxer last 6", () => { expect(rjjLacy.secondBoxerLast6).toEqual([WinLossDraw.loss, WinLossDraw.win, WinLossDraw.win, WinLossDraw.win, WinLossDraw.loss, WinLossDraw.win]); }); describe("getter firstBoxerRating", () => { it("should return the rating of the first boxer before and after the fight", () => { expect(gggCanelo.firstBoxerRating).toEqual([jasmine.any(Number), jasmine.any(Number)]); }); }); describe("secondBoxerRating", () => { it("should return the rating of the second boxer before and after the fight", () => { expect(gggCanelo.secondBoxerRating).toEqual([jasmine.any(Number), jasmine.any(Number)]); }); }); describe("getter otherInfo", () => { it("should return an array", () => { expect(outputGGG.otherInfo.length).toEqual(jasmine.any(Number)); }); it("should not contain known profile values like global id", () => { const globalId: string[] | undefined = outputGGG.otherInfo.find((key: any) => key[0] === BoxrecProfileTable.globalId); expect(globalId).toBeUndefined(); }); }); describe("getter hasBoutScheduled", () => { it("should return true/false if the boxer has a bout scheduled", () => { expect(outputGGG.hasBoutScheduled).toEqual(jasmine.any(Boolean)); }); }); describe("getter stance", () => { it("should return the stance", () => { expect(outputGGG.stance).toBe("orthodox"); }); }); }); }); }); describe("role promoter", () => { let output: BoxrecProfilePromoterOutput; beforeAll(() => { output = promoterLeonardEllerbe.output; }); describe("getter company", () => { it("should return the company name as a string", () => { expect(output.company).toBe("Mayweather Promotions"); }); }); }); describe("role judge", () => { describe("getter globalId", () => { it("should return the judge globalId", () => { expect(judgeDaveMoretti.globalId).toBe(401002); }); }); describe("getter secondBoxerRecord", () => { // todo should this be undefined? xit("should be undefined", () => { expect(judgeDaveMoretti.bouts[0].secondBoxerRecord).toBeUndefined(); }); }); describe("getter residence", () => { it("should return the residence for other roles", () => { expect(judgeDaveMoretti.residence).toBe("Las Vegas, Nevada, USA"); }); }); describe("getter bouts", () => { // todo this shouldn't be under role judge it("should have an equal length or greater of bouts/scheduled bouts compared against bouts they've completed", () => { expect(boxerGGG.bouts.length).toBeGreaterThanOrEqual(boxerGGG.numberOfBouts); }); // todo this shouldn't be under role judge it("should give a boxer rating to boxers even if they lose of their first bout", () => { expect(boxerFloydMayweatherJr.bouts[49].secondBoxerRating) .toEqual([jasmine.any(Number), jasmine.any(Number)]); }); describe("getter numberOfRounds", () => { it("should return the number of rounds for bouts", () => { expect(judgeDaveMoretti.bouts[0].numberOfRounds) .toEqual([jasmine.any(Number), jasmine.any(Number)]); }); }); describe("getter secondBoxerLast6", () => { xit("should be undefined", () => { // todo this fails, it should be undefined expect(judgeDaveMoretti.bouts[0].secondBoxerLast6).toBeUndefined(); }); }); }); describe("getter birthPlace", () => { let output: BoxrecProfileOtherOutput; beforeAll(() => { output = judgeDaveMoretti.output; }); it("should return the null if the birth place isn't set", () => { expect(output.birthPlace).toBe(null); }); }); }); describe("role manager", () => { let output: BoxrecProfileManagerOutput; beforeAll(() => { output = managerMichaelMcSorleyJr.output; }); describe("getter boxers", () => { let boxer: BoxrecPageProfileManagerBoxerRow; beforeAll(() => { boxer = output.boxers[0]; }); describe("getter name", () => { it("should return the name", () => { expect(boxer.name).toBeDefined(); }); it("should not be empty", () => { expect(boxer.name).not.toBe(""); }); }); describe("getter stance", () => { it("should return the stance", () => { expect(boxer.stance === "orthodox" || boxer.stance === "southpaw").toBeTruthy(); }); }); describe("getter residence", () => { it("should have the fighters residence", () => { expect(boxer.residence).toEqual({ country: jasmine.anything(), region: jasmine.anything(), town: jasmine.anything(), }); }); }); describe("getter division", () => { it("should return the division as a string", () => { expect(boxer.division).toContain(boxer.division); }); }); describe("getter age", () => { it("should return the age", () => { expect(boxer.age).toBeGreaterThan(12); }); }); describe("getter record", () => { it("should return the person's record", () => { const keys: string[] = Object.keys(boxer.record); expect(keys).toContain(WinLossDraw.win); expect(keys).toContain(WinLossDraw.draw); expect(keys).toContain(WinLossDraw.loss); }); }); describe("getter last6", () => { it("should return the last 6", () => { expect(Object.values(WinLossDraw)).toContain(boxer.last6[0]); }); }); describe("getter debut", () => { it("should return the last 6", () => { expect(boxer.debut).toMatch(/^\d{4}-\d{2}-\d{2}$/); }); }); }); }); describe("roles with events", () => { let matchmakerVeliPekkaMaekiEvent: BoxrecPageProfileEventRow; let doctorAnthonyRuggeroliEvent: BoxrecPageProfileEventRow; let leonardEllerbeEvent: BoxrecPageProfileEventRow; let inspectorMichaelBuchatoEvent: BoxrecPageProfileEventRow; beforeAll(() => { matchmakerVeliPekkaMaekiEvent = matchmakerVeliPekkaMaeki.output.events[0]; doctorAnthonyRuggeroliEvent = doctorAnthonyRuggeroli.output.events[0]; leonardEllerbeEvent = promoterLeonardEllerbe.output.events[0]; inspectorMichaelBuchatoEvent = inspectorMichaelBuchato.output.events[0]; }); // these tests are to see if the columns still match up between different `roles` describe("getter events", () => { it("should have the date", () => { const dateRegex: RegExp = /^\d{4}-\d{2}-\d{2}$/; expect(doctorAnthonyRuggeroliEvent.date).toMatch(dateRegex); expect(leonardEllerbeEvent.date).toMatch(dateRegex); expect(inspectorMichaelBuchatoEvent.date).toMatch(dateRegex); expect(matchmakerVeliPekkaMaekiEvent.date).toMatch(dateRegex); }); describe("getter venue", () => { it("should have the id of the venue", () => { expect(doctorAnthonyRuggeroliEvent.venue.id).toBeGreaterThanOrEqual(0); expect(leonardEllerbeEvent.venue.id).toBeGreaterThanOrEqual(0); expect(inspectorMichaelBuchatoEvent.venue.id).toBeGreaterThanOrEqual(0); expect(matchmakerVeliPekkaMaekiEvent.venue.id).toBeGreaterThanOrEqual(0); }); it("should have the name of the venue", () => { expect(doctorAnthonyRuggeroliEvent.venue.name).toEqual(jasmine.any(String)); expect(leonardEllerbeEvent.venue.name).toEqual(jasmine.any(String)); expect(inspectorMichaelBuchatoEvent.venue.name).toEqual(jasmine.any(String)); expect(matchmakerVeliPekkaMaekiEvent.venue.name).toEqual(jasmine.any(String)); }); }); describe("getter links", () => { it("should return an object with `event` in it", () => { expect(leonardEllerbeEvent.links).toEqual( { event: jasmine.any(Number), } ); }); }); }); }); describe("getter socialMedia", () => { it("should include social media links", () => { expect(boxerGGG.socialMedia).toBeDefined(); }); }); }); });
the_stack
import __Utils = require("./Utils") export import Utils = __Utils.Utils; import __Angle = require("./Angle") export import Angle = __Angle.Angle; import __Vec2 = require("./Vec2") export import Vec2 = __Vec2.Vec2; /** * A three-component vector type. */ export class Vec3 { x: number; y: number; z: number; // TODO: // GetAngleBetween // CreateRandomDeviationX/Y/Z/Normal /** * Default initializes the vector to all zero. */ constructor(x: number = 0, y: number = 0, z: number = 0) { // [tested] this.x = x; this.y = y; this.z = z; } /** * Returns a duplicate of this vector. */ Clone(): Vec3 { // [tested] return new Vec3(this.x, this.y, this.z); } /** * Returns a duplicate Vec2 with the z component removed. */ CloneAsVec2() { // [tested] return new Vec2(this.x, this.y); } /** * Returns a vector with all components set to zero. */ static ZeroVector(): Vec3 { // [tested] return new Vec3(0, 0, 0); } /** * Returns a vector with all components set to one. */ static OneVector(): Vec3 { // [tested] return new Vec3(1, 1, 1); } /** * Returns the vector (1, 0, 0) */ static UnitAxisX(): Vec3 { // [tested] return new Vec3(1, 0, 0); } /** * Returns the vector (0, 1, 0) */ static UnitAxisY(): Vec3 { // [tested] return new Vec3(0, 1, 0); } /** * Returns the vector (0, 0, 1) */ static UnitAxisZ(): Vec3 { // [tested] return new Vec3(0, 0, 1); } /** * Sets all components to the given values. */ Set(x: number, y: number, z: number): void { // [tested] this.x = x; this.y = y; this.z = z; } /** * Copies all component values from rhs. */ SetVec3(rhs: Vec3): void { // [tested] this.x = rhs.x; this.y = rhs.y; this.z = rhs.z; } /** * Sets all components to the value 'val'. */ SetAll(val: number): void { // [tested] this.x = val; this.y = val; this.z = val; } /** * Sets all components to zero. */ SetZero(): void { // [tested] this.x = 0; this.y = 0; this.z = 0; } /** * Returns the squared length of the vector. */ GetLengthSquared(): number { // [tested] return this.x * this.x + this.y * this.y + this.z * this.z; } /** * Returns the length of the vector. */ GetLength(): number { // [tested] return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } /** * Computes and returns the length of the vector, and normalizes the vector. * This is more efficient than calling GetLength() followed by Normalize(). */ GetLengthAndNormalize(): number { // [tested] let length = this.GetLength(); let invLength = 1.0 / length; this.x *= invLength; this.y *= invLength; this.z *= invLength; return length; } /** * Normalizes the vector. Afterwards its length will be one. * This only works on non-zero vectors. Calling Normalize() on a zero-vector is an error. */ Normalize(): void { // [tested] let invLength = 1.0 / this.GetLength(); this.x *= invLength; this.y *= invLength; this.z *= invLength; } /** * Returns a normalized duplicate of this vector. * Calling this on a zero-vector is an error. */ GetNormalized(): Vec3 { // [tested] let norm = this.Clone(); norm.Normalize(); return norm; } /** * Normalizes the vector as long as it is not a zero-vector (within the given epsilon). * If it is determined to be too close to zero, it is set to 'fallback'. * * @param fallback The value to use in case 'this' is too close to zero. * @param epsilon The epsilon within this vector is considered to be a zero-vector. * @returns true if the vector was normalized regularly, false if the vector was close to zero and 'fallback' was used instead. */ NormalizeIfNotZero(fallback: Vec3 = new Vec3(1, 0, 0), epsilon: number = 0.000001): boolean { // [tested] let length = this.GetLength(); if (length >= -epsilon && length <= epsilon) { this.SetVec3(fallback); return false; } this.DivNumber(length); return true; } /** * Checks whether all components of this are close to zero. */ IsZero(epsilon: number = 0): boolean { // [tested] if (epsilon != 0) { return this.x >= -epsilon && this.x <= epsilon && this.y >= -epsilon && this.y <= epsilon && this.z >= -epsilon && this.z <= epsilon; } else { return this.x == 0 && this.y == 0 && this.z == 0; } } /** * Checks whether this is normalized within some epsilon. */ IsNormalized(epsilon: number = 0.001): boolean { // [tested] let length = this.GetLength(); return (length >= 1.0 - epsilon) && (length <= 1.0 + epsilon); } /** * Returns a negated duplicate of this. */ GetNegated(): Vec3 { // [tested] return new Vec3(-this.x, -this.y, -this.z); } /** * Negates all components of this. */ Negate(): void { // [tested] this.x = -this.x; this.y = -this.y; this.z = -this.z; } /** * Adds rhs component-wise to this. */ AddVec3(rhs: Vec3): void { // [tested] this.x += rhs.x; this.y += rhs.y; this.z += rhs.z; } /** * Subtracts rhs component-wise from this. */ SubVec3(rhs: Vec3): void { // [tested] this.x -= rhs.x; this.y -= rhs.y; this.z -= rhs.z; } /** * Multiplies rhs component-wise into this. */ MulVec3(rhs: Vec3): void { // [tested] this.x *= rhs.x; this.y *= rhs.y; this.z *= rhs.z; } /** * Divides each component of this by rhs. */ DivVec3(rhs: Vec3): void { // [tested] this.x /= rhs.x; this.y /= rhs.y; this.z /= rhs.z; } /** * Multiplies all components of this by 'val'. */ MulNumber(val: number): void { // [tested] this.x *= val; this.y *= val; this.z *= val; } /** * Divides all components of this by 'val'. */ DivNumber(val: number): void { // [tested] let invVal = 1.0 / val; this.x *= invVal; this.y *= invVal; this.z *= invVal; } /** * Checks whether this and rhs are exactly identical. */ IsIdentical(rhs: Vec3): boolean { // [tested] return this.x == rhs.x && this.y == rhs.y && this.z == rhs.z; } /** * Checks whether this and rhs are approximately equal within a given epsilon. */ IsEqual(rhs: Vec3, epsilon: number = 0.0001): boolean { // [tested] return (this.x >= rhs.x - epsilon && this.x <= rhs.x + epsilon) && (this.y >= rhs.y - epsilon && this.y <= rhs.y + epsilon) && (this.z >= rhs.z - epsilon && this.z <= rhs.z + epsilon); } /** * Returns the dot-product between this and rhs. */ Dot(rhs: Vec3): number { // [tested] return this.x * rhs.x + this.y * rhs.y + this.z * rhs.z; } /** * Returns the cross-product between this and rhs. */ CrossRH(rhs: Vec3): Vec3 { // [tested] return new Vec3(this.y * rhs.z - this.z * rhs.y, this.z * rhs.x - this.x * rhs.z, this.x * rhs.y - this.y * rhs.x); } /** * Sets this to be the cross product between lhs and rhs. */ SetCrossRH(lhs: Vec3, rhs: Vec3): void { // [tested] this.x = lhs.y * rhs.z - lhs.z * rhs.y; this.y = lhs.z * rhs.x - lhs.x * rhs.z; this.z = lhs.x * rhs.y - lhs.y * rhs.x; } /** * Returns a vector consisting of the minimum of the respective components of this and rhs. */ GetCompMin(rhs: Vec3): Vec3 { // [tested] return new Vec3(Math.min(this.x, rhs.x), Math.min(this.y, rhs.y), Math.min(this.z, rhs.z)); } /** * Returns a vector consisting of the maximum of the respective components of this and rhs. */ GetCompMax(rhs: Vec3): Vec3 { // [tested] return new Vec3(Math.max(this.x, rhs.x), Math.max(this.y, rhs.y), Math.max(this.z, rhs.z)); } /** * Returns a vector where each component is set to this component's value, clamped to the respective low and high value. */ GetCompClamp(low: Vec3, high: Vec3): Vec3 { // [tested] let _x = Math.max(low.x, Math.min(high.x, this.x)); let _y = Math.max(low.y, Math.min(high.y, this.y)); let _z = Math.max(low.z, Math.min(high.z, this.z)); return new Vec3(_x, _y, _z); } /** * Returns a vector with each component being the product of this and rhs. */ GetCompMul(rhs: Vec3): Vec3 { // [tested] return new Vec3(this.x * rhs.x, this.y * rhs.y, this.z * rhs.z); } /** * Returns a vector with each component being the division of this and rhs. */ GetCompDiv(rhs: Vec3): Vec3 { // [tested] return new Vec3(this.x / rhs.x, this.y / rhs.y, this.z / rhs.z); } /** * Returns a vector with each component set to the absolute value of this vector's respective component. */ GetAbs(): Vec3 { // [tested] return new Vec3(Math.abs(this.x), Math.abs(this.y), Math.abs(this.z)); } /** * Sets this vector's components to the absolute value of lhs's respective components. */ SetAbs(lhs: Vec3): void { // [tested] this.x = Math.abs(lhs.x); this.y = Math.abs(lhs.y); this.z = Math.abs(lhs.z); } /** * Sets this vector to be the normal of the plane formed by the given three points in space. * The points are expected to be in counter-clockwise order to define the 'front' of a triangle. * If the points are given in clockwise order, the normal will point in the opposite direction. * The points must form a proper triangle, if they are degenerate, the calculation may fail. * * @returns true when the normal could be calculated successfully. */ CalculateNormal(v1: Vec3, v2: Vec3, v3: Vec3): boolean { // [tested] let tmp1 = new Vec3(); tmp1.SetSub(v3, v2); let tmp2 = new Vec3(); tmp2.SetSub(v1, v2); this.SetCrossRH(tmp1, tmp2); return this.NormalizeIfNotZero(); } /** * Adjusts this vector such that it is orthogonal to the given normal. * The operation may change the length of this vector. */ MakeOrthogonalTo(normal: Vec3): void { // [tested] let ortho = normal.CrossRH(this); this.SetCrossRH(ortho, normal); } /** * Returns an arbitrary vector that is orthogonal to this vector. */ GetOrthogonalVector(): Vec3 { // [tested] if (Math.abs(this.y) < 0.999) { return this.CrossRH(new Vec3(0, 1, 0)); } return this.CrossRH(new Vec3(1, 0, 0)); } /** * Returns a vector that is this vector reflected along the given normal. */ GetReflectedVector(normal: Vec3): Vec3 { // [tested] let res = this.Clone(); let tmp = normal.Clone(); tmp.MulNumber(this.Dot(normal) * 2.0); res.SubVec3(tmp); return res; } /** * Sets this vector to be the addition of lhs and rhs. */ SetAdd(lhs: Vec3, rhs: Vec3): void { // [tested] this.x = lhs.x + rhs.x; this.y = lhs.y + rhs.y; this.z = lhs.z + rhs.z; } /** * Sets this vector to be the subtraction of lhs and rhs. */ SetSub(lhs: Vec3, rhs: Vec3): void { // [tested] this.x = lhs.x - rhs.x; this.y = lhs.y - rhs.y; this.z = lhs.z - rhs.z; } /** * Sets this vector to be the product of lhs and rhs. */ SetMul(lhs: Vec3, rhs: number): void { // [tested] this.x = lhs.x * rhs; this.y = lhs.y * rhs; this.z = lhs.z * rhs; } /** * Sets this vector to be the division of lhs and rhs. */ SetDiv(lhs: Vec3, rhs: number): void { // [tested] let invRhs = 1.0 / rhs; this.x = lhs.x * invRhs; this.y = lhs.y * invRhs; this.z = lhs.z * invRhs; } /** * Attempts to modify this vector such that it has the desired length. * Requires that this vector is not zero. * * @returns true if the vector's length could be changed as desired. */ SetLength(length: number, epsilon: number): boolean { // [tested] if (!this.NormalizeIfNotZero(Vec3.ZeroVector(), epsilon)) return false; this.MulNumber(length); return true; } /** * Sets this vector to the linear interpolation between lhs and rhs. * @param lerpFactor Factor between 0 and 1 that specifies how much to interpolate. */ SetLerp(lhs: Vec3, rhs: Vec3, lerpFactor: number) { this.SetSub(rhs, lhs); this.MulNumber(lerpFactor); this.AddVec3(lhs); } /** * Returns a random point inside a sphere of radius 1 around the origin. */ static CreateRandomPointInSphere(): Vec3 { // [tested] let px: number, py: number, pz: number; let len: number = 0.0; do { px = Math.random() * 2.0 - 1.0; py = Math.random() * 2.0 - 1.0; pz = Math.random() * 2.0 - 1.0; len = (px * px) + (py * py) + (pz * pz); } while (len > 1.0 || len <= 0.000001); // prevent the exact center return new Vec3(px, py, pz); } /** * Returns a random direction vector. */ static CreateRandomDirection(): Vec3 { // [tested] let res = Vec3.CreateRandomPointInSphere(); res.Normalize(); return res; } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormWork_Order { interface tab__B8E326EE_5C21_4A18_BA55_E3B56966C249_Sections { _B14F3E67_E51B_4B3E_BB7F_A9CF0CF8DC17: DevKit.Controls.Section; _B8E326EE_5C21_4A18_BA55_E3B56966C249_SECTION_2: DevKit.Controls.Section; _B8E326EE_5C21_4A18_BA55_E3B56966C249_SECTION_3: DevKit.Controls.Section; _B8E326EE_5C21_4A18_BA55_E3B56966C249_SECTION_7: DevKit.Controls.Section; f1tab_mainsettings_section_5: DevKit.Controls.Section; tab_3_section_1: DevKit.Controls.Section; tab_8_section_1: DevKit.Controls.Section; } interface tab_DeviceInsightsTab_Sections { DeviceInsightsSection: DevKit.Controls.Section; } interface tab_f1tab_additionalsettings_Sections { f1tab_settings_section_address: DevKit.Controls.Section; } interface tab_f1tab_mainsettings_Sections { f1tab_mainsettings_section_2: DevKit.Controls.Section; f1tab_mainsettings_section_3: DevKit.Controls.Section; tab_7_section_1: DevKit.Controls.Section; } interface tab_f1tab_record_log_Sections { tab_6_section_1: DevKit.Controls.Section; } interface tab_KnowledgeArticlesTab_Sections { _B8E326EE_5C21_4A18_BA55_E3B56966C249_SECTION_8: DevKit.Controls.Section; } interface tab_tab_5_Sections { tab_5_section_2: DevKit.Controls.Section; } interface tab_tab_6_Sections { tab_6_section_2: DevKit.Controls.Section; } interface tab_tab_7_Sections { tab_7_section_1_2: DevKit.Controls.Section; } interface tab_tab_8_Sections { tab_8_section_2: DevKit.Controls.Section; } interface tab__B8E326EE_5C21_4A18_BA55_E3B56966C249 extends DevKit.Controls.ITab { Section: tab__B8E326EE_5C21_4A18_BA55_E3B56966C249_Sections; } interface tab_DeviceInsightsTab extends DevKit.Controls.ITab { Section: tab_DeviceInsightsTab_Sections; } interface tab_f1tab_additionalsettings extends DevKit.Controls.ITab { Section: tab_f1tab_additionalsettings_Sections; } interface tab_f1tab_mainsettings extends DevKit.Controls.ITab { Section: tab_f1tab_mainsettings_Sections; } interface tab_f1tab_record_log extends DevKit.Controls.ITab { Section: tab_f1tab_record_log_Sections; } interface tab_KnowledgeArticlesTab extends DevKit.Controls.ITab { Section: tab_KnowledgeArticlesTab_Sections; } interface tab_tab_5 extends DevKit.Controls.ITab { Section: tab_tab_5_Sections; } interface tab_tab_6 extends DevKit.Controls.ITab { Section: tab_tab_6_Sections; } interface tab_tab_7 extends DevKit.Controls.ITab { Section: tab_tab_7_Sections; } interface tab_tab_8 extends DevKit.Controls.ITab { Section: tab_tab_8_Sections; } interface Tabs { _B8E326EE_5C21_4A18_BA55_E3B56966C249: tab__B8E326EE_5C21_4A18_BA55_E3B56966C249; DeviceInsightsTab: tab_DeviceInsightsTab; f1tab_additionalsettings: tab_f1tab_additionalsettings; f1tab_mainsettings: tab_f1tab_mainsettings; f1tab_record_log: tab_f1tab_record_log; KnowledgeArticlesTab: tab_KnowledgeArticlesTab; tab_5: tab_tab_5; tab_6: tab_tab_6; tab_7: tab_tab_7; tab_8: tab_tab_8; } interface Body { Tab: Tabs; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.Controls.Lookup; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn: DevKit.Controls.DateTime; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.Controls.Lookup; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn: DevKit.Controls.DateTime; msdyn_Address1: DevKit.Controls.String; msdyn_Address1_1: DevKit.Controls.String; msdyn_Address2: DevKit.Controls.String; msdyn_Address3: DevKit.Controls.String; msdyn_AddressName: DevKit.Controls.String; /** Shows the agreement linked to this work order. */ msdyn_Agreement: DevKit.Controls.Lookup; /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; msdyn_City: DevKit.Controls.String; /** The user that last closed this work order */ msdyn_ClosedBy: DevKit.Controls.Lookup; /** When Bookings are used on a Work Order, this field is auto-populated based on the latest End Time from the related Bookings. Otherwise, this field is populated based on the change of System Status. */ msdyn_completedon: DevKit.Controls.DateTime; msdyn_Country: DevKit.Controls.String; /** Customer Asset related to this incident reported */ msdyn_CustomerAsset: DevKit.Controls.Lookup; msdyn_DateWindowEnd: DevKit.Controls.Date; msdyn_DateWindowStart: DevKit.Controls.Date; /** Enter the summary of total estimated billing amount for this work order */ msdyn_EstimateSubtotalAmount: DevKit.Controls.Money; /** When Bookings are used on a Work Order, this field is auto-populated based on the earliest Actual Arrival Time from the related Bookings. */ msdyn_firstarrivedon: DevKit.Controls.DateTime; /** Workorder's functional location */ msdyn_FunctionalLocation: DevKit.Controls.Lookup; /** Shows instructions for booked resources. By default, this information is taken from the work order instructions field on the service account. */ msdyn_Instructions: DevKit.Controls.String; /** The iot alert which initiated this work order. */ msdyn_IoTAlert: DevKit.Controls.Lookup; /** The iot alert which initiated this work order. */ msdyn_IoTAlert_1: DevKit.Controls.Lookup; msdyn_Latitude: DevKit.Controls.Double; msdyn_Latitude_1: DevKit.Controls.Double; msdyn_Longitude: DevKit.Controls.Double; msdyn_Longitude_1: DevKit.Controls.Double; msdyn_mapcontrol: DevKit.Controls.String; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Unique identifier for Opportunity associated with Work Order. */ msdyn_OpportunityId: DevKit.Controls.Lookup; /** Unique identifier for Work Order associated with Work Order. */ msdyn_ParentWorkOrder: DevKit.Controls.Lookup; msdyn_PostalCode: DevKit.Controls.String; /** Price List that controls pricing for products / services added to this work order. By default the system will use the Price List specified on the account */ msdyn_PriceList: DevKit.Controls.Lookup; /** Incident description */ msdyn_PrimaryIncidentDescription: DevKit.Controls.String; /** Shows the time estimated to resolve this incident. */ msdyn_PrimaryIncidentEstimatedDuration: DevKit.Controls.Integer; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; msdyn_PrimaryResolution: DevKit.Controls.Lookup; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.Controls.Lookup; /** The contact that reported this Work Order */ msdyn_ReportedByContact: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Case of which this work order originates from */ msdyn_ServiceRequest: DevKit.Controls.Lookup; /** The service territory this work order relates to. By default this will be set to the Service Territory defined on the service account */ msdyn_ServiceTerritory: DevKit.Controls.Lookup; msdyn_StateOrProvince: DevKit.Controls.String; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Enter the summary of subtotal billing amount excluding tax for this work order. */ msdyn_SubtotalAmount: DevKit.Controls.Money; /** A support contact can be specified so that the individual working on the work order has someone to contact for assistance. */ msdyn_SupportContact: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Shows whether sales tax is to be charged for this work order. */ msdyn_Taxable: DevKit.Controls.Boolean; /** Tax Code to be used to calculate tax when Work Order is taxable. By default the system will use the tax code specified on the service account */ msdyn_TaxCode: DevKit.Controls.Lookup; /** Enter the time this work order was last closed. */ msdyn_TimeClosed: DevKit.Controls.DateTime; /** Enter the starting range of the time promised to the account that incidents will be resolved. */ msdyn_TimeFromPromised: DevKit.Controls.DateTime; msdyn_TimeGroup: DevKit.Controls.Lookup; /** Enter the ending range of the time promised to the account that incidents will be resolved. */ msdyn_TimeToPromised: DevKit.Controls.DateTime; msdyn_TimeWindowEnd: DevKit.Controls.DateTime; msdyn_TimeWindowStart: DevKit.Controls.DateTime; /** Enter the summary of total billing amount for this work order. */ msdyn_TotalAmount: DevKit.Controls.Money; /** Calculated from the estimated duration of Work Order Incidents and Work Order Service Tasks not related to a Work Order Incident on the Work Order. Intended to be read-only. */ msdyn_totalestimatedduration: DevKit.Controls.Integer; /** Enter the summary of total sales tax charged for this work order. */ msdyn_TotalSalesTax: DevKit.Controls.Money; /** The working hours for a requirement. */ msdyn_workhourtemplate: DevKit.Controls.Lookup; msdyn_WorkLocation: DevKit.Controls.OptionSet; /** Type a summary description of the job. */ msdyn_WorkOrderSummary: DevKit.Controls.String; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; WebResource_msdyn_timewindowend: DevKit.Controls.WebResource; WebResource_msdyn_timewindowstart: DevKit.Controls.WebResource; } interface Footer extends DevKit.Controls.IFooter { /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_workorder_bookableresourcebooking_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_invoicedetail: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_agreementbookingdate_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_inventoryjournal_AllocatedToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_payment_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_paymentdetail_Workorder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorder_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderreceiptproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rma_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtv_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtvproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorder_ParentWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workordercharacteristic_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderincident_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderresolution_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderresourcerestriction_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservice_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservicetask_WorkOrder: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem, navDocument: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface quickForm_service_account_details_Body { Address1_Telephone1: DevKit.Controls.QuickView; EMailAddress1: DevKit.Controls.QuickView; PrimaryContactId: DevKit.Controls.QuickView; } interface quickForm_service_account_details extends DevKit.Controls.IQuickView { Body: quickForm_service_account_details_Body; } interface QuickForm { service_account_details: quickForm_service_account_details; } interface ProcessWork_Order_Business_Process { /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Tracks the current system status. */ msdyn_SystemStatus_1: DevKit.Controls.OptionSet; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Work_Order_Business_Process: ProcessWork_Order_Business_Process; } interface Grid { Incidents_List: DevKit.Controls.Grid; bookings: DevKit.Controls.Grid; workorderproductsgrid: DevKit.Controls.Grid; workorderservicesgrid: DevKit.Controls.Grid; workorderservicetasksgrid: DevKit.Controls.Grid; KnowledgeArticleSubGrid: DevKit.Controls.Grid; } } class FormWork_Order extends DevKit.IForm { /** * DynamicsCrm.DevKit form Work_Order * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Work_Order */ Body: DevKit.FormWork_Order.Body; /** The Footer section of form Work_Order */ Footer: DevKit.FormWork_Order.Footer; /** The Navigation of form Work_Order */ Navigation: DevKit.FormWork_Order.Navigation; /** The QuickForm of form Work_Order */ QuickForm: DevKit.FormWork_Order.QuickForm; /** The Process of form Work_Order */ Process: DevKit.FormWork_Order.Process; /** The Grid of form Work_Order */ Grid: DevKit.FormWork_Order.Grid; } namespace FormWork_Order_Customer { interface tab_fstab_customer_Sections { fstab_customer_section_address: DevKit.Controls.Section; fstab_customer_section_map: DevKit.Controls.Section; } interface tab_fstab_fieldservice_Sections { fstab_fieldservice_section_general: DevKit.Controls.Section; fstab_fieldservice_section_others: DevKit.Controls.Section; } interface tab_fstab_customer extends DevKit.Controls.ITab { Section: tab_fstab_customer_Sections; } interface tab_fstab_fieldservice extends DevKit.Controls.ITab { Section: tab_fstab_fieldservice_Sections; } interface Tabs { fstab_customer: tab_fstab_customer; fstab_fieldservice: tab_fstab_fieldservice; } interface Body { Tab: Tabs; msdyn_Address1: DevKit.Controls.String; msdyn_Address2: DevKit.Controls.String; /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; msdyn_City: DevKit.Controls.String; msdyn_Country: DevKit.Controls.String; /** Workorder's functional location */ msdyn_FunctionalLocation: DevKit.Controls.Lookup; /** For internal use only. */ msdyn_InternalFlags: DevKit.Controls.String; msdyn_Latitude: DevKit.Controls.Double; msdyn_Longitude: DevKit.Controls.Double; msdyn_mapcontrol: DevKit.Controls.String; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; msdyn_PostalCode: DevKit.Controls.String; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; msdyn_StateOrProvince: DevKit.Controls.String; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_workorder_bookableresourcebooking_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_invoicedetail: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_agreementbookingdate_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_inventoryjournal_AllocatedToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_payment_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_paymentdetail_Workorder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorder_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderreceiptproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rma_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtv_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtvproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorder_ParentWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workordercharacteristic_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderincident_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderresourcerestriction_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservice_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservicetask_WorkOrder: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem, navDocument: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface ProcessWork_Order_Business_Process { /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Tracks the current system status. */ msdyn_SystemStatus_1: DevKit.Controls.OptionSet; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Work_Order_Business_Process: ProcessWork_Order_Business_Process; } } class FormWork_Order_Customer extends DevKit.IForm { /** * DynamicsCrm.DevKit form Work_Order_Customer * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Work_Order_Customer */ Body: DevKit.FormWork_Order_Customer.Body; /** The Navigation of form Work_Order_Customer */ Navigation: DevKit.FormWork_Order_Customer.Navigation; /** The Process of form Work_Order_Customer */ Process: DevKit.FormWork_Order_Customer.Process; } namespace FormWork_Order_Mobile { interface Header extends DevKit.Controls.IHeader { /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; } interface tab__B8E326EE_5C21_4A18_BA55_E3B56966C249_Sections { _B8E326EE_5C21_4A18_BA55_E3B56966C249_COLUMN_2_SECTION_1: DevKit.Controls.Section; _B8E326EE_5C21_4A18_BA55_E3B56966C249_SECTION_9: DevKit.Controls.Section; fstab_other_section_misc: DevKit.Controls.Section; fstab_other_section_total: DevKit.Controls.Section; fstab_sub_grids_section: DevKit.Controls.Section; fstab_summary_section_address: DevKit.Controls.Section; fstab_summary_section_general: DevKit.Controls.Section; fstab_summary_section_primary_incident: DevKit.Controls.Section; fstab_summary_section_sales_tax: DevKit.Controls.Section; } interface tab_tab_8_Sections { tab_8_section_2: DevKit.Controls.Section; } interface tab__B8E326EE_5C21_4A18_BA55_E3B56966C249 extends DevKit.Controls.ITab { Section: tab__B8E326EE_5C21_4A18_BA55_E3B56966C249_Sections; } interface tab_tab_8 extends DevKit.Controls.ITab { Section: tab_tab_8_Sections; } interface Tabs { _B8E326EE_5C21_4A18_BA55_E3B56966C249: tab__B8E326EE_5C21_4A18_BA55_E3B56966C249; tab_8: tab_tab_8; } interface Body { Tab: Tabs; msdyn_Address1: DevKit.Controls.String; msdyn_Address1_1: DevKit.Controls.String; msdyn_Address2: DevKit.Controls.String; msdyn_Address3: DevKit.Controls.String; /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; msdyn_City: DevKit.Controls.String; msdyn_Country: DevKit.Controls.String; /** Customer Asset related to this incident reported */ msdyn_CustomerAsset: DevKit.Controls.Lookup; /** Enter the summary of total estimated billing amount for this work order */ msdyn_EstimateSubtotalAmount: DevKit.Controls.Money; /** Workorder's functional location */ msdyn_FunctionalLocation: DevKit.Controls.Lookup; /** Shows instructions for booked resources. By default, this information is taken from the work order instructions field on the service account. */ msdyn_Instructions: DevKit.Controls.String; /** For internal use only. */ msdyn_InternalFlags: DevKit.Controls.String; /** The iot alert which initiated this work order. */ msdyn_IoTAlert: DevKit.Controls.Lookup; msdyn_Latitude: DevKit.Controls.Double; msdyn_Latitude_1: DevKit.Controls.Double; msdyn_Longitude: DevKit.Controls.Double; msdyn_Longitude_1: DevKit.Controls.Double; msdyn_mapcontrol: DevKit.Controls.String; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; msdyn_PostalCode: DevKit.Controls.String; /** Price List that controls pricing for products / services added to this work order. By default the system will use the Price List specified on the account */ msdyn_PriceList: DevKit.Controls.Lookup; /** Incident description */ msdyn_PrimaryIncidentDescription: DevKit.Controls.String; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; msdyn_PrimaryResolution: DevKit.Controls.Lookup; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.Controls.Lookup; /** The contact that reported this Work Order */ msdyn_ReportedByContact: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** The service territory this work order relates to. By default this will be set to the Service Territory defined on the service account */ msdyn_ServiceTerritory: DevKit.Controls.Lookup; msdyn_StateOrProvince: DevKit.Controls.String; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Enter the summary of subtotal billing amount excluding tax for this work order. */ msdyn_SubtotalAmount: DevKit.Controls.Money; /** A support contact can be specified so that the individual working on the work order has someone to contact for assistance. */ msdyn_SupportContact: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Shows whether sales tax is to be charged for this work order. */ msdyn_Taxable: DevKit.Controls.Boolean; /** Tax Code to be used to calculate tax when Work Order is taxable. By default the system will use the tax code specified on the service account */ msdyn_TaxCode: DevKit.Controls.Lookup; /** Enter the starting range of the time promised to the account that incidents will be resolved. */ msdyn_TimeFromPromised: DevKit.Controls.DateTime; /** Enter the ending range of the time promised to the account that incidents will be resolved. */ msdyn_TimeToPromised: DevKit.Controls.DateTime; /** Enter the summary of total billing amount for this work order. */ msdyn_TotalAmount: DevKit.Controls.Money; /** Enter the summary of total sales tax charged for this work order. */ msdyn_TotalSalesTax: DevKit.Controls.Money; /** Type a summary description of the job. */ msdyn_WorkOrderSummary: DevKit.Controls.String; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_workorder_bookableresourcebooking_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_invoicedetail: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_agreementbookingdate_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_inventoryjournal_AllocatedToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_payment_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_paymentdetail_Workorder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorder_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderreceiptproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rma_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtv_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtvproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorder_ParentWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workordercharacteristic_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderincident_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderresourcerestriction_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservice_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservicetask_WorkOrder: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem, navDocument: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface ProcessWork_Order_Business_Process { /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Tracks the current system status. */ msdyn_SystemStatus_1: DevKit.Controls.OptionSet; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Work_Order_Business_Process: ProcessWork_Order_Business_Process; } interface Grid { workorderproductsgrid: DevKit.Controls.Grid; workorderservicesgrid: DevKit.Controls.Grid; workorderservicetasksgrid: DevKit.Controls.Grid; Incidents_List: DevKit.Controls.Grid; bookings: DevKit.Controls.Grid; KnowledgeArticlesSubGrid: DevKit.Controls.Grid; } } class FormWork_Order_Mobile extends DevKit.IForm { /** * DynamicsCrm.DevKit form Work_Order_Mobile * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Work_Order_Mobile */ Body: DevKit.FormWork_Order_Mobile.Body; /** The Header section of form Work_Order_Mobile */ Header: DevKit.FormWork_Order_Mobile.Header; /** The Navigation of form Work_Order_Mobile */ Navigation: DevKit.FormWork_Order_Mobile.Navigation; /** The Process of form Work_Order_Mobile */ Process: DevKit.FormWork_Order_Mobile.Process; /** The Grid of form Work_Order_Mobile */ Grid: DevKit.FormWork_Order_Mobile.Grid; } namespace FormWork_Order_Notes { interface tab_fstab_fieldservice_Sections { fstab_fieldservice_section_general: DevKit.Controls.Section; fstab_fieldservice_section_others: DevKit.Controls.Section; } interface tab_fstab_notes_Sections { fstab_notes_section_details: DevKit.Controls.Section; fstab_notes_section_summary: DevKit.Controls.Section; } interface tab_fstab_fieldservice extends DevKit.Controls.ITab { Section: tab_fstab_fieldservice_Sections; } interface tab_fstab_notes extends DevKit.Controls.ITab { Section: tab_fstab_notes_Sections; } interface Tabs { fstab_fieldservice: tab_fstab_fieldservice; fstab_notes: tab_fstab_notes; } interface Body { Tab: Tabs; /** For internal use only. */ msdyn_InternalFlags: DevKit.Controls.String; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Type a summary description of the job. */ msdyn_WorkOrderSummary: DevKit.Controls.String; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_workorder_bookableresourcebooking_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_invoicedetail: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_agreementbookingdate_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_inventoryjournal_AllocatedToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_payment_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_paymentdetail_Workorder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorder_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderreceiptproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rma_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtv_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtvproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorder_ParentWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workordercharacteristic_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderincident_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderresourcerestriction_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservice_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservicetask_WorkOrder: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem, navDocument: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface ProcessWork_Order_Business_Process { /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Tracks the current system status. */ msdyn_SystemStatus_1: DevKit.Controls.OptionSet; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Work_Order_Business_Process: ProcessWork_Order_Business_Process; } } class FormWork_Order_Notes extends DevKit.IForm { /** * DynamicsCrm.DevKit form Work_Order_Notes * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Work_Order_Notes */ Body: DevKit.FormWork_Order_Notes.Body; /** The Navigation of form Work_Order_Notes */ Navigation: DevKit.FormWork_Order_Notes.Navigation; /** The Process of form Work_Order_Notes */ Process: DevKit.FormWork_Order_Notes.Process; } namespace FormWork_Order_Service { interface tab_fstab_fieldservice_Sections { fstab_fieldservice_section_general: DevKit.Controls.Section; fstab_fieldservice_section_others: DevKit.Controls.Section; } interface tab_fstab_service_Sections { fstab_service_section_subgrids: DevKit.Controls.Section; fstab_service_section_summary: DevKit.Controls.Section; } interface tab_fstab_fieldservice extends DevKit.Controls.ITab { Section: tab_fstab_fieldservice_Sections; } interface tab_fstab_service extends DevKit.Controls.ITab { Section: tab_fstab_service_Sections; } interface Tabs { fstab_fieldservice: tab_fstab_fieldservice; fstab_service: tab_fstab_service; } interface Body { Tab: Tabs; /** Customer Asset related to this incident reported */ msdyn_CustomerAsset: DevKit.Controls.Lookup; /** Enter the summary of total estimated billing amount for this work order */ msdyn_EstimateSubtotalAmount: DevKit.Controls.Money; /** Shows instructions for booked resources. By default, this information is taken from the work order instructions field on the service account. */ msdyn_Instructions: DevKit.Controls.String; /** For internal use only. */ msdyn_InternalFlags: DevKit.Controls.String; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Incident description */ msdyn_PrimaryIncidentDescription: DevKit.Controls.String; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; msdyn_PrimaryResolution: DevKit.Controls.Lookup; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Enter the summary of subtotal billing amount excluding tax for this work order. */ msdyn_SubtotalAmount: DevKit.Controls.Money; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Enter the summary of total billing amount for this work order. */ msdyn_TotalAmount: DevKit.Controls.Money; /** Enter the summary of total sales tax charged for this work order. */ msdyn_TotalSalesTax: DevKit.Controls.Money; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_workorder_bookableresourcebooking_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_invoicedetail: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_agreementbookingdate_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_inventoryjournal_AllocatedToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_payment_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_paymentdetail_Workorder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorder_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderreceiptproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rma_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtv_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtvproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorder_ParentWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workordercharacteristic_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderincident_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderresourcerestriction_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservice_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservicetask_WorkOrder: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem, navDocument: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface ProcessWork_Order_Business_Process { /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Tracks the current system status. */ msdyn_SystemStatus_1: DevKit.Controls.OptionSet; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Work_Order_Business_Process: ProcessWork_Order_Business_Process; } interface Grid { FsWorkOrderServiceTasksGrid: DevKit.Controls.Grid; FsWorkOrderProductsGrid: DevKit.Controls.Grid; FsWorkOrderServicesGrid: DevKit.Controls.Grid; FsWorkOrderIncidentsGrid: DevKit.Controls.Grid; FsWorkOrderResolutionsGrid: DevKit.Controls.Grid; workorder_KASubgrid: DevKit.Controls.Grid; } } class FormWork_Order_Service extends DevKit.IForm { /** * DynamicsCrm.DevKit form Work_Order_Service * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Work_Order_Service */ Body: DevKit.FormWork_Order_Service.Body; /** The Navigation of form Work_Order_Service */ Navigation: DevKit.FormWork_Order_Service.Navigation; /** The Process of form Work_Order_Service */ Process: DevKit.FormWork_Order_Service.Process; /** The Grid of form Work_Order_Service */ Grid: DevKit.FormWork_Order_Service.Grid; } namespace FormWork_Order_Create { interface tab_maintab_Sections { _B14F3E67_E51B_4B3E_BB7F_A9CF0CF8DC17: DevKit.Controls.Section; } interface tab_maintab extends DevKit.Controls.ITab { Section: tab_maintab_Sections; } interface Tabs { maintab: tab_maintab; } interface Body { Tab: Tabs; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Price List that controls pricing for products / services added to this work order. By default the system will use the Price List specified on the account */ msdyn_PriceList: DevKit.Controls.Lookup; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Shows whether sales tax is to be charged for this work order. */ msdyn_Taxable: DevKit.Controls.Boolean; /** Tax Code to be used to calculate tax when Work Order is taxable. By default the system will use the tax code specified on the service account */ msdyn_TaxCode: DevKit.Controls.Lookup; /** Type a summary description of the job. */ msdyn_WorkOrderSummary: DevKit.Controls.String; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; product: DevKit.Controls.ActionCards; service: DevKit.Controls.ActionCards; servicetask: DevKit.Controls.ActionCards; } interface Navigation { nav_bpf_msdyn_workorder_msdyn_bpf_989e9b1857e24af18787d5143b67523b: DevKit.Controls.NavigationItem, nav_bpf_msdyn_workorder_msdyn_bpf_d3d97bac8c294105840e99e37a9d1c39: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_bookableresourcebooking_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_invoicedetail: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_actual_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_agreementbookingdate_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_inventoryjournal_AllocatedToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_payment_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_paymentdetail_Workorder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorder_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_purchaseorderreceiptproduct_AssociateToWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_requirementcharacteristic_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_requirementresourcepreference_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_resourcerequirement_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rma_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtv_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_rtvproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorder_ParentWorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workordercharacteristic_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderincident_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderproduct_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderresourcerestriction_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservice_WorkOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorder_msdyn_workorderservicetask_WorkOrder: DevKit.Controls.NavigationItem, navAsyncOperations: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navConnections: DevKit.Controls.NavigationItem, navDocument: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem, navSPDocuments: DevKit.Controls.NavigationItem } interface ProcessWork_Order_Business_Process { /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Tracks the current system status. */ msdyn_SystemStatus_1: DevKit.Controls.OptionSet; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Work_Order_Business_Process: ProcessWork_Order_Business_Process; } } class FormWork_Order_Create extends DevKit.IForm { /** * DynamicsCrm.DevKit form Work_Order_Create * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Work_Order_Create */ Body: DevKit.FormWork_Order_Create.Body; /** The Navigation of form Work_Order_Create */ Navigation: DevKit.FormWork_Order_Create.Navigation; /** The Process of form Work_Order_Create */ Process: DevKit.FormWork_Order_Create.Process; } namespace FormQuick_Create_Work_Order { interface tab_tab_1_Sections { tab_1_column_1_section_1: DevKit.Controls.Section; tab_1_column_2_section_1: DevKit.Controls.Section; tab_1_column_3_section_1: DevKit.Controls.Section; } interface tab_tab_1 extends DevKit.Controls.ITab { Section: tab_tab_1_Sections; } interface Tabs { tab_1: tab_tab_1; } interface Body { Tab: Tabs; /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.Controls.Lookup; /** Customer Asset related to this incident reported */ msdyn_CustomerAsset: DevKit.Controls.Lookup; /** The iot alert which initiated this work order. */ msdyn_IoTAlert: DevKit.Controls.Lookup; /** Unique identifier for Opportunity associated with Work Order. */ msdyn_OpportunityId: DevKit.Controls.Lookup; /** Price List that controls pricing for products / services added to this work order. By default the system will use the Price List specified on the account */ msdyn_PriceList: DevKit.Controls.Lookup; /** Incident description */ msdyn_PrimaryIncidentDescription: DevKit.Controls.String; /** Shows the time estimated to resolve this incident. */ msdyn_PrimaryIncidentEstimatedDuration: DevKit.Controls.Integer; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.Controls.Lookup; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.Controls.Lookup; /** The contact that reported this Work Order */ msdyn_ReportedByContact: DevKit.Controls.Lookup; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.Controls.Lookup; /** Case of which this work order originates from */ msdyn_ServiceRequest: DevKit.Controls.Lookup; /** The service territory this work order relates to. By default this will be set to the Service Territory defined on the service account */ msdyn_ServiceTerritory: DevKit.Controls.Lookup; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Type a summary description of the job. */ msdyn_WorkOrderSummary: DevKit.Controls.String; /** Work Order Type */ msdyn_WorkOrderType: DevKit.Controls.Lookup; } } class FormQuick_Create_Work_Order extends DevKit.IForm { /** * DynamicsCrm.DevKit form Quick_Create_Work_Order * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Quick_Create_Work_Order */ Body: DevKit.FormQuick_Create_Work_Order.Body; } class msdyn_workorderApi { /** * DynamicsCrm.DevKit msdyn_workorderApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows the exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; msdyn_Address1: DevKit.WebApi.StringValue; msdyn_Address2: DevKit.WebApi.StringValue; msdyn_Address3: DevKit.WebApi.StringValue; msdyn_AddressName: DevKit.WebApi.StringValue; /** Shows the agreement linked to this work order. */ msdyn_Agreement: DevKit.WebApi.LookupValue; /** Internal field used to generate the next name upon entity creation. It is optionally copied to the msdyn_name field. */ msdyn_AutoNumbering: DevKit.WebApi.StringValue; /** Account to be billed. If a billing account has been set on service account it will be populated by default. Otherwise, the billing account will be the same as the service account. */ msdyn_BillingAccount: DevKit.WebApi.LookupValue; /** For internal use only. */ msdyn_BookingSummary: DevKit.WebApi.StringValue; msdyn_ChildIndex: DevKit.WebApi.IntegerValue; msdyn_City: DevKit.WebApi.StringValue; /** The user that last closed this work order */ msdyn_ClosedBy: DevKit.WebApi.LookupValue; /** When Bookings are used on a Work Order, this field is auto-populated based on the latest End Time from the related Bookings. Otherwise, this field is populated based on the change of System Status. */ msdyn_completedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; msdyn_Country: DevKit.WebApi.StringValue; /** Customer Asset related to this incident reported */ msdyn_CustomerAsset: DevKit.WebApi.LookupValue; msdyn_DateWindowEnd_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; msdyn_DateWindowStart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the summary of total estimated billing amount for this work order */ msdyn_EstimateSubtotalAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the estimate subtotal amount in the base currency. */ msdyn_estimatesubtotalamount_Base: DevKit.WebApi.MoneyValueReadonly; /** When Bookings are used on a Work Order, this field is auto-populated based on the earliest Actual Arrival Time from the related Bookings. */ msdyn_firstarrivedon_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Indicate the details of the follow up work */ msdyn_FollowUpNote: DevKit.WebApi.StringValue; /** Allows indication if follow up work is required for a work order. */ msdyn_FollowUpRequired: DevKit.WebApi.BooleanValue; /** Workorder's functional location */ msdyn_FunctionalLocation: DevKit.WebApi.LookupValue; /** Shows instructions for booked resources. By default, this information is taken from the work order instructions field on the service account. */ msdyn_Instructions: DevKit.WebApi.StringValue; /** For internal use only. */ msdyn_InternalFlags: DevKit.WebApi.StringValue; /** The iot alert which initiated this work order. */ msdyn_IoTAlert: DevKit.WebApi.LookupValue; msdyn_IsFollowUp: DevKit.WebApi.BooleanValue; msdyn_IsMobile: DevKit.WebApi.BooleanValue; msdyn_Latitude: DevKit.WebApi.DoubleValue; msdyn_Longitude: DevKit.WebApi.DoubleValue; msdyn_mapcontrol: DevKit.WebApi.StringValueReadonly; /** Enter the name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; /** Unique identifier for Opportunity associated with Work Order. */ msdyn_OpportunityId: DevKit.WebApi.LookupValue; /** Unique identifier for Work Order associated with Work Order. */ msdyn_ParentWorkOrder: DevKit.WebApi.LookupValue; msdyn_PostalCode: DevKit.WebApi.StringValue; /** The customer Preferred Resource to work on this job. Should be taken into consideration while scheduling resources */ msdyn_PreferredResource: DevKit.WebApi.LookupValue; /** Price List that controls pricing for products / services added to this work order. By default the system will use the Price List specified on the account */ msdyn_PriceList: DevKit.WebApi.LookupValue; /** Incident description */ msdyn_PrimaryIncidentDescription: DevKit.WebApi.StringValue; /** Shows the time estimated to resolve this incident. */ msdyn_PrimaryIncidentEstimatedDuration: DevKit.WebApi.IntegerValue; /** Primary incident type reported */ msdyn_PrimaryIncidentType: DevKit.WebApi.LookupValue; msdyn_PrimaryResolution: DevKit.WebApi.LookupValue; /** Priority of the Work Order. To be taken into consideration while scheduling resources */ msdyn_Priority: DevKit.WebApi.LookupValue; /** The contact that reported this Work Order */ msdyn_ReportedByContact: DevKit.WebApi.LookupValue; /** Account to be serviced */ msdyn_ServiceAccount: DevKit.WebApi.LookupValue; /** Case of which this work order originates from */ msdyn_ServiceRequest: DevKit.WebApi.LookupValue; /** The service territory this work order relates to. By default this will be set to the Service Territory defined on the service account */ msdyn_ServiceTerritory: DevKit.WebApi.LookupValue; msdyn_StateOrProvince: DevKit.WebApi.StringValue; /** Work Order subsstatus */ msdyn_SubStatus: DevKit.WebApi.LookupValue; /** Enter the summary of subtotal billing amount excluding tax for this work order. */ msdyn_SubtotalAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the subtotal amount in the base currency. */ msdyn_subtotalamount_Base: DevKit.WebApi.MoneyValueReadonly; /** A support contact can be specified so that the individual working on the work order has someone to contact for assistance. */ msdyn_SupportContact: DevKit.WebApi.LookupValue; /** Tracks the current system status. */ msdyn_SystemStatus: DevKit.WebApi.OptionSetValue; /** Shows whether sales tax is to be charged for this work order. */ msdyn_Taxable: DevKit.WebApi.BooleanValue; /** Tax Code to be used to calculate tax when Work Order is taxable. By default the system will use the tax code specified on the service account */ msdyn_TaxCode: DevKit.WebApi.LookupValue; /** Enter the time this work order was last closed. */ msdyn_TimeClosed_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Enter the starting range of the time promised to the account that incidents will be resolved. */ msdyn_TimeFromPromised_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; msdyn_TimeGroup: DevKit.WebApi.LookupValue; msdyn_TimeGroupDetailSelected: DevKit.WebApi.LookupValue; /** Enter the ending range of the time promised to the account that incidents will be resolved. */ msdyn_TimeToPromised_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; msdyn_TimeWindowEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; msdyn_TimeWindowStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Enter the summary of total billing amount for this work order. */ msdyn_TotalAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the total amount in the base currency. */ msdyn_totalamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Calculated from the estimated duration of Work Order Incidents and Work Order Service Tasks not related to a Work Order Incident on the Work Order. Intended to be read-only. */ msdyn_totalestimatedduration: DevKit.WebApi.IntegerValue; /** Enter the summary of total sales tax charged for this work order. */ msdyn_TotalSalesTax: DevKit.WebApi.MoneyValue; /** Shows the value of the total sales tax in the base currency. */ msdyn_totalsalestax_Base: DevKit.WebApi.MoneyValueReadonly; /** The working hours for a requirement. */ msdyn_workhourtemplate: DevKit.WebApi.LookupValue; msdyn_WorkLocation: DevKit.WebApi.OptionSetValue; /** For internal use only. */ msdyn_workorderarrivaltimekpiid: DevKit.WebApi.LookupValue; /** Shows the entity instances. */ msdyn_workorderId: DevKit.WebApi.GuidValue; /** For internal use only. */ msdyn_workorderresolutionkpiid: DevKit.WebApi.LookupValue; /** Type a summary description of the job. */ msdyn_WorkOrderSummary: DevKit.WebApi.StringValue; /** Work Order Type */ msdyn_WorkOrderType: DevKit.WebApi.LookupValue; /** Shows the date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Shows the ID of the process associated with the entity. */ processid: DevKit.WebApi.GuidValue; /** Shows the ID of the stage where the entity is located. */ stageid: DevKit.WebApi.GuidValue; /** Status of the Work Order */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Work Order */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Shows a comma-separated list of string values representing the unique identifiers of stages in a business process flow instance in the order that they occur. */ traversedpath: DevKit.WebApi.StringValue; /** Shows the time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_workorder { enum msdyn_SystemStatus { /** 690970005 */ Closed_Canceled, /** 690970004 */ Closed_Posted, /** 690970003 */ Open_Completed, /** 690970002 */ Open_In_Progress, /** 690970001 */ Open_Scheduled, /** 690970000 */ Open_Unscheduled } enum msdyn_WorkLocation { /** 690970001 */ Facility, /** 690970002 */ Location_Agnostic, /** 690970000 */ Onsite } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Quick Create Work Order','Work Order','Work Order - Customer','Work Order - Mobile','Work Order - Notes','Work Order - Service','Work Order Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Kind } from "graphql/language" import { rangeFactory } from "../" describe(`rangeFactory`, () => { const NOT_FINITE = /Value is not a finite number:/ const NOT_NUMBER = /Value is not a number:/ const NOT_INTEGER = /Value is not an integer:/ const OUTSIDE_RANGE = /Value is (less|greater) than limit: [0-9]+/ const CANNOT_VALIDATE = /Can only validate (Floats|Integers) but got a:/ const { scalar: ExampleRangeScalar, resolver: ExampleRange } = rangeFactory({ name: `ExampleRange`, start: 1, end: 5 }) describe(`scalar`, () => { it(`exports scalar`, () => { expect(ExampleRangeScalar).toBe(`scalar ExampleRange`) }) }) describe(`valid:integer`, () => { describe(`as int`, () => { it(`serialize`, () => { expect(ExampleRange.serialize(3)).toBe(3) }) it(`parseValue`, () => { expect(ExampleRange.parseValue(3)).toBe(3) }) it(`parseLiteral`, () => { expect( // @ts-ignore ExampleRange.parseLiteral({ value: 3, kind: Kind.INT }, {}) ).toBe(3) }) }) describe(`as string`, () => { it(`serialize`, () => { expect(ExampleRange.serialize(`3`)).toBe(3) }) it(`parseValue`, () => { expect(ExampleRange.parseValue(`3`)).toBe(3) }) it(`parseLiteral`, () => { expect( ExampleRange.parseLiteral({ value: `3`, kind: Kind.INT }, {}) ).toBe(3) }) }) }) describe(`invalid:integer`, () => { describe(`float`, () => { describe(`as float`, () => { it(`serialize`, () => { expect(() => ExampleRange.serialize(3.45)).toThrow( NOT_INTEGER ) }) it(`parseValue`, () => { expect(() => ExampleRange.parseValue(3.45)).toThrow( NOT_INTEGER ) }) it(`parseLiteral`, () => { expect(() => // @ts-ignore ExampleRange.parseLiteral({ value: 3.45, kind: Kind.FLOAT }, {}) ).toThrow(CANNOT_VALIDATE) }) }) describe(`as string`, () => { it(`serialize`, () => { expect(() => ExampleRange.serialize(`3.45`)).toThrow( NOT_INTEGER ) }) it(`parseValue`, () => { expect(() => ExampleRange.parseValue(`3.45`)).toThrow( NOT_INTEGER ) }) it(`parseLiteral`, () => { expect(() => ExampleRange.parseLiteral({ value: `3.45`, kind: Kind.FLOAT }, {}) ).toThrow(CANNOT_VALIDATE) }) }) }) describe(`null`, () => { it(`serialize`, () => { expect(() => ExampleRange.serialize(null)).toThrow(NOT_NUMBER) }) it(`parseValue`, () => { expect(() => ExampleRange.parseValue(null)).toThrow(NOT_NUMBER) }) it(`parseLiteral`, () => { expect(() => ExampleRange.parseLiteral({ value: null, kind: Kind.INT }, {}) ).toThrow(NOT_NUMBER) }) }) describe(`undefined`, () => { it(`serialize`, () => { // @ts-ignore expect(() => ExampleRange.serialize()).toThrow(NOT_NUMBER) // eslint-disable-line }) it(`parseValue`, () => { // @ts-ignore expect(() => ExampleRange.parseValue()).toThrow(NOT_NUMBER) }) it(`parseLiteral`, () => { // @ts-ignore expect(() => ExampleRange.parseLiteral({ kind: Kind.INT }, {})).toThrow( NOT_NUMBER ) }) }) describe(`unsafe integer`, () => { it(`serialize`, () => { expect(() => ExampleRange.serialize(2 ** 53)).toThrow( NOT_NUMBER ) }) it(`parseValue`, () => { expect(() => ExampleRange.parseValue(2 ** 53)).toThrow( NOT_NUMBER ) }) it(`parseLiteral`, () => { expect(() => // @ts-ignore ExampleRange.parseLiteral({ value: 2 ** 53, kind: Kind.INT }, {}) ).toThrow(NOT_NUMBER) }) }) describe(`outside range`, () => { describe(`as int`, () => { it(`serialize`, () => { expect(() => ExampleRange.serialize(6)).toThrow( OUTSIDE_RANGE ) }) it(`parseValue`, () => { expect(() => ExampleRange.parseValue(6)).toThrow( OUTSIDE_RANGE ) }) it(`parseLiteral`, () => { expect(() => // @ts-ignore ExampleRange.parseLiteral({ value: 6, kind: Kind.INT }, {}) ).toThrow(OUTSIDE_RANGE) }) }) describe(`as string`, () => { it(`serialize`, () => { expect(() => ExampleRange.serialize(`6`)).toThrow( OUTSIDE_RANGE ) }) it(`parseValue`, () => { expect(() => ExampleRange.parseValue(`6`)).toThrow( OUTSIDE_RANGE ) }) it(`parseLiteral`, () => { expect(() => ExampleRange.parseLiteral({ value: `6`, kind: Kind.INT }, {}) ).toThrow(OUTSIDE_RANGE) }) }) }) describe(`infinity`, () => { it(`serialize`, () => { expect(() => ExampleRange.serialize(Number.NEGATIVE_INFINITY)).toThrow( NOT_FINITE ) }) it(`parseValue`, () => { expect(() => ExampleRange.parseValue(Number.NEGATIVE_INFINITY)).toThrow( NOT_FINITE ) }) it(`parseLiteral`, () => { expect(() => ExampleRange.parseLiteral( { // @ts-ignore value: Number.NEGATIVE_INFINITY, kind: Kind.INT }, {} ) ).toThrow(NOT_FINITE) }) }) describe(`not a number`, () => { it(`serialize`, () => { expect(() => ExampleRange.serialize(`not a number`)).toThrow( NOT_NUMBER ) }) it(`parseValue`, () => { expect(() => ExampleRange.parseValue(`not a number`)).toThrow( NOT_NUMBER ) }) it(`parseLiteral`, () => { expect(() => ExampleRange.parseLiteral( { value: `not a number`, kind: Kind.STRING }, {} ) ).toThrow(CANNOT_VALIDATE) }) }) describe(`NaN`, () => { it(`serialize`, () => { expect(() => ExampleRange.serialize(Number.NaN)).toThrow( NOT_NUMBER ) }) it(`parseValue`, () => { expect(() => ExampleRange.parseValue(Number.NaN)).toThrow( NOT_NUMBER ) }) it(`parseLiteral`, () => { expect(() => // @ts-ignore ExampleRange.parseLiteral({ value: Number.NaN, kind: Kind.STRING }, {}) ).toThrow(CANNOT_VALIDATE) }) }) }) const { resolver: ExampleZeroStart } = rangeFactory({ name: `ExampleRange`, start: 0, end: 1 }) describe(`valid:allowsZero`, () => { describe(`as int`, () => { it(`serialize`, () => { expect(ExampleZeroStart.serialize(0)).toBe(0) }) it(`parseValue`, () => { expect(ExampleZeroStart.parseValue(0)).toBe(0) }) it(`parseLiteral`, () => { expect( // @ts-ignore ExampleZeroStart.parseLiteral({ value: 0, kind: Kind.INT }, {}) ).toBe(0) }) }) describe(`as string`, () => { it(`serialize`, () => { expect(ExampleZeroStart.serialize(`0`)).toBe(0) }) it(`parseValue`, () => { expect(ExampleZeroStart.parseValue(`0`)).toBe(0) }) it(`parseLiteral`, () => { expect( ExampleZeroStart.parseLiteral({ value: `0`, kind: Kind.INT }, {}) ).toBe(0) }) }) }) const { resolver: ExampleFloatRange } = rangeFactory({ name: `ExampleFloatRange`, start: 0.25, end: 5.5, float: true }) describe(`valid:float`, () => { describe(`as float`, () => { it(`serialize`, () => { expect(ExampleFloatRange.serialize(3.45)).toBe(3.45) }) it(`parseValue`, () => { expect(ExampleFloatRange.parseValue(3.45)).toBe(3.45) }) it(`parseLiteral`, () => { expect( // @ts-ignore ExampleFloatRange.parseLiteral({ value: 3.45, kind: Kind.FLOAT }, {}) ).toBe(3.45) }) }) describe(`as string`, () => { it(`serialize`, () => { expect(ExampleFloatRange.serialize(`3.45`)).toBe(3.45) }) it(`parseValue`, () => { expect(ExampleFloatRange.parseValue(`3.45`)).toBe(3.45) }) it(`parseLiteral`, () => { expect( ExampleFloatRange.parseLiteral({ value: `3.45`, kind: Kind.FLOAT }, {}) ).toBe(3.45) }) }) }) describe(`invalid:float`, () => { describe(`null`, () => { it(`serialize`, () => { expect(() => ExampleFloatRange.serialize(null)).toThrow( NOT_NUMBER ) }) it(`parseValue`, () => { expect(() => ExampleFloatRange.parseValue(null)).toThrow( NOT_NUMBER ) }) it(`parseLiteral`, () => { expect(() => ExampleFloatRange.parseLiteral({ value: null, kind: Kind.FLOAT }, {}) ).toThrow(NOT_NUMBER) }) }) describe(`undefined`, () => { it(`serialize`, () => { // @ts-ignore expect(() => ExampleFloatRange.serialize()).toThrow(NOT_NUMBER) }) it(`parseValue`, () => { // @ts-ignore expect(() => ExampleFloatRange.parseValue()).toThrow( NOT_NUMBER ) }) it(`parseLiteral`, () => { expect(() => ExampleFloatRange.parseLiteral( // @ts-ignore { kind: Kind.FLOAT }, {} ) ).toThrow(NOT_NUMBER) }) }) describe(`outside range`, () => { describe(`as float`, () => { it(`serialize`, () => { expect(() => ExampleFloatRange.serialize(0.123)).toThrow( OUTSIDE_RANGE ) }) it(`parseValue`, () => { expect(() => ExampleFloatRange.parseValue(0.123)).toThrow( OUTSIDE_RANGE ) }) it(`parseLiteral`, () => { expect(() => // @ts-ignore ExampleFloatRange.parseLiteral({ value: 0.123, kind: Kind.FLOAT }, {}) ).toThrow(OUTSIDE_RANGE) }) }) describe(`as string`, () => { it(`serialize`, () => { expect(() => ExampleFloatRange.serialize(`0.123`)).toThrow( OUTSIDE_RANGE ) }) it(`parseValue`, () => { expect(() => ExampleFloatRange.parseValue(`0.123`)).toThrow( OUTSIDE_RANGE ) }) it(`parseLiteral`, () => { expect(() => ExampleFloatRange.parseLiteral({ value: `0.123`, kind: Kind.FLOAT }, {}) ).toThrow(OUTSIDE_RANGE) }) }) }) describe(`infinity`, () => { it(`serialize`, () => { expect(() => ExampleFloatRange.serialize(Number.NEGATIVE_INFINITY)).toThrow( NOT_FINITE ) }) it(`parseValue`, () => { expect(() => ExampleFloatRange.parseValue(Number.NEGATIVE_INFINITY) ).toThrow(NOT_FINITE) }) it(`parseLiteral`, () => { expect(() => ExampleFloatRange.parseLiteral( { // @ts-ignore value: Number.NEGATIVE_INFINITY, kind: Kind.FLOAT }, {} ) ).toThrow(NOT_FINITE) }) }) describe(`not a number`, () => { it(`serialize`, () => { expect(() => ExampleFloatRange.serialize(`not a number`)).toThrow( NOT_NUMBER ) }) it(`parseValue`, () => { expect(() => ExampleFloatRange.parseValue(`not a number`)).toThrow( NOT_NUMBER ) }) it(`parseLiteral`, () => { expect(() => ExampleFloatRange.parseLiteral( { value: `not a number`, kind: Kind.STRING }, {} ) ).toThrow( CANNOT_VALIDATE ) }) }) describe(`NaN`, () => { it(`serialize`, () => { expect(() => ExampleFloatRange.serialize(Number.NaN)).toThrow( NOT_NUMBER ) }) it(`parseValue`, () => { expect(() => ExampleFloatRange.parseValue(Number.NaN)).toThrow( NOT_NUMBER ) }) it(`parseLiteral`, () => { expect(() => ExampleFloatRange.parseLiteral( // @ts-ignore { value: Number.NaN, kind: Kind.STRING }, {} ) ).toThrow( CANNOT_VALIDATE ) }) }) }) })
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [ecs](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Ecs extends PolicyStatement { public servicePrefix = 'ecs'; /** * Statement provider for service [ecs](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonelasticcontainerservice.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 a new capacity provider. Capacity providers are associated with an Amazon ECS cluster and are used in capacity provider strategies to facilitate cluster auto scaling * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateCapacityProvider.html */ public toCreateCapacityProvider() { return this.to('CreateCapacityProvider'); } /** * Grants permission to create a new Amazon ECS cluster * * Access Level: Write * * Possible conditions: * - .ifCapacityProvider() * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateCluster.html */ public toCreateCluster() { return this.to('CreateCluster'); } /** * Grants permission to run and maintain a desired number of tasks from a specified task definition via service creation * * Access Level: Write * * Possible conditions: * - .ifCluster() * - .ifCapacityProvider() * - .ifTaskDefinition() * - .ifEnableExecuteCommand() * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateService.html */ public toCreateService() { return this.to('CreateService'); } /** * Grants permission to create a new Amazon ECS task set * * Access Level: Write * * Possible conditions: * - .ifCluster() * - .ifCapacityProvider() * - .ifService() * - .ifTaskDefinition() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_CreateTaskSet.html */ public toCreateTaskSet() { return this.to('CreateTaskSet'); } /** * Grants permission to modify the ARN and resource ID format of a resource for a specified IAM user, IAM role, or the root user for an account. You can specify whether the new ARN and resource ID format are disabled for new resources that are created * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeleteAccountSetting.html */ public toDeleteAccountSetting() { return this.to('DeleteAccountSetting'); } /** * Grants permission to delete one or more custom attributes from an Amazon ECS resource * * Access Level: Write * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeleteAttributes.html */ public toDeleteAttributes() { return this.to('DeleteAttributes'); } /** * Grants permission to delete the specified capacity provider * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeleteCapacityProvider.html */ public toDeleteCapacityProvider() { return this.to('DeleteCapacityProvider'); } /** * Grants permission to delete the specified cluster * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeleteCluster.html */ public toDeleteCluster() { return this.to('DeleteCluster'); } /** * Grants permission to delete a specified service within a cluster * * Access Level: Write * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeleteService.html */ public toDeleteService() { return this.to('DeleteService'); } /** * Grants permission to delete the specified task set * * Access Level: Write * * Possible conditions: * - .ifCluster() * - .ifService() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeleteTaskSet.html */ public toDeleteTaskSet() { return this.to('DeleteTaskSet'); } /** * Grants permission to deregister an Amazon ECS container instance from the specified cluster * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeregisterContainerInstance.html */ public toDeregisterContainerInstance() { return this.to('DeregisterContainerInstance'); } /** * Grants permission to deregister the specified task definition by family and revision * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DeregisterTaskDefinition.html */ public toDeregisterTaskDefinition() { return this.to('DeregisterTaskDefinition'); } /** * Grants permission to describe one or more Amazon ECS capacity providers * * Access Level: Read * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeCapacityProviders.html */ public toDescribeCapacityProviders() { return this.to('DescribeCapacityProviders'); } /** * Grants permission to describes one or more of your clusters * * Access Level: Read * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeClusters.html */ public toDescribeClusters() { return this.to('DescribeClusters'); } /** * Grants permission to describes Amazon ECS container instances * * Access Level: Read * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeContainerInstances.html */ public toDescribeContainerInstances() { return this.to('DescribeContainerInstances'); } /** * Grants permission to describe the specified services running in your cluster * * Access Level: Read * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeServices.html */ public toDescribeServices() { return this.to('DescribeServices'); } /** * Grants permission to describe a task definition. You can specify a family and revision to find information about a specific task definition, or you can simply specify the family to find the latest ACTIVE revision in that family * * Access Level: Read * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeTaskDefinition.html */ public toDescribeTaskDefinition() { return this.to('DescribeTaskDefinition'); } /** * Grants permission to describe Amazon ECS task sets * * Access Level: Read * * Possible conditions: * - .ifCluster() * - .ifService() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeTaskSets.html */ public toDescribeTaskSets() { return this.to('DescribeTaskSets'); } /** * Grants permission to describe a specified task or tasks * * Access Level: Read * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeTasks.html */ public toDescribeTasks() { return this.to('DescribeTasks'); } /** * Grants permission to get an endpoint for the Amazon ECS agent to poll for updates * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DiscoverPollEndpoint.html */ public toDiscoverPollEndpoint() { return this.to('DiscoverPollEndpoint'); } /** * Grants permission to run a command remotely on an Amazon ECS container * * Access Level: Write * * Possible conditions: * - .ifCluster() * - .ifContainerName() * - .ifTask() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ExecuteCommand.html */ public toExecuteCommand() { return this.to('ExecuteCommand'); } /** * Grants permission to list the account settings for an Amazon ECS resource for a specified principal * * Access Level: Read * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListAccountSettings.html */ public toListAccountSettings() { return this.to('ListAccountSettings'); } /** * Grants permission to lists the attributes for Amazon ECS resources within a specified target type and cluster * * Access Level: List * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListAttributes.html */ public toListAttributes() { return this.to('ListAttributes'); } /** * Grants permission to get a list of existing clusters * * Access Level: List * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListClusters.html */ public toListClusters() { return this.to('ListClusters'); } /** * Grants permission to get a list of container instances in a specified cluster * * Access Level: List * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListContainerInstances.html */ public toListContainerInstances() { return this.to('ListContainerInstances'); } /** * Grants permission to get a list of services that are running in a specified cluster * * Access Level: List * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListServices.html */ public toListServices() { return this.to('ListServices'); } /** * Grants permission to get a list of tags for the specified resource * * Access Level: Read * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to get a list of task definition families that are registered to your account (which may include task definition families that no longer have any ACTIVE task definitions) * * Access Level: List * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListServices.html */ public toListTaskDefinitionFamilies() { return this.to('ListTaskDefinitionFamilies'); } /** * Grants permission to get a list of task definitions that are registered to your account * * Access Level: List * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListTaskDefinitions.html */ public toListTaskDefinitions() { return this.to('ListTaskDefinitions'); } /** * Grants permission to get a list of tasks for a specified cluster * * Access Level: List * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListTasks.html */ public toListTasks() { return this.to('ListTasks'); } /** * Grants permission to an agent to connect with the Amazon ECS service to report status and get commands * * Access Level: Write * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/instance_IAM_role.html */ public toPoll() { return this.to('Poll'); } /** * Grants permission to modify the ARN and resource ID format of a resource for a specified IAM user, IAM role, or the root user for an account. You can specify whether the new ARN and resource ID format are enabled for new resources that are created. Enabling this setting is required to use new Amazon ECS features such as resource tagging * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PutAccountSetting.html */ public toPutAccountSetting() { return this.to('PutAccountSetting'); } /** * Grants permission to modify the ARN and resource ID format of a resource type for all IAM users on an account for which no individual account setting has been set. Enabling this setting is required to use new Amazon ECS features such as resource tagging * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PutAccountSettingDefault.html */ public toPutAccountSettingDefault() { return this.to('PutAccountSettingDefault'); } /** * Grants permission to create or update an attribute on an Amazon ECS resource * * Access Level: Write * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PutAttributes.html */ public toPutAttributes() { return this.to('PutAttributes'); } /** * Grants permission to modify the available capacity providers and the default capacity provider strategy for a cluster * * Access Level: Write * * Possible conditions: * - .ifCapacityProvider() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_PutClusterCapacityProviders.html */ public toPutClusterCapacityProviders() { return this.to('PutClusterCapacityProviders'); } /** * Grants permission to register an EC2 instance into the specified cluster * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RegisterContainerInstance.html */ public toRegisterContainerInstance() { return this.to('RegisterContainerInstance'); } /** * Grants permission to register a new task definition from the supplied family and containerDefinitions * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RegisterTaskDefinition.html */ public toRegisterTaskDefinition() { return this.to('RegisterTaskDefinition'); } /** * Grants permission to start a task using random placement and the default Amazon ECS scheduler * * Access Level: Write * * Possible conditions: * - .ifCluster() * - .ifCapacityProvider() * - .ifEnableExecuteCommand() * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_RunTask.html */ public toRunTask() { return this.to('RunTask'); } /** * Grants permission to start a new task from the specified task definition on the specified container instance or instances * * Access Level: Write * * Possible conditions: * - .ifCluster() * - .ifContainerInstances() * - .ifEnableExecuteCommand() * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_StartTask.html */ public toStartTask() { return this.to('StartTask'); } /** * Grants permission to start a telemetry session * * Access Level: Write * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cloudwatch-metrics.html#enable_cloudwatch */ public toStartTelemetrySession() { return this.to('StartTelemetrySession'); } /** * Grants permission to stop a running task * * Access Level: Write * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_StopTask.html */ public toStopTask() { return this.to('StopTask'); } /** * Grants permission to send an acknowledgement that attachments changed states * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_SubmitAttachmentStateChanges.html */ public toSubmitAttachmentStateChanges() { return this.to('SubmitAttachmentStateChanges'); } /** * Grants permission to send an acknowledgement that a container changed states * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_SubmitContainerStateChange.html */ public toSubmitContainerStateChange() { return this.to('SubmitContainerStateChange'); } /** * Grants permission to send an acknowledgement that a task changed states * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_SubmitTaskStateChange.html */ public toSubmitTaskStateChange() { return this.to('SubmitTaskStateChange'); } /** * Grants permission to tag the specified resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to untag the specified resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update the specified capacity provider * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateCapacityProvider.html */ public toUpdateCapacityProvider() { return this.to('UpdateCapacityProvider'); } /** * Grants permission to modify the configuration or settings to use for a cluster * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateCluster.html */ public toUpdateCluster() { return this.to('UpdateCluster'); } /** * Grants permission to modify the settings to use for a cluster * * Access Level: Write * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateClusterSettings.html */ public toUpdateClusterSettings() { return this.to('UpdateClusterSettings'); } /** * Grants permission to update the Amazon ECS container agent on a specified container instance * * Access Level: Write * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateContainerAgent.html */ public toUpdateContainerAgent() { return this.to('UpdateContainerAgent'); } /** * Grants permission to the user to modify the status of an Amazon ECS container instance * * Access Level: Write * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateContainerInstancesState.html */ public toUpdateContainerInstancesState() { return this.to('UpdateContainerInstancesState'); } /** * Grants permission to modify the parameters of a service * * Access Level: Write * * Possible conditions: * - .ifCluster() * - .ifCapacityProvider() * - .ifEnableExecuteCommand() * - .ifTaskDefinition() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateService.html */ public toUpdateService() { return this.to('UpdateService'); } /** * Grants permission to modify the primary task set used in a service * * Access Level: Write * * Possible conditions: * - .ifCluster() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateServicePrimaryTaskSet.html */ public toUpdateServicePrimaryTaskSet() { return this.to('UpdateServicePrimaryTaskSet'); } /** * Grants permission to update the specified task set * * Access Level: Write * * Possible conditions: * - .ifCluster() * - .ifService() * * https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_UpdateTaskSet.html */ public toUpdateTaskSet() { return this.to('UpdateTaskSet'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateCapacityProvider", "CreateCluster", "CreateService", "CreateTaskSet", "DeleteAccountSetting", "DeleteAttributes", "DeleteCapacityProvider", "DeleteCluster", "DeleteService", "DeleteTaskSet", "DeregisterContainerInstance", "DeregisterTaskDefinition", "DiscoverPollEndpoint", "ExecuteCommand", "Poll", "PutAccountSetting", "PutAccountSettingDefault", "PutAttributes", "PutClusterCapacityProviders", "RegisterContainerInstance", "RegisterTaskDefinition", "RunTask", "StartTask", "StartTelemetrySession", "StopTask", "SubmitAttachmentStateChanges", "SubmitContainerStateChange", "SubmitTaskStateChange", "UpdateCapacityProvider", "UpdateCluster", "UpdateClusterSettings", "UpdateContainerAgent", "UpdateContainerInstancesState", "UpdateService", "UpdateServicePrimaryTaskSet", "UpdateTaskSet" ], "Read": [ "DescribeCapacityProviders", "DescribeClusters", "DescribeContainerInstances", "DescribeServices", "DescribeTaskDefinition", "DescribeTaskSets", "DescribeTasks", "ListAccountSettings", "ListTagsForResource" ], "List": [ "ListAttributes", "ListClusters", "ListContainerInstances", "ListServices", "ListTaskDefinitionFamilies", "ListTaskDefinitions", "ListTasks" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type cluster to the statement * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_clusters.html * * @param clusterName - Identifier for the clusterName. * @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() * - .ifResourceTag() */ public onCluster(clusterName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ecs:${Region}:${Account}:cluster/${ClusterName}'; arn = arn.replace('${ClusterName}', clusterName); 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 container-instance to the statement * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html * * @param containerInstanceId - Identifier for the containerInstanceId. * @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() * - .ifResourceTag() */ public onContainerInstance(containerInstanceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ecs:${Region}:${Account}:container-instance/${ContainerInstanceId}'; arn = arn.replace('${ContainerInstanceId}', containerInstanceId); 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 service to the statement * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html * * @param serviceName - Identifier for the serviceName. * @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() * - .ifResourceTag() */ public onService(serviceName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ecs:${Region}:${Account}:service/${ServiceName}'; arn = arn.replace('${ServiceName}', serviceName); 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 task to the statement * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/scheduling_tasks.html * * @param taskId - Identifier for the taskId. * @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() * - .ifResourceTag() */ public onTask(taskId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ecs:${Region}:${Account}:task/${TaskId}'; arn = arn.replace('${TaskId}', taskId); 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 task-definition to the statement * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html * * @param taskDefinitionFamilyName - Identifier for the taskDefinitionFamilyName. * @param taskDefinitionRevisionNumber - Identifier for the taskDefinitionRevisionNumber. * @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() * - .ifResourceTag() */ public onTaskDefinition(taskDefinitionFamilyName: string, taskDefinitionRevisionNumber: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ecs:${Region}:${Account}:task-definition/${TaskDefinitionFamilyName}:${TaskDefinitionRevisionNumber}'; arn = arn.replace('${TaskDefinitionFamilyName}', taskDefinitionFamilyName); arn = arn.replace('${TaskDefinitionRevisionNumber}', taskDefinitionRevisionNumber); 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 capacity-provider to the statement * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/capacity_provider_definitions.html * * @param capacityProviderName - Identifier for the capacityProviderName. * @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() * - .ifResourceTag() */ public onCapacityProvider(capacityProviderName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ecs:${Region}:${Account}:capacity-provider/${CapacityProviderName}'; arn = arn.replace('${CapacityProviderName}', capacityProviderName); 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 task-set to the statement * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_sets.html * * @param clusterName - Identifier for the clusterName. * @param serviceName - Identifier for the serviceName. * @param taskSetId - Identifier for the taskSetId. * @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() * - .ifResourceTag() */ public onTaskSet(clusterName: string, serviceName: string, taskSetId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ecs:${Region}:${Account}:task-set/${ClusterName}/${ServiceName}/${TaskSetId}'; arn = arn.replace('${ClusterName}', clusterName); arn = arn.replace('${ServiceName}', serviceName); arn = arn.replace('${TaskSetId}', taskSetId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters access based on tag key-value pairs attached to the resource * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/iam-policy-structure.html#amazon-ecs-keys * * Applies to resource types: * - cluster * - container-instance * - service * - task * - task-definition * - capacity-provider * - task-set * * @param tagKey The tag key to check * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifResourceTag(tagKey: string, value: string | string[], operator?: Operator | string) { return this.if(`ResourceTag/${ tagKey }`, value, operator || 'StringLike'); } /** * Filters access based on the ARN of an Amazon ECS capacity provider * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/iam-policy-structure.html#amazon-ecs-keys * * Applies to actions: * - .toCreateCluster() * - .toCreateService() * - .toCreateTaskSet() * - .toPutClusterCapacityProviders() * - .toRunTask() * - .toUpdateService() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifCapacityProvider(value: string | string[], operator?: Operator | string) { return this.if(`capacity-provider`, value, operator || 'ArnLike'); } /** * Filters access based on the ARN of an Amazon ECS cluster * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/iam-policy-structure.html#amazon-ecs-keys * * Applies to actions: * - .toCreateService() * - .toCreateTaskSet() * - .toDeleteAttributes() * - .toDeleteService() * - .toDeleteTaskSet() * - .toDescribeContainerInstances() * - .toDescribeServices() * - .toDescribeTaskSets() * - .toDescribeTasks() * - .toExecuteCommand() * - .toListServices() * - .toListTasks() * - .toPoll() * - .toPutAttributes() * - .toRunTask() * - .toStartTask() * - .toStartTelemetrySession() * - .toStopTask() * - .toUpdateContainerAgent() * - .toUpdateContainerInstancesState() * - .toUpdateService() * - .toUpdateServicePrimaryTaskSet() * - .toUpdateTaskSet() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifCluster(value: string | string[], operator?: Operator | string) { return this.if(`cluster`, value, operator || 'ArnLike'); } /** * Filters access based on the ARN of an Amazon ECS container instance * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/iam-policy-structure.html#amazon-ecs-keys * * Applies to actions: * - .toStartTask() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifContainerInstances(value: string | string[], operator?: Operator | string) { return this.if(`container-instances`, value, operator || 'ArnLike'); } /** * Filters access based on the name of an Amazon ECS container which is defined in the ECS task definition * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/iam-policy-structure.html#amazon-ecs-keys * * Applies to actions: * - .toExecuteCommand() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifContainerName(value: string | string[], operator?: Operator | string) { return this.if(`container-name`, value, operator || 'StringLike'); } /** * Filters access based on execute-command capability of your Amazon ECS task or Amazon ECS service * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/iam-policy-structure.html#amazon-ecs-keys * * Applies to actions: * - .toCreateService() * - .toRunTask() * - .toStartTask() * - .toUpdateService() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifEnableExecuteCommand(value: string | string[], operator?: Operator | string) { return this.if(`enable-execute-command`, value, operator || 'StringLike'); } /** * Filters access based on the ARN of an Amazon ECS service * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/iam-policy-structure.html#amazon-ecs-keys * * Applies to actions: * - .toCreateTaskSet() * - .toDeleteTaskSet() * - .toDescribeTaskSets() * - .toUpdateTaskSet() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifService(value: string | string[], operator?: Operator | string) { return this.if(`service`, value, operator || 'ArnLike'); } /** * Filters access based on the ARN of an Amazon ECS task * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/iam-policy-structure.html#amazon-ecs-keys * * Applies to actions: * - .toExecuteCommand() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifTask(value: string | string[], operator?: Operator | string) { return this.if(`task`, value, operator || 'ArnLike'); } /** * Filters access based on the ARN of an Amazon ECS task definition * * https://docs.aws.amazon.com/AmazonECS/latest/developerguide/iam-policy-structure.html#amazon-ecs-keys * * Applies to actions: * - .toCreateService() * - .toCreateTaskSet() * - .toUpdateService() * * @param value The value(s) to check * @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike` */ public ifTaskDefinition(value: string | string[], operator?: Operator | string) { return this.if(`task-definition`, value, operator || 'ArnLike'); } }
the_stack
import { motion, AnimatePresence, AnimateSharedLayout } from "@framer" import * as React from "react" import { useState } from "react" import styled from "styled-components" /** * This demo demonstrates the crossfade function between * components with the same layoutId * * The styles are pretty broken but it makes for a good test * case for smooth animation between very different layouts. */ function Card({ id, title, category, theme, isSelected, onClick }) { return ( <li className={`card ${theme}`} onClick={onClick}> <motion.div className="card-content-container"> <motion.div className="card-content" layoutId={`card-container-${id}`} magicDependency={isSelected} > <motion.div className="card-image-container" layoutId={`card-image-container-${id}`} magicDependency={isSelected} > <img className="card-image" src={`images/${id}.jpg`} alt="" /> </motion.div> <motion.div className="title-container" layoutId={`title-container-${id}`} magicDependency={isSelected} > <span className="category">{category}</span> <h2>{title}</h2> </motion.div> </motion.div> </motion.div> </li> ) } function List({ selectedId, setOpen }) { return ( <ul className="card-list"> {items.map(card => { return ( <Card key={card.id} {...card} isSelected={card.id === selectedId} onClick={() => setOpen(card.id)} /> ) })} </ul> ) } export function Item({ id, setOpen }) { const { category, title } = items.find(item => item.id === id) return ( <> <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} //1 transition={{ duration: 0.2 }} className="overlay" onClick={() => setOpen(false)} /> <div className="card-content-container open"> <motion.div className="card-content" layoutId={`card-container-${id}`} //2 > <motion.div className="card-image-container" layoutId={`card-image-container-${id}`} //3 > <img className="card-image" src={`images/${id}.jpg`} alt="" /> </motion.div> <motion.div className="title-container" layoutId={`title-container-${id}`} //4 > <span className="category">{category}</span> <h2>{title}</h2> </motion.div> <motion.div className="content-container" animate> Text </motion.div> </motion.div> </div> </> ) } const Header = () => ( <header> <span className="date">Thursday, August 8th</span> <h1>Today</h1> </header> ) export const items = [ // Photo by ivan Torres on Unsplash { id: "c", category: "Pizza", title: "5 Food Apps Delivering the Best of Your City", pointOfInterest: 80, backgroundColor: "#814A0E", }, // Photo by Dennis Brendel on Unsplash { id: "f", category: "How to", title: "Arrange Your Apple Devices for the Gram", pointOfInterest: 120, backgroundColor: "#959684", }, // Photo by Alessandra Caretto on Unsplash { id: "a", category: "Pedal Power", title: "Map Apps for the Superior Mode of Transport", pointOfInterest: 260, backgroundColor: "#5DBCD2", }, // Photo by Taneli Lahtinen on Unsplash { id: "g", category: "Holidays", title: "Our Pick of Apps to Help You Escape From Apps", pointOfInterest: 200, backgroundColor: "#8F986D", }, // Photo by Simone Hutsch on Unsplash { id: "d", category: "Photography", title: "The Latest Ultra-Specific Photography Editing Apps", pointOfInterest: 150, backgroundColor: "#FA6779", }, // Photo by Siora Photography on Unsplash { id: "h", category: "They're all the same", title: "100 Cupcake Apps for the Cupcake Connoisseur", pointOfInterest: 60, backgroundColor: "#282F49", }, // Photo by Yerlin Matu on Unsplash { id: "e", category: "Cats", title: "Yes, They Are Sociopaths", pointOfInterest: 200, backgroundColor: "#AC7441", }, // Photo by Ali Abdul Rahman on Unsplash { id: "b", category: "Holidays", title: "Seriously the Only Escape is the Stratosphere", pointOfInterest: 260, backgroundColor: "#CC555B", }, ] export const openSpring = { type: "spring", stiffness: 200, damping: 30 } export const closeSpring = { type: "spring", stiffness: 300, damping: 35 } function Store() { const [open, setOpen] = useState<string | false>(false) return ( <AnimateSharedLayout type="crossfade" transition={{ duration: 2 }}> <List selectedId={open} setOpen={setOpen} /> <AnimatePresence> {open && <Item id={open} setOpen={setOpen} />} </AnimatePresence> </AnimateSharedLayout> ) } export function App() { return ( <Container> <Header /> <Store /> </Container> ) } const Container = styled.div` * { box-sizing: border-box; font-family: ".SFNSText", "SFProText-Regular", "SFUIText-Regular", ".SFUIText", Helvetica, Arial, sans-serif; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } margin: 0; padding: 0; background: black; overflow-y: scroll; --secondary: rgb(161, 161, 161); --divider: #343434; font-family: sans-serif; text-align: center; display: flex; justify-content: center; width: 100vw; max-width: 990px; flex: 1 1 100%; padding: 45px 25px; .screen { width: 100%; height: 100%; } h1 { font-weight: bold; color: white; margin: 6px 0 12px; } .date { color: var(--secondary); font-size: 14px; text-transform: uppercase; } header { border-bottom: 1px solid var(--divider); position: relative; } .avatar { background: var(--divider); border-radius: 50%; position: absolute; bottom: 12px; right: 0; overflow: hidden; } .avatar, .avatar img { width: 40px; height: 40px; } ul, li { list-style: none; padding: 0; margin: 0; } .card-list { display: flex; flex-wrap: wrap; align-content: flex-start; } .card { position: relative; padding: 25px; height: 460px; flex: 0 0 40%; max-width: 40%; } .card:nth-child(4n + 1), .card:nth-child(4n + 4) { flex: 0 0 60%; max-width: 60%; } .card:nth-child(odd) { padding-left: 0; } .card:nth-child(even) { padding-right: 0; } .card-content-container { width: 100%; height: 100%; position: relative; display: block; pointer-events: none; } .card-content-container.open { top: 0; left: 0; right: 0; position: fixed; z-index: 1; overflow: hidden; padding: 40px 0; } .card-content { pointer-events: auto; position: relative; border-radius: 20px; background: #1c1c1e; overflow: hidden; width: 100%; height: 100%; margin: 0 auto; } .open .card-content { height: auto; max-width: 700px; overflow: hidden; } .card-open-link { position: absolute; top: 0; left: 0; right: 0; bottom: 0; } .card-image-container { position: absolute; top: 0; left: 0; overflow: hidden; height: 420px; width: 100vw; } .open .card-image-container, .open .title-container { z-index: 1; } .title-container { position: absolute; top: 15px; left: 15px; max-width: 300px; } .open .title-container { top: 30px; left: 30px; } h2 { color: #fff; margin: 8px 0; } .category { color: #fff; font-size: 14px; text-transform: uppercase; } .overlay { z-index: 1; position: fixed; background: rgba(0, 0, 0, 0.8); will-change: opacity; top: 0; bottom: 0; left: 50%; transform: translateX(-50%); width: 100%; max-width: 990px; } .overlay a { display: block; position: fixed; top: 0; bottom: 0; width: 100vw; left: 50%; transform: translateX(-50%); } .content-container { padding: 460px 35px 35px 35px; max-width: 700px; width: 90vw; } p { color: #9d9ca1; font-size: 20px; line-height: 28px; } @media only screen and (max-width: 800px) { .card { flex: 0 0 50%; max-width: 50%; } .card:nth-child(4n + 1), .card:nth-child(4n + 4) { flex: 0 0 50%; max-width: 50%; } } @media only screen and (max-width: 600px) { .card { flex: 1 0 100%; max-width: 100%; padding-left: 0; padding-right: 0; } .card:nth-child(4n + 1), .card:nth-child(4n + 4) { flex: 1 0 100%; max-width: 100%; } .card-content-container.open { padding: 0; } } `
the_stack
import { DebugElement, EventEmitter, Type, InjectionToken, AbstractType } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { outputProxy, PickByType } from '../tools/output-proxy'; import { createQueryMatch, QueryMatch } from './query-match'; import { TestSetup } from './test-setup'; import { MockDirective } from '../tools/mock-directive'; export interface RenderOptions<TBindings> { /** * Toggles automatic change-detection on initial render * * @default true */ detectChanges: boolean; /** * Toggles automatic awaiting of fixture.whenStable() on initial render * * @default true */ whenStable: boolean; /** * Bindings to be applied to your component or HTML template `@Input` properties */ bind: TBindings; } /** * Contains all information about a rendered test component including * utilities for querying and toggling rendered states of directives * * This is not intended for direct instantion. These are created via the `render` method on an instance of `Shallow` * * @link https://getsaf.github.io/shallow-render/#rendering */ export class Rendering<TComponent, TBindings> { constructor( public readonly fixture: ComponentFixture<any>, public readonly element: DebugElement, public readonly instance: TComponent, public readonly bindings: TBindings, private readonly _setup: TestSetup<TComponent> ) {} readonly outputs: PickByType<TComponent, EventEmitter<any>> = outputProxy(this.instance); ///////////////////////////////////////////////////////////////////////////// // The following methods MUST be arrow functions so they can be deconstructured // off of the class ///////////////////////////////////////////////////////////////////////////// /** * Search for a component with a CSS celector * * The result is either a `DebugElement` OR an Array of `DebugElement`. Your test * must give proper treatment to the result based on the expected results. * * For example, if your test expects a single result, you may treat the result as a `DebugElement` or an array of `DebugElement`s with one entry. * * @example * expect(find('h1.large').nativeElement.textContent).toBe('Foo'); * * // If your query results in multiple matches, you may iterate over the matches but if you attempt * // to treat the collection of matches as a single match, the test will fail due to a mismatched * // usage of the query results in the test. * * // This would throw an error if the query resulted in multiple matches * expect(find('h1.large').nativeElement.textContent).toBe('Foo'); * * const results = find('h1.large'); * expect(results.length).toBe(3); * expect(results.map(result => result.nativeElement.innerText)).toEqual([ * 'Foo', * 'Bar', * 'Baz' * ]) * * @link https://getsaf.github.io/shallow-render/#querying */ readonly find = (cssOrDirective: string | Type<any>, options?: { query?: string }): QueryMatch<DebugElement> => { const query = typeof cssOrDirective === 'string' ? By.css(cssOrDirective) : By.directive(this._setup.mockCache.find(cssOrDirective) || cssOrDirective); const mainQuery = this.fixture.debugElement.queryAll(query); const found = options && options.query ? this.fixture.debugElement.queryAll(By.css(options.query)).filter(item => mainQuery.includes(item)) : mainQuery; if (found.includes(this.element)) { throw new Error(`Don't search for your test component, it is automatically returned by the shallow renderer`); } return createQueryMatch(found); }; /** * Search for a component by it's class * * The result is either an instance of the component OR an Array of component instances. Your test * must give proper treatment to the result based on the expected results. * * For example, if your test expects a single result, you may treat the result as a single component instance or an array of instances with one entry. * * @example * expect(find(ItemComponent).label).toBe('Foo'); * * // If your query results in multiple matches, you may iterate over the matches but if you attempt * // to treat the collection of matches as a single match, the test will fail due to a mismatched * // usage of the query results in the test. * * // This would throw an error if the query resulted in multiple matches * expect(findComponent(ItemComponent).label).toBe('Foo'); * * const results = findComponent(ItemComponent); * expect(results.length).toBe(3); * expect(results.map(result => result.label)).toEqual([ * 'Foo', * 'Bar', * 'Baz' * ]) * * @link https://getsaf.github.io/shallow-render/#querying */ readonly findComponent = <TMatch>(component: Type<TMatch>, options?: { query?: string }): QueryMatch<TMatch> => this.findDirective(component, options); /** * Search for a directive by it's class * * Note: For structural directives, @see Rendering#findStructuralDirective * * The result is either an instance of the directive OR an Array of directive instances. Your test * must give proper treatment to the result based on the expected results. * * For example, if your test expects a single result, you may treat the result as a single directive instance or an array of instances with one entry. * * @example * expect(findDirective(MyDirective).label).toBe('Foo'); * * // If your query results in multiple matches, you may iterate over the matches but if you attempt * // to treat the collection of matches as a single match, the test will fail due to a mismatched * // usage of the query results in the test. * * // This would throw an error if the query resulted in multiple matches * expect(findDirective(MyDirective).label).toBe('Foo'); * * const results = findDirective(MyDirective); * expect(results.length).toBe(3); * expect(results.map(result => result.label)).toEqual([ * 'Foo', * 'Bar', * 'Baz' * ]) * * @link https://getsaf.github.io/shallow-render/#querying */ readonly findDirective = <TDirective>( directive: Type<TDirective>, options?: { query?: string } ): QueryMatch<TDirective> => { const directiveOrMock = this._setup.mockCache.find(directive) || directive; const foundElements = options && options.query ? this.fixture.debugElement.queryAll(By.css(options.query)) : this.find(directive, options); const foundDirectives = foundElements .map(result => { try { return result.injector.get<TDirective>(directiveOrMock); } catch (e) { return undefined; } }) .filter(i => i) as TDirective[]; if (foundDirectives.some(i => (i as any) === this.instance)) { throw new Error(`Don't search for your test component, it is automatically returned by the shallow renderer`); } return createQueryMatch(foundDirectives); }; /** * @deprecated Use inject instead */ readonly get = <TValue>(queryClass: Type<TValue> | InjectionToken<TValue> | AbstractType<TValue>): TValue => TestBed.inject(queryClass); /** * Get the instance of a provider via Angular's injection system. * * This is identical to `TestBed.inject` */ // tslint:disable-next-line: member-ordering readonly inject = TestBed.inject.bind(TestBed); /** * Search for a structural directive by it's class * * The result is either an instance of the directive OR an Array of directive instances. Your test * must give proper treatment to the result based on the expected results. * * For example, if your test expects a single result, you may treat the result as a single directive instance or an array of directives with one entry. * * @example * expect(find(MyDirective).label).toBe('Foo'); * * // If your query results in multiple matches, you may iterate over the matches but if you attempt * // to treat the collection of matches as a single match, the test will fail due to a mismatched * // usage of the query results in the test. * * // This would throw an error if the query resulted in multiple matches * expect(findStructuralDirective(MyDirective).label).toBe('Foo'); * * const results = findStructuralDirective(MyDirective); * expect(results.length).toBe(3); * expect(results.map(result => result.label)).toEqual([ * 'Foo', * 'Bar', * 'Baz' * ]) * * @link https://getsaf.github.io/shallow-render/#querying */ readonly findStructuralDirective = <TDirective>( directiveClass: Type<TDirective>, options?: { query?(d: TDirective): boolean } ) => createQueryMatch( this.fixture.debugElement .queryAllNodes(node => { try { const instance = node.injector.get(directiveClass); if (instance) { return options && options.query ? options.query(instance) : true; } } catch (e) {} // tslint:disable-line no-empty return false; }) .map(node => node.injector.get<TDirective>(directiveClass)) ); /** * Toggle on and off the rendering of child templates into a structural directive * * @link https://getsaf.github.io/shallow-render/#structural-directives */ readonly renderStructuralDirective = ( directiveClassOrObject: Type<any> | QueryMatch<any> | object, renderContents = true ) => { const directives: Array<MockDirective> = typeof directiveClassOrObject === 'function' ? this.findStructuralDirective<MockDirective>(directiveClassOrObject) : directiveClassOrObject.length ? directiveClassOrObject : [directiveClassOrObject]; if (!directives.length) { throw new Error(`Tried to render a structural directive but none were found.`); } directives.forEach(foundDirective => { if (!('renderContents' in foundDirective)) { const directiveName = Object.getPrototypeOf(foundDirective).constructor.name; throw new Error( `You may only manually render mocked directives with "renderStructuralDirective". Tried to render a structural directive (${directiveName}) but the directive is not mocked.` ); } if (renderContents) { foundDirective.renderContents(); } else { foundDirective.clearContents(); } }); }; }
the_stack
import { strict as assert } from 'assert'; import { Position, TextDocument } from 'vscode'; import { PythonDocument } from '../../../../src/actions/languages/python/motion'; suite('PythonDocument lines generator', () => { let _lines: string[]; let doc: TextDocument; setup(() => { _lines = ['x', 'y', 'z']; doc = { lineCount: _lines.length, lineAt: (line: number) => { return { text: _lines[line] }; }, } as TextDocument; }); test('lines() generator', () => { // GIVEN // WHEN const array = [...PythonDocument.lines(doc)]; // THEN assert.equal(array.length, 3); assert.equal(array[0], 'x'); assert.equal(array[1], 'y'); assert.equal(array[2], 'z'); }); }); suite('PythonDocument constructor without parsing', () => { test('constructor', () => { // GIVEN const doc = { lineCount: 0 } as TextDocument; // WHEN const pydoc = new PythonDocument(doc); // THEN: Object construction succeeds }); }); /* * Create a fake TextDocument object from a provided array of strings. * This has the minimal interface required by the find functionality. */ function fakeTextDocument(lines: string[]): TextDocument { return { lineCount: lines.length, lineAt: (line: number) => { return { text: lines[line] }; }, } as TextDocument; } suite('PythonDocument parse lines to extract structure', () => { let lines: string[]; let doc: TextDocument; setup(() => { lines = [ 'def first(x, y):', // 0 ' pass', '', 'class A:', '', ' def inner(self):', // 5 ' pass', '', 'def second():', ' pass', ]; doc = fakeTextDocument(lines); }); test('parse doc to calculate indentation', () => { // WHEN const parsed = PythonDocument._parseLines(doc); const line1 = parsed[0]; const line2 = parsed[1]; const line4 = parsed[3]; const line5 = parsed[4]; // THEN assert.equal(parsed.length, 7); assert.equal(line1.line, 0); assert.equal(line1.indentation, 0); assert.equal(line1.text, 'def first(x, y):'); assert.equal(line2.line, 1); assert.equal(line2.indentation, 4); assert.equal(line4.line, 5); assert.equal(line4.indentation, 4); assert.equal(line5.line, 6); assert.equal(line5.indentation, 8); }); test('document structure extraction', () => { // GIVEN const pydoc = new PythonDocument(doc); // WHEN const structure = pydoc.structure; const func1 = structure[0]; const class1 = structure[1]; const func2 = structure[2]; const func3 = structure[3]; // THEN assert.equal(func1.type, 'function'); assert.equal(func1.start.line, 0); assert.equal(func1.start.character, 0); assert.equal(func1.end.line, 1); assert.equal(func1.end.character, 7); assert.equal(class1.type, 'class'); assert.equal(class1.start.line, 3); assert.equal(class1.start.character, 0); assert.equal(class1.end.line, 6); assert.equal(class1.end.character, 11); assert.equal(func2.type, 'function'); assert.equal(func2.start.line, 5); assert.equal(func2.start.character, 4); assert.equal(func2.end.line, 6); assert.equal(func2.end.character, 11); assert.equal(func3.type, 'function'); assert.equal(func3.start.line, 8); assert.equal(func3.start.character, 0); assert.equal(func3.end.line, 9); assert.equal(func3.end.character, 7); }); }); suite('PythonDocument._textIndentation and PythonDocument._parseLine', () => { test('indentation of line with none', () => { // GIVEN const line = 'x = 42'; // WHEN const indent = PythonDocument._indentation(line); const info = PythonDocument._parseLine(42, line); // THEN assert.equal(indent, 0); assert.notEqual(info, undefined); assert(info !== undefined); assert.equal(info.line, 42); assert.equal(info.indentation, 0); assert.equal(info.text, line); }); test('indentation of line with 4 spaces', () => { // GIVEN const line = ' x = 42'; // WHEN const indent = PythonDocument._indentation(line); const info = PythonDocument._parseLine(42, line); // THEN assert.equal(indent, 4); assert.notEqual(info, undefined); assert(info !== undefined); assert.equal(info.line, 42); assert.equal(info.indentation, 4); assert.equal(info.text, line); }); test('indentation of line starting with a comment', () => { // GIVEN const line = ' # x = 42'; // WHEN const indent = PythonDocument._indentation(line); const info = PythonDocument._parseLine(42, line); // THEN assert.equal(indent, undefined); assert.equal(info, undefined); }); test('indentation of line containing only whitespace', () => { // GIVEN const line = ' '; // WHEN const indent = PythonDocument._indentation(line); const info = PythonDocument._parseLine(42, line); // THEN assert.equal(indent, undefined); assert.equal(info, undefined); }); test('indentation of empty line', () => { // GIVEN const line = ''; // WHEN const indent = PythonDocument._indentation(line); const info = PythonDocument._parseLine(42, line); // THEN assert.equal(indent, undefined); assert.equal(info, undefined); }); }); // Type of the find function after all but the last arg have been binded type Find = (position: Position) => Position | undefined; /* * Use fakeDocument to create a fake PythonDocument based on the passed in * array of strings. */ function fakePythonDocument(lines: string[]): PythonDocument { const doc = fakeTextDocument(lines); return new PythonDocument(doc); } suite('PythonDocument find function functionality', () => { let findNextFunctionStart: Find; let findPrevFunctionStart: Find; let findNextFunctionEnd: Find; let findPrevFunctionEnd: Find; setup(() => { const lines = [ "'''Module docstring.'''", // 0 '', 'def first(x, y):', '# a mis-placed comment', ' pass', '', // 5 'p = 42', '', 'def second(a, b):', '', ' def inner():', // 10 ' pass', '', 'x = 139', 'greeting = "Hello"', ]; const pydoc = fakePythonDocument(lines); findNextFunctionStart = pydoc.find.bind(pydoc, 'function', 'next', 'start'); findPrevFunctionStart = pydoc.find.bind(pydoc, 'function', 'prev', 'start'); findNextFunctionEnd = pydoc.find.bind(pydoc, 'function', 'next', 'end'); findPrevFunctionEnd = pydoc.find.bind(pydoc, 'function', 'prev', 'end'); }); test('valid findNextFunctionStart, start of file', () => { // GIVEN const position = new Position(0, 0); // WHEN const newPosition = findNextFunctionStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 2); assert.equal(newPosition.character, 0); }); test('valid findNextFunctionStart, past outer function', () => { // GIVEN const position = new Position(8, 2); // WHEN const newPosition = findNextFunctionStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 10); assert.equal(newPosition.character, 4); }); test('Invalid findNextFunctionStart, past last function', () => { // GIVEN const position = new Position(10, 6); // WHEN const newPosition = findNextFunctionStart(position); // THEN assert.equal(newPosition, undefined); }); test('valid findPrevFunctionStart, middle of function', () => { // GIVEN const position = new Position(3, 8); // WHEN const newPosition = findPrevFunctionStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 2); assert.equal(newPosition.character, 0); }); test('valid findPrevFunctionStart, start of inner function', () => { // GIVEN const position = new Position(10, 4); // WHEN const newPosition = findPrevFunctionStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 8); assert.equal(newPosition.character, 0); }); test('valid findPrevFunctionStart, start of second function', () => { // GIVEN const position = new Position(8, 0); // WHEN const newPosition = findPrevFunctionStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 2); assert.equal(newPosition.character, 0); }); test('invalid findPrevFunctionStart, above first function', () => { // GIVEN const position = new Position(0, 7); // WHEN const newPosition = findPrevFunctionStart(position); // THEN assert.equal(newPosition, undefined); }); test('Invalid findNextFunctionEnd, past last indented block', () => { // GIVEN const position = new Position(13, 2); // WHEN const newPosition = findNextFunctionEnd(position); // THEN assert.equal(newPosition, undefined); }); test('valid findNextFuntionEnd, inside inner function', () => { // GIVEN const position = new Position(10, 10); // WHEN const newPosition = findNextFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 11); assert.equal(newPosition.character, 11); }); test('valid findNextFuntionEnd, from inside outer function', () => { // GIVEN const position = new Position(9, 0); // WHEN const newPosition = findNextFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 11); assert.equal(newPosition.character, 11); }); test('valid findNextFunctionEnd, from start of function', () => { // GIVEN const position = new Position(2, 0); // WHEN const newPosition = findNextFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 4); assert.equal(newPosition.character, 7); }); test('valid findNextFunctionEnd, in middle from outside any function', () => { // GIVEN const position = new Position(6, 2); // WHEN const newPosition = findNextFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 11); assert.equal(newPosition.character, 11); }); test('valid findNextFunctionEnd, at exact end of first function', () => { // GIVEN const position = new Position(4, 7); // WHEN const newPosition = findNextFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 11); assert.equal(newPosition.character, 11); }); test('valid findPrevFunctionEnd, after first function, outside any function', () => { // GIVEN const position = new Position(6, 2); // WHEN const newPosition = findPrevFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 4); assert.equal(newPosition.character, 7); }); test('valid findPrevFunctionEnd, inside second function', () => { // GIVEN const position = new Position(9, 0); // WHEN const newPosition = findPrevFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 4); assert.equal(newPosition.character, 7); }); test('valid findPrevFunctionEnd, inside second function-s inner function', () => { // GIVEN const position = new Position(10, 7); // WHEN const newPosition = findPrevFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 4); assert.equal(newPosition.character, 7); }); test('valid findPrevFunctionEnd, after last function', () => { // GIVEN const position = new Position(13, 4); // WHEN const newPosition = findPrevFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 11); assert.equal(newPosition.character, 11); }); test('invalid findPrevFunctionEnd, before first function', () => { // GIVEN const position = new Position(1, 0); // WHEN const newPosition = findPrevFunctionEnd(position); // THEN assert.equal(newPosition, undefined); }); }); suite('PythonDocument find function functionality in doc containing class', () => { let findNextFunctionEnd: Find; setup(() => { const lines = [ 'def first(x, y):', // 0 ' pass', '', 'class A:', '', ' def inner(self):', // 5 ' pass', '', 'def second():', ' pass', ]; const pydoc = fakePythonDocument(lines); findNextFunctionEnd = pydoc.find.bind(pydoc, 'function', 'next', 'end'); }); test('valid findNextFunctionEnd, from within a class that follows a function', () => { // GIVEN const position = new Position(4, 0); // WHEN const newPosition = findNextFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 6); assert.equal(newPosition.character, 11); }); test('valid findNextFunctionEnd, from inside last function at end of file', () => { // GIVEN const position = new Position(8, 6); // WHEN const newPosition = findNextFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 9); assert.equal(newPosition.character, 7); }); }); suite('PythonDocument find function functionality near end of file', () => { let findNextFunctionEnd: Find; setup(() => { const lines = [ 'def first(x, y):', // 0 ' pass', '', ]; const pydoc = fakePythonDocument(lines); findNextFunctionEnd = pydoc.find.bind(pydoc, 'function', 'next', 'end'); }); test('valid findNextFunctionEnd, function ends with single empty line after it before file ends', () => { // GIVEN const position = new Position(0, 6); // WHEN const newPosition = findNextFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 1); assert.equal(newPosition.character, 7); }); }); suite('findPrevFunctionEnd with nested functions', () => { let findPrevFunctionEnd: Find; setup(() => { const lines = [ 'def outer(a, b):', // 0 '', ' def inner():', ' pass', '', ' return inner', // 5 '', 'x = 139', ]; const pydoc = fakePythonDocument(lines); findPrevFunctionEnd = pydoc.find.bind(pydoc, 'function', 'prev', 'end'); }); test('findPrevFunctoinEnd from after nested function should find outer function-s end', () => { // GIVEN const position = new Position(7, 4); // WHEN const newPosition = findPrevFunctionEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 5); assert.equal(newPosition.character, 15); }); }); suite('PythonDocument find class functionality', () => { let findNextClassStart: Find; let findPrevClassStart: Find; let findNextClassEnd: Find; let findPrevClassEnd: Find; setup(() => { const lines = [ "'''Module docstring.'''", // 0 '', 'class First:', '# a mis-placed comment', ' def __init__(self):', ' pass', // 5 '', 'p = 42', '', 'class Second:', '', // 10 ' def __init__(self):', ' pass', '', ' class Inner:', ' def __init__(self):', // 15 ' pass', '', 'x = 139', ]; const pydoc = fakePythonDocument(lines); findNextClassStart = pydoc.find.bind(pydoc, 'class', 'next', 'start'); findPrevClassStart = pydoc.find.bind(pydoc, 'class', 'prev', 'start'); findNextClassEnd = pydoc.find.bind(pydoc, 'class', 'next', 'end'); findPrevClassEnd = pydoc.find.bind(pydoc, 'class', 'prev', 'end'); }); test('valid findNextClassStart, start of file', () => { // GIVEN const position = new Position(0, 0); // WHEN const newPosition = findNextClassStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 2); assert.equal(newPosition.character, 0); }); test('valid findNextClassStart, past first class', () => { // GIVEN const position = new Position(8, 2); // WHEN const newPosition = findNextClassStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 9); assert.equal(newPosition.character, 0); }); test('valid findNextClassStart, past second outer class', () => { // GIVEN const position = new Position(9, 3); // WHEN const newPosition = findNextClassStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 14); assert.equal(newPosition.character, 4); }); test('Invalid findNextClassStart, past last class', () => { // GIVEN const position = new Position(14, 6); // WHEN const newPosition = findNextClassStart(position); // THEN assert.equal(newPosition, undefined); }); test('valid findPrevClassStart, end of file', () => { // GIVEN const position = new Position(18, 0); // WHEN const newPosition = findPrevClassStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 14); assert.equal(newPosition.character, 4); }); test('valid findPrevClassStart, past first class', () => { // GIVEN const position = new Position(7, 2); // WHEN const newPosition = findPrevClassStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 2); assert.equal(newPosition.character, 0); }); test('valid findPrevClassStart, past second outer class, before inner class', () => { // GIVEN const position = new Position(11, 8); // WHEN const newPosition = findPrevClassStart(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 9); assert.equal(newPosition.character, 0); }); test('Invalid findPrevClassStart, before first class', () => { // GIVEN const position = new Position(0, 6); // WHEN const newPosition = findPrevClassStart(position); // THEN assert.equal(newPosition, undefined); }); test('valid findNextClassEnd, start of file', () => { // GIVEN const position = new Position(0, 0); // WHEN const newPosition = findNextClassEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 5); assert.equal(newPosition.character, 11); }); test('valid findNextClassEnd, past first class', () => { // GIVEN const position = new Position(7, 2); // WHEN const newPosition = findNextClassEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 16); assert.equal(newPosition.character, 15); }); test('valid findNextClassEnd, past second outer class', () => { // GIVEN const position = new Position(9, 3); // WHEN const newPosition = findNextClassEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 16); assert.equal(newPosition.character, 15); }); test('Invalid findNextClassEnd, past last class', () => { // GIVEN const position = new Position(18, 3); // WHEN const newPosition = findNextClassEnd(position); // THEN assert.equal(newPosition, undefined); }); test('valid findPrevClassEnd, end of file', () => { // GIVEN const position = new Position(18, 4); // WHEN const newPosition = findPrevClassEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 16); assert.equal(newPosition.character, 15); }); test('valid findPrevClassEnd, past first class', () => { // GIVEN const position = new Position(7, 2); // WHEN const newPosition = findPrevClassEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 5); assert.equal(newPosition.character, 11); }); test('valid findPrevClassEnd, past second outer class', () => { // GIVEN const position = new Position(9, 3); // WHEN const newPosition = findPrevClassEnd(position); // THEN assert.notEqual(newPosition, undefined); assert(newPosition !== undefined); assert.equal(newPosition.line, 5); assert.equal(newPosition.character, 11); }); test('Invalid findPrevClassEnd, before end of first class', () => { // GIVEN const position = new Position(4, 8); // WHEN const newPosition = findPrevClassEnd(position); // THEN assert.equal(newPosition, undefined); }); });
the_stack
import { DEF_FONT_SIZE, DEF_SLIDE_MARGIN_IN, EMU, LINEH_MODIFIER, ONEPT, SLIDE_OBJECT_TYPES } from './core-enums' import { PresLayout, SlideLayout, TableCell, TableToSlidesProps, TableRow, TableRowSlide, TableCellProps } from './core-interfaces' import { getSmartParseNumber, inch2Emu, rgbToHex, valToPts } from './gen-utils' import PptxGenJS from './pptxgen' /** * Break cell text into lines based upon table column width (e.g.: Magic Happens Here(tm)) * @param {TableCell} cell - table cell * @param {number} colWidth - table column width (inches) * @return {TableRow[]} - cell's text objects grouped into lines */ function parseTextToLines(cell: TableCell, colWidth: number, verbose?: boolean): TableCell[][] { // FYI: CPL = Width / (font-size / font-constant) // FYI: CHAR:2.3, colWidth:10, fontSize:12 => CPL=138, (actual chars per line in PPT)=145 [14.5 CPI] // FYI: CHAR:2.3, colWidth:7 , fontSize:12 => CPL= 97, (actual chars per line in PPT)=100 [14.3 CPI] // FYI: CHAR:2.3, colWidth:9 , fontSize:16 => CPL= 96, (actual chars per line in PPT)=84 [ 9.3 CPI] const FOCO = 2.3 + (cell.options && cell.options.autoPageCharWeight ? cell.options.autoPageCharWeight : 0) // Character Constant const CPL = Math.floor((colWidth / ONEPT) * EMU) / ((cell.options && cell.options.fontSize ? cell.options.fontSize : DEF_FONT_SIZE) / FOCO) // Chars-Per-Line let parsedLines: TableCell[][] = [] let inputCells: TableCell[] = [] let inputLines1: TableCell[][] = [] let inputLines2: TableCell[][] = [] /* if (cell.options && cell.options.autoPageCharWeight) { let CHR1 = 2.3 + (cell.options && cell.options.autoPageCharWeight ? cell.options.autoPageCharWeight : 0) // Character Constant let CPL1 = ((colWidth / ONEPT) * EMU) / ((cell.options && cell.options.fontSize ? cell.options.fontSize : DEF_FONT_SIZE) / CHR1) // Chars-Per-Line console.log(`cell.options.autoPageCharWeight: '${cell.options.autoPageCharWeight}' => CPL: ${CPL1}`) let CHR2 = 2.3 + 0 let CPL2 = ((colWidth / ONEPT) * EMU) / ((cell.options && cell.options.fontSize ? cell.options.fontSize : DEF_FONT_SIZE) / CHR2) // Chars-Per-Line console.log(`cell.options.autoPageCharWeight: '0' => CPL: ${CPL2}`) } */ /** * EX INPUTS: `cell.text` * - string....: "Account Name Column" * - object....: { text:"Account Name Column" } * - object[]..: [{ text:"Account Name", options:{ bold:true } }, { text:" Column" }] * - object[]..: [{ text:"Account Name", options:{ breakLine:true } }, { text:"Input" }] */ /** * EX OUTPUTS: * - string....: [{ text:"Account Name Column" }] * - object....: [{ text:"Account Name Column" }] * - object[]..: [{ text:"Account Name", options:{ breakLine:true } }, { text:"Input" }] * - object[]..: [{ text:"Account Name", options:{ breakLine:true } }, { text:"Input" }] */ // STEP 1: Ensure inputCells is an array of TableCells if (cell.text && cell.text.toString().trim().length === 0) { // Allow a single space/whitespace as cell text (user-requested feature) inputCells.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: ' ' }) } else if (typeof cell.text === 'number' || typeof cell.text === 'string') { inputCells.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: (cell.text || '').toString().trim() }) } else if (Array.isArray(cell.text)) { inputCells = cell.text } if (verbose) { console.log('[1/4] inputCells') inputCells.forEach((cell, idx) => console.log(`[1/4] [${idx + 1}] cell: ${JSON.stringify(cell)}`)) //console.log('...............................................\n\n') } // STEP 2: Group table cells into lines based on "\n" or `breakLine` prop /** * - EX: `[{ text:"Input Output" }, { text:"Extra" }]` == 1 line * - EX: `[{ text:"Input" }, { text:"Output", options:{ breakLine:true } }]` == 1 line * - EX: `[{ text:"Input\nOutput" }]` == 2 lines * - EX: `[{ text:"Input", options:{ breakLine:true } }, { text:"Output" }]` == 2 lines */ let newLine: TableCell[] = [] inputCells.forEach(cell => { // (this is always true, we just constructed them above, but we need to tell typescript b/c type is still string||Cell[]) if (typeof cell.text === 'string') { if (cell.text.split('\n').length > 1) { cell.text.split('\n').forEach(textLine => { newLine.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: textLine, options: { ...cell.options, ...{ breakLine: true } }, }) }) } else { newLine.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: cell.text.trim(), options: cell.options, }) } if (cell.options && cell.options.breakLine) { if (verbose) console.log(`inputCells: new line > ${JSON.stringify(newLine)}`) inputLines1.push(newLine) newLine = [] } } // Flush buffer if (newLine.length > 0) inputLines1.push(newLine) }) if (verbose) { console.log(`[2/4] inputLines1 (${inputLines1.length})`) inputLines1.forEach((line, idx) => console.log(`[2/4] [${idx + 1}] line: ${JSON.stringify(line)}`)) //console.log('...............................................\n\n') } // STEP 3: Tokenize every text object into words (then it's really easy to assemble lines below without having to break text, add its `options`, etc.) inputLines1.forEach(line => { line.forEach(cell => { let lineCells: TableCell[] = [] let cellTextStr = cell.text + '' // force convert to string (compiled JS is better with this than a cast) let lineWords = cellTextStr.split(' ') lineWords.forEach((word, idx) => { let cellProps = { ...cell.options } // IMPORTANT: Handle `breakLine` prop - we cannot apply to each word - only apply to very last word! if (cellProps && cellProps.breakLine) cellProps.breakLine = idx + 1 === lineWords.length lineCells.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: word + (idx + 1 < lineWords.length ? ' ' : ''), options: cellProps }) }) inputLines2.push(lineCells) }) }) if (verbose) { console.log(`[3/4] inputLines2 (${inputLines2.length})`) inputLines2.forEach(line => console.log(`[3/4] line: ${JSON.stringify(line)}`)) //console.log('...............................................\n\n') } // STEP 4: Group cells/words into lines based upon space consumed by word letters inputLines2.forEach(line => { let lineCells: TableCell[] = [] let strCurrLine = '' line.forEach(word => { // A: create new line when horizontal space is exhausted if (strCurrLine.length + word.text.length > CPL) { //if (verbose) console.log(`STEP 4: New line added: (${strCurrLine.length} + ${word.text.length} > ${CPL})`); parsedLines.push(lineCells) lineCells = [] strCurrLine = '' } // B: add current word to line cells lineCells.push(word) // C: add current word to `strCurrLine` which we use to keep track of line's char length strCurrLine += word.text.toString() }) // Flush buffer: Only create a line when there's text to avoid empty row if (lineCells.length > 0) parsedLines.push(lineCells) }) if (verbose) { console.log(`[4/4] parsedLines (${parsedLines.length})`) parsedLines.forEach((line, idx) => console.log(`[4/4] [Line ${idx + 1}]:\n${JSON.stringify(line)}`)) console.log('...............................................\n\n') } // Done: return parsedLines } /** * Takes an array of table rows and breaks into an array of slides, which contain the calculated amount of table rows that fit on that slide * @param {TableCell[][]} tableRows - table rows * @param {TableToSlidesProps} tableProps - table2slides properties * @param {PresLayout} presLayout - presentation layout * @param {SlideLayout} masterSlide - master slide * @return {TableRowSlide[]} array of table rows */ export function getSlidesForTableRows(tableRows: TableCell[][] = [], tableProps: TableToSlidesProps = {}, presLayout: PresLayout, masterSlide?: SlideLayout): TableRowSlide[] { let arrInchMargins = DEF_SLIDE_MARGIN_IN let emuSlideTabW = EMU * 1 let emuSlideTabH = EMU * 1 let emuTabCurrH = 0 let numCols = 0 let tableRowSlides: TableRowSlide[] = [] let tablePropX = getSmartParseNumber(tableProps.x, 'X', presLayout) let tablePropY = getSmartParseNumber(tableProps.y, 'Y', presLayout) let tablePropW = getSmartParseNumber(tableProps.w, 'X', presLayout) let tablePropH = getSmartParseNumber(tableProps.h, 'Y', presLayout) let tableCalcW = tablePropW if (tableProps.verbose) { console.log('[[VERBOSE MODE]]') console.log('|-- TABLE PROPS --------------------------------------------------------|') console.log(`| presLayout.width ................................ = ${(presLayout.width / EMU).toFixed(1)}`) console.log(`| presLayout.height ............................... = ${(presLayout.height / EMU).toFixed(1)}`) console.log(`| tableProps.x .................................... = ${typeof tableProps.x === 'number' ? (tableProps.x / EMU).toFixed(1) : tableProps.x}`) console.log(`| tableProps.y .................................... = ${typeof tableProps.y === 'number' ? (tableProps.y / EMU).toFixed(1) : tableProps.y}`) console.log(`| tableProps.w .................................... = ${typeof tableProps.w === 'number' ? (tableProps.w / EMU).toFixed(1) : tableProps.w}`) console.log(`| tableProps.h .................................... = ${typeof tableProps.h === 'number' ? (tableProps.h / EMU).toFixed(1) : tableProps.h}`) console.log(`| tableProps.slideMargin .......................... = ${tableProps.slideMargin || ''}`) console.log(`| tableProps.margin ............................... = ${tableProps.margin}`) console.log(`| tableProps.colW ................................. = ${tableProps.colW}`) console.log(`| tableProps.autoPageSlideStartY .................. = ${tableProps.autoPageSlideStartY}`) console.log(`| tableProps.autoPageCharWeight ................... = ${tableProps.autoPageCharWeight}`) console.log('|-- CALCULATIONS -------------------------------------------------------|') console.log(`| tablePropX ...................................... = ${tablePropX / EMU}`) console.log(`| tablePropY ...................................... = ${tablePropY / EMU}`) console.log(`| tablePropW ...................................... = ${tablePropW / EMU}`) console.log(`| tablePropH ...................................... = ${tablePropH / EMU}`) console.log(`| tableCalcW ...................................... = ${tableCalcW / EMU}`) } // STEP 1: Calculate margins { // Important: Use default size as zero cell margin is causing our tables to be too large and touch bottom of slide! if (!tableProps.slideMargin && tableProps.slideMargin !== 0) tableProps.slideMargin = DEF_SLIDE_MARGIN_IN[0] if (masterSlide && typeof masterSlide._margin !== 'undefined') { if (Array.isArray(masterSlide._margin)) arrInchMargins = masterSlide._margin else if (!isNaN(Number(masterSlide._margin))) arrInchMargins = [Number(masterSlide._margin), Number(masterSlide._margin), Number(masterSlide._margin), Number(masterSlide._margin)] } else if (tableProps.slideMargin || tableProps.slideMargin === 0) { if (Array.isArray(tableProps.slideMargin)) arrInchMargins = tableProps.slideMargin else if (!isNaN(tableProps.slideMargin)) arrInchMargins = [tableProps.slideMargin, tableProps.slideMargin, tableProps.slideMargin, tableProps.slideMargin] } if (tableProps.verbose) console.log(`| arrInchMargins .................................. = [${arrInchMargins.join(', ')}]`) } // STEP 2: Calculate number of columns { // NOTE: Cells may have a colspan, so merely taking the length of the [0] (or any other) row is not // ....: sufficient to determine column count. Therefore, check each cell for a colspan and total cols as reqd let firstRow = tableRows[0] || [] firstRow.forEach(cell => { if (!cell) cell = { _type: SLIDE_OBJECT_TYPES.tablecell } let cellOpts = cell.options || null numCols += Number(cellOpts && cellOpts.colspan ? cellOpts.colspan : 1) }) if (tableProps.verbose) console.log(`| numCols ......................................... = ${numCols}`) } // STEP 3: Calculate width using tableProps.colW if possible if (!tablePropW && tableProps.colW) { tableCalcW = Array.isArray(tableProps.colW) ? tableProps.colW.reduce((p, n) => p + n) * EMU : tableProps.colW * numCols || 0 if (tableProps.verbose) console.log(`| tableCalcW ...................................... = ${tableCalcW / EMU}`) } // STEP 4: Calculate usable space/table size (now that total usable space is known) { emuSlideTabW = tableCalcW ? tableCalcW : inch2Emu((tablePropX ? tablePropX / EMU : arrInchMargins[1]) + arrInchMargins[3]) if (tableProps.verbose) console.log(`| emuSlideTabW .................................... = ${(emuSlideTabW / EMU).toFixed(1)}`) } // STEP 5: Calculate column widths if not provided (emuSlideTabW will be used below to determine lines-per-col) if (!tableProps.colW || !Array.isArray(tableProps.colW)) { if (tableProps.colW && !isNaN(Number(tableProps.colW))) { let arrColW = [] let firstRow = tableRows[0] || [] firstRow.forEach(() => arrColW.push(tableProps.colW)) tableProps.colW = [] arrColW.forEach(val => { if (Array.isArray(tableProps.colW)) tableProps.colW.push(val) }) } // No column widths provided? Then distribute cols. else { tableProps.colW = [] for (let iCol = 0; iCol < numCols; iCol++) { tableProps.colW.push(emuSlideTabW / EMU / numCols) } } } // STEP 6: **MAIN** Iterate over rows, add table content, create new slides as rows overflow let newTableRowSlide: TableRowSlide = { rows: [] as TableRow[] } tableRows.forEach((row, iRow) => { // A: Row variables let rowCellLines: TableCell[] = [] let maxCellMarTopEmu = 0 let maxCellMarBtmEmu = 0 // B: Create new row in data model let currTableRow: TableRow = [] row.forEach(cell => { currTableRow.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: [], options: cell.options, }) /** FUTURE: DEPRECATED: * - Backwards-Compat: Oops! Discovered we were still using points for cell margin before v3.8.0 (UGH!) * - We cant introduce a breaking change before v4.0, so... */ if (cell.options.margin && cell.options.margin[0] >= 1) { if (cell.options.margin && cell.options.margin[0] && valToPts(cell.options.margin[0]) > maxCellMarTopEmu) maxCellMarTopEmu = valToPts(cell.options.margin[0]) else if (tableProps.margin && tableProps.margin[0] && valToPts(tableProps.margin[0]) > maxCellMarTopEmu) maxCellMarTopEmu = valToPts(tableProps.margin[0]) if (cell.options.margin && cell.options.margin[2] && valToPts(cell.options.margin[2]) > maxCellMarBtmEmu) maxCellMarBtmEmu = valToPts(cell.options.margin[2]) else if (tableProps.margin && tableProps.margin[2] && valToPts(tableProps.margin[2]) > maxCellMarBtmEmu) maxCellMarBtmEmu = valToPts(tableProps.margin[2]) } else { if (cell.options.margin && cell.options.margin[0] && inch2Emu(cell.options.margin[0]) > maxCellMarTopEmu) maxCellMarTopEmu = inch2Emu(cell.options.margin[0]) else if (tableProps.margin && tableProps.margin[0] && inch2Emu(tableProps.margin[0]) > maxCellMarTopEmu) maxCellMarTopEmu = inch2Emu(tableProps.margin[0]) if (cell.options.margin && cell.options.margin[2] && inch2Emu(cell.options.margin[2]) > maxCellMarBtmEmu) maxCellMarBtmEmu = inch2Emu(cell.options.margin[2]) else if (tableProps.margin && tableProps.margin[2] && inch2Emu(tableProps.margin[2]) > maxCellMarBtmEmu) maxCellMarBtmEmu = inch2Emu(tableProps.margin[2]) } }) // C: Calc usable vertical space/table height. Set default value first, adjust below when necessary. let emuStartY = 0 if (tableRowSlides.length === 0) emuStartY = tablePropY ? tablePropY : inch2Emu(arrInchMargins[0]) if (tableRowSlides.length > 0) emuStartY = inch2Emu(tableProps.autoPageSlideStartY || tableProps.newSlideStartY || arrInchMargins[0]) emuSlideTabH = (tablePropH || presLayout.height) - emuStartY - inch2Emu(arrInchMargins[2]) //console.log(`| startY .......................................... = ${(emuStartY / EMU).toFixed(1)}`) //console.log(`| emuSlideTabH .................................... = ${(emuSlideTabH / EMU).toFixed(1)}`) if (tableRowSlides.length > 1) { // D: RULE: Use margins for starting point after the initial Slide, not `opt.y` (ISSUE #43, ISSUE #47, ISSUE #48) if (typeof tableProps.autoPageSlideStartY === 'number') { emuSlideTabH = (tablePropH || presLayout.height) - inch2Emu(tableProps.autoPageSlideStartY + arrInchMargins[2]) } else if (typeof tableProps.newSlideStartY === 'number') { // @deprecated v3.3.0 emuSlideTabH = (tablePropH || presLayout.height) - inch2Emu(tableProps.newSlideStartY + arrInchMargins[2]) } else if (tablePropY) { emuSlideTabH = (tablePropH || presLayout.height) - inch2Emu((tablePropY / EMU < arrInchMargins[0] ? tablePropY / EMU : arrInchMargins[0]) + arrInchMargins[2]) // Use whichever is greater: area between margins or the table H provided (dont shrink usable area - the whole point of over-riding Y on paging is to *increase* usable space) if (emuSlideTabH < tablePropH) emuSlideTabH = tablePropH } } if (tableProps.verbose && iRow === 0) console.log(`| SLIDE [${tableRowSlides.length}]: emuSlideTabH ...... = ${(emuSlideTabH / EMU).toFixed(1)} `) // E: --==[[ BUILD DATA SET ]]==-- (iterate over cells: split text into lines[], set `lineHeight`) row.forEach((cell, iCell) => { let newCell: TableCell = { _type: SLIDE_OBJECT_TYPES.tablecell, _lines: null, _lineHeight: inch2Emu( ((cell.options && cell.options.fontSize ? cell.options.fontSize : tableProps.fontSize ? tableProps.fontSize : DEF_FONT_SIZE) * (LINEH_MODIFIER + (tableProps.autoPageLineWeight ? tableProps.autoPageLineWeight : 0))) / 100 ), text: [], options: cell.options, } // E-1: Exempt cells with `rowspan` from increasing lineHeight (or we could create a new slide when unecessary!) if (newCell.options.rowspan) newCell._lineHeight = 0 // E-2: The parseTextToLines method uses `autoPageCharWeight`, so inherit from table options newCell.options.autoPageCharWeight = tableProps.autoPageCharWeight ? tableProps.autoPageCharWeight : null // E-3: **MAIN** Parse cell contents into lines based upon col width, font, etc let totalColW = tableProps.colW[iCell] if (cell.options.colspan && Array.isArray(tableProps.colW)) { totalColW = tableProps.colW.filter((_cell, idx) => idx >= iCell && idx < idx + cell.options.colspan).reduce((prev, curr) => prev + curr) } // E-4: Create lines based upon available column width newCell._lines = parseTextToLines(cell, totalColW, false) // E-5: Add cell to array rowCellLines.push(newCell) }) // F: Start row height with margins emuTabCurrH += maxCellMarTopEmu + maxCellMarBtmEmu /** G: --==[[ PAGE DATA SET ]]==-- * Add text one-line-a-time to this row's cells until: lines are exhausted OR table height limit is hit * * Design: * - Building cells L-to-R/loop style wont work as one could be 100 lines and another 1 line * - Therefore, build the whole row, one-line-at-a-time, across each table columns * - Then, when the vertical size limit is hit is by any of the cells, make a new slide and continue adding any remaining lines * * Implementation: * `rowCellLines` is an array of cells * - each cell contains an array of lines * EX: * { * _lines: [{ text:'cell-1,line-1' }, { text:'cell-1,line-2' }], // TOTAL-CELL-HEIGHT = 2 * _lines: [{ text:'cell-2,line-1' }, { text:'cell-2,line-2' }], // TOTAL-CELL-HEIGHT = 2 * _lines: [{ text:'cell-3,line-1' }, { text:'cell-3,line-2' }, { text:'cell-3,line-3' }, { text:'cell-3,line-4' }], // TOTAL-CELL-HEIGHT = 4 * } */ if (rowCellLines) { if (tableProps.verbose) console.log(`\n| SLIDE [${tableRowSlides.length}]: ROW [${iRow}]: START...`) // 1: Only increment `emuTabCurrH` below when adding lines from tallest cell (most lines or tallest total lineH) let maxLineHeightCellIdx = 0 rowCellLines.forEach((cell, cellIdx) => { // NOTE: Use ">=" because we want to use largest index possible - if all cols are H=1, then we want last index ot be the one we select if (cell._lines.length >= rowCellLines[maxLineHeightCellIdx]._lines.length) maxLineHeightCellIdx = cellIdx // TODO: we're only looking or most lines - we need to check for TALLEST _lineHeight too! }) // 2: build lines inside cells rowCellLines.forEach((cell, cellIdx) => { cell._lines.forEach((line, lineIdx) => { // A: create a new slide if there is insufficient room for the current row if (emuTabCurrH + cell._lineHeight > emuSlideTabH) { if (tableProps.verbose) { console.log('\n|-----------------------------------------------------------------------|') console.log( `|-- NEW SLIDE CREATED (currTabH+currLineH > maxH) => ${(emuTabCurrH / EMU).toFixed(2)} + ${(cell._lineHeight / EMU).toFixed(2)} > ${ emuSlideTabH / EMU }` ) console.log('|-----------------------------------------------------------------------|\n\n') } // 1: add current row slide or it will be lost (only if it has rows and text) if (currTableRow.length > 0 && currTableRow.map(cell => cell.text.length).reduce((p, n) => p + n) > 0) newTableRowSlide.rows.push(currTableRow) // 2: add current slide to Slides array tableRowSlides.push(newTableRowSlide) // 3: reset working/curr slide to hold rows as they're created let newRows: TableRow[] = [] newTableRowSlide = { rows: newRows } // 4: reset working/curr row currTableRow = [] row.forEach(cell => { currTableRow.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: [], options: cell.options, }) }) // 5: reset current table height for this new Slide emuTabCurrH = 0 // 6: handle repeat headers option /or/ Add new empty row to continue current lines into if ((tableProps.addHeaderToEach || tableProps.autoPageRepeatHeader) && tableProps._arrObjTabHeadRows) { tableProps._arrObjTabHeadRows.forEach(row => { let newHeadRow: TableRow = [] let maxLineHeight = 0 row.forEach(cell => { newHeadRow.push(cell) if (cell._lineHeight > maxLineHeight) maxLineHeight = cell._lineHeight }) newTableRowSlide.rows.push(newHeadRow) emuTabCurrH += maxLineHeight // TODO: what about margins? dont we need to include cell margin in line height? }) } } // B: get current cell on `currTableRow` let currCell = currTableRow[cellIdx] // C: create new line (add all words) if (Array.isArray(currCell.text)) currCell.text = currCell.text.concat(line) // D: increase table height by the curr line height (if this is tallest cell) if (cellIdx === maxLineHeightCellIdx) emuTabCurrH += cell._lineHeight /** E: handle case where a cell's lines overflow, but adjacent row cells dont have lines left * - In this case, `rowCellLines` has no content for cell 0 and cell 1 * - so we need to add a { text: "" } or PPTX will be corrupted! (as each row needs the same amount of cells) * * SLIDE 1: * |--------|--------|--------| * | line-1 | line-1 | line-1 | * |--------|--------|--------| * * SLIDE 2: * |--------|--------|--------| * | | | line-2 | * |--------|--------|--------| */ currTableRow.forEach((cell, idx) => { if (idx < cellIdx && Array.isArray(cell.text) && cell.text.length === 0) cell.text.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: ' ' }) }) // DONE if (tableProps.verbose) { console.log( `- SLIDE [${tableRowSlides.length}]: ROW [${iRow}]: CELL [${cellIdx}]: LINE [${lineIdx}] added ... emuTabCurrH = ${(emuTabCurrH / EMU).toFixed(2)}` ) } }) }) } // 7: Flush/capture row buffer before it resets at the top of this loop if (currTableRow.length > 0) newTableRowSlide.rows.push(currTableRow) if (tableProps.verbose) console.log( `- SLIDE [${tableRowSlides.length}]: ROW [${iRow}]: ...COMPLETE ...... emuTabCurrH = ${(emuTabCurrH / EMU).toFixed(2)} ( emuSlideTabH = ${( emuSlideTabH / EMU ).toFixed(2)} )` ) }) // STEP 7: Flush buffer / add final slide tableRowSlides.push(newTableRowSlide) if (tableProps.verbose) { console.log(`\n|================================================|`) console.log(`| FINAL: tableRowSlides.length = ${tableRowSlides.length}`) tableRowSlides.forEach(slide => console.log(slide)) console.log(`|================================================|\n\n`) } // LAST: return tableRowSlides } /** * Reproduces an HTML table as a PowerPoint table - including column widths, style, etc. - creates 1 or more slides as needed * @param {PptxGenJS} pptx - pptxgenjs instance * @param {string} tabEleId - HTMLElementID of the table * @param {ITableToSlidesOpts} options - array of options (e.g.: tabsize) * @param {SlideLayout} masterSlide - masterSlide */ export function genTableToSlides(pptx: PptxGenJS, tabEleId: string, options: TableToSlidesProps = {}, masterSlide?: SlideLayout) { let opts = options || {} opts.slideMargin = opts.slideMargin || opts.slideMargin === 0 ? opts.slideMargin : 0.5 let emuSlideTabW = opts.w || pptx.presLayout.width let arrObjTabHeadRows: [TableCell[]?] = [] let arrObjTabBodyRows: [TableCell[]?] = [] let arrObjTabFootRows: [TableCell[]?] = [] let arrColW: number[] = [] let arrTabColW: number[] = [] let arrInchMargins: [number, number, number, number] = [0.5, 0.5, 0.5, 0.5] // TRBL-style let intTabW = 0 // REALITY-CHECK: if (!document.getElementById(tabEleId)) throw new Error('tableToSlides: Table ID "' + tabEleId + '" does not exist!') // STEP 1: Set margins if (masterSlide && masterSlide._margin) { if (Array.isArray(masterSlide._margin)) arrInchMargins = masterSlide._margin else if (!isNaN(masterSlide._margin)) arrInchMargins = [masterSlide._margin, masterSlide._margin, masterSlide._margin, masterSlide._margin] opts.slideMargin = arrInchMargins } else if (opts && opts.slideMargin) { if (Array.isArray(opts.slideMargin)) arrInchMargins = opts.slideMargin else if (!isNaN(opts.slideMargin)) arrInchMargins = [opts.slideMargin, opts.slideMargin, opts.slideMargin, opts.slideMargin] } emuSlideTabW = (opts.w ? inch2Emu(opts.w) : pptx.presLayout.width) - inch2Emu(arrInchMargins[1] + arrInchMargins[3]) if (opts.verbose) { console.log('[[VERBOSE MODE]]') console.log('|-- `tableToSlides` ----------------------------------------------------|') console.log(`| tableProps.h .................................... = ${opts.h}`) console.log(`| tableProps.w .................................... = ${opts.w}`) console.log(`| pptx.presLayout.width ........................... = ${(pptx.presLayout.width / EMU).toFixed(1)}`) console.log(`| pptx.presLayout.height .......................... = ${(pptx.presLayout.height / EMU).toFixed(1)}`) console.log(`| emuSlideTabW .................................... = ${(emuSlideTabW / EMU).toFixed(1)}`) } // STEP 2: Grab table col widths - just find the first availble row, either thead/tbody/tfoot, others may have colspans, who cares, we only need col widths from 1 let firstRowCells = document.querySelectorAll(`#${tabEleId} tr:first-child th`) if (firstRowCells.length === 0) firstRowCells = document.querySelectorAll(`#${tabEleId} tr:first-child td`) firstRowCells.forEach((cell: HTMLElement) => { if (cell.getAttribute('colspan')) { // Guesstimate (divide evenly) col widths // NOTE: both j$query and vanilla selectors return {0} when table is not visible) for (let idxc = 0; idxc < Number(cell.getAttribute('colspan')); idxc++) { arrTabColW.push(Math.round(cell.offsetWidth / Number(cell.getAttribute('colspan')))) } } else { arrTabColW.push(cell.offsetWidth) } }) arrTabColW.forEach(colW => { intTabW += colW }) // STEP 3: Calc/Set column widths by using same column width percent from HTML table arrTabColW.forEach((colW, idxW) => { let intCalcWidth = Number(((Number(emuSlideTabW) * ((colW / intTabW) * 100)) / 100 / EMU).toFixed(2)) let intMinWidth = 0 let colSelectorMin = document.querySelector(`#${tabEleId} thead tr:first-child th:nth-child(${idxW + 1})`) if (colSelectorMin) intMinWidth = Number(colSelectorMin.getAttribute('data-pptx-min-width')) let intSetWidth = 0 let colSelectorSet = document.querySelector(`#${tabEleId} thead tr:first-child th:nth-child(${idxW + 1})`) if (colSelectorSet) intMinWidth = Number(colSelectorSet.getAttribute('data-pptx-width')) arrColW.push(intSetWidth ? intSetWidth : intMinWidth > intCalcWidth ? intMinWidth : intCalcWidth) }) if (opts.verbose) { console.log(`| arrColW ......................................... = [${arrColW.join(', ')}]`) } // STEP 4: Iterate over each table element and create data arrays (text and opts) // NOTE: We create 3 arrays instead of one so we can loop over body then show header/footer rows on first and last page let tableParts = ['thead', 'tbody', 'tfoot'] tableParts.forEach(part => { document.querySelectorAll(`#${tabEleId} ${part} tr`).forEach((row: HTMLTableRowElement) => { let arrObjTabCells: TableCell[] = [] Array.from(row.cells).forEach(cell => { // A: Get RGB text/bkgd colors let arrRGB1 = window.getComputedStyle(cell).getPropertyValue('color').replace(/\s+/gi, '').replace('rgba(', '').replace('rgb(', '').replace(')', '').split(',') let arrRGB2 = window .getComputedStyle(cell) .getPropertyValue('background-color') .replace(/\s+/gi, '') .replace('rgba(', '') .replace('rgb(', '') .replace(')', '') .split(',') if ( // NOTE: (ISSUE#57): Default for unstyled tables is black bkgd, so use white instead window.getComputedStyle(cell).getPropertyValue('background-color') === 'rgba(0, 0, 0, 0)' || window.getComputedStyle(cell).getPropertyValue('transparent') ) { arrRGB2 = ['255', '255', '255'] } // B: Create option object let cellOpts: TableCellProps = { align: null, bold: window.getComputedStyle(cell).getPropertyValue('font-weight') === 'bold' || Number(window.getComputedStyle(cell).getPropertyValue('font-weight')) >= 500 ? true : false, border: null, color: rgbToHex(Number(arrRGB1[0]), Number(arrRGB1[1]), Number(arrRGB1[2])), fill: { color: rgbToHex(Number(arrRGB2[0]), Number(arrRGB2[1]), Number(arrRGB2[2])) }, fontFace: (window.getComputedStyle(cell).getPropertyValue('font-family') || '').split(',')[0].replace(/"/g, '').replace('inherit', '').replace('initial', '') || null, fontSize: Number(window.getComputedStyle(cell).getPropertyValue('font-size').replace(/[a-z]/gi, '')), margin: null, colspan: Number(cell.getAttribute('colspan')) || null, rowspan: Number(cell.getAttribute('rowspan')) || null, valign: null, } if (['left', 'center', 'right', 'start', 'end'].indexOf(window.getComputedStyle(cell).getPropertyValue('text-align')) > -1) { let align = window.getComputedStyle(cell).getPropertyValue('text-align').replace('start', 'left').replace('end', 'right') cellOpts.align = align === 'center' ? 'center' : align === 'left' ? 'left' : align === 'right' ? 'right' : null } if (['top', 'middle', 'bottom'].indexOf(window.getComputedStyle(cell).getPropertyValue('vertical-align')) > -1) { let valign = window.getComputedStyle(cell).getPropertyValue('vertical-align') cellOpts.valign = valign === 'top' ? 'top' : valign === 'middle' ? 'middle' : valign === 'bottom' ? 'bottom' : null } // C: Add padding [margin] (if any) // NOTE: Margins translate: px->pt 1:1 (e.g.: a 20px padded cell looks the same in PPTX as 20pt Text Inset/Padding) if (window.getComputedStyle(cell).getPropertyValue('padding-left')) { cellOpts.margin = [0, 0, 0, 0] let sidesPad = ['padding-top', 'padding-right', 'padding-bottom', 'padding-left'] sidesPad.forEach((val, idxs) => { cellOpts.margin[idxs] = Math.round(Number(window.getComputedStyle(cell).getPropertyValue(val).replace(/\D/gi, ''))) }) } // D: Add border (if any) if ( window.getComputedStyle(cell).getPropertyValue('border-top-width') || window.getComputedStyle(cell).getPropertyValue('border-right-width') || window.getComputedStyle(cell).getPropertyValue('border-bottom-width') || window.getComputedStyle(cell).getPropertyValue('border-left-width') ) { cellOpts.border = [null, null, null, null] let sidesBor = ['top', 'right', 'bottom', 'left'] sidesBor.forEach((val, idxb) => { let intBorderW = Math.round( Number( window .getComputedStyle(cell) .getPropertyValue('border-' + val + '-width') .replace('px', '') ) ) let arrRGB = [] arrRGB = window .getComputedStyle(cell) .getPropertyValue('border-' + val + '-color') .replace(/\s+/gi, '') .replace('rgba(', '') .replace('rgb(', '') .replace(')', '') .split(',') let strBorderC = rgbToHex(Number(arrRGB[0]), Number(arrRGB[1]), Number(arrRGB[2])) cellOpts.border[idxb] = { pt: intBorderW, color: strBorderC } }) } // LAST: Add cell arrObjTabCells.push({ _type: SLIDE_OBJECT_TYPES.tablecell, text: cell.innerText, // `innerText` returns <br> as "\n", so linebreak etc. work later! options: cellOpts, }) }) switch (part) { case 'thead': arrObjTabHeadRows.push(arrObjTabCells) break case 'tbody': arrObjTabBodyRows.push(arrObjTabCells) break case 'tfoot': arrObjTabFootRows.push(arrObjTabCells) break default: console.log(`table parsing: unexpected table part: ${part}`) break } }) }) // STEP 5: Break table into Slides as needed // Pass head-rows as there is an option to add to each table and the parse func needs this data to fulfill that option opts._arrObjTabHeadRows = arrObjTabHeadRows || null opts.colW = arrColW getSlidesForTableRows([...arrObjTabHeadRows, ...arrObjTabBodyRows, ...arrObjTabFootRows], opts, pptx.presLayout, masterSlide).forEach((slide, idxTr) => { // A: Create new Slide let newSlide = pptx.addSlide({ masterName: opts.masterSlideName || null }) // B: DESIGN: Reset `y` to startY or margin after first Slide (ISSUE#43, ISSUE#47, ISSUE#48) if (idxTr === 0) opts.y = opts.y || arrInchMargins[0] if (idxTr > 0) opts.y = opts.autoPageSlideStartY || opts.newSlideStartY || arrInchMargins[0] if (opts.verbose) console.log(`| opts.autoPageSlideStartY: ${opts.autoPageSlideStartY} / arrInchMargins[0]: ${arrInchMargins[0]} => opts.y = ${opts.y}`) // C: Add table to Slide newSlide.addTable(slide.rows, { x: opts.x || arrInchMargins[3], y: opts.y, w: Number(emuSlideTabW) / EMU, colW: arrColW, autoPage: false }) // D: Add any additional objects if (opts.addImage) newSlide.addImage({ path: opts.addImage.url, x: opts.addImage.x, y: opts.addImage.y, w: opts.addImage.w, h: opts.addImage.h }) if (opts.addShape) newSlide.addShape(opts.addShape.shape, opts.addShape.options || {}) if (opts.addTable) newSlide.addTable(opts.addTable.rows, opts.addTable.options || {}) if (opts.addText) newSlide.addText(opts.addText.text, opts.addText.options || {}) }) }
the_stack
import { makeApp, makeClientForPlugin, makeDisplay, makePowerMonitor, makeProcess, makeScreen } from '@bugsnag/electron-test-helpers' import plugin from '../' const nextTick = async () => new Promise(process.nextTick) function makeClient ({ app = makeApp(), screen = makeScreen(), process = makeProcess(), filestore = makeFilestore(), NativeClient = makeNativeClient(), powerMonitor = makePowerMonitor() } = {}) { return makeClientForPlugin({ plugin: plugin(app, screen, process, filestore, NativeClient, powerMonitor) }) } const DEFAULTS = { freeMemory: 25, // this is in KiB to match Electron's API id: 'abcdefghijklmnopqrstuvwxyz', locale: 'en-GB', platform: 'serenity', osVersion: '10.20.30', versions: { node: '1.1.1', chrome: '22.22.22', electron: '333.333.333' }, screenDensity: 1.0, screenResolution: { width: 1234, height: 5678 }, time: expect.any(Date), totalMemory: 100, // this is in KiB to match Electron's API usingBattery: false, isLocked: false, idleTime: 0 } // expected data for 'session.device' const makeExpectedSessionDevice = (customisations = {}) => ({ totalMemory: DEFAULTS.totalMemory * 1024, id: DEFAULTS.id, locale: DEFAULTS.locale, osName: DEFAULTS.platform, osVersion: DEFAULTS.osVersion, runtimeVersions: DEFAULTS.versions, ...customisations }) // expected data for 'event.device' const makeExpectedEventDevice = (customisations = {}) => ({ ...makeExpectedSessionDevice(), time: DEFAULTS.time, freeMemory: DEFAULTS.freeMemory * 1024, ...customisations }) // expected data for 'event.metadata.device' const makeExpectedMetadataDevice = (customisations = {}) => ({ isLocked: DEFAULTS.isLocked, screenDensity: DEFAULTS.screenDensity, screenResolution: DEFAULTS.screenResolution, usingBattery: DEFAULTS.usingBattery, idleTime: DEFAULTS.idleTime, ...customisations }) describe('plugin: electron device info', () => { it('syncs device information to the NativeClient', async () => { const NativeClient = makeNativeClient() makeClient({ NativeClient }) const expected = makeExpectedSessionDevice() expect(NativeClient.setDevice).toHaveBeenNthCalledWith(1, expected) }) it('handles exceptions thrown by the NativeClient', async () => { const NativeClient = { setDevice: jest.fn().mockImplementation(() => { throw new Error('abc') }) } makeClient({ NativeClient }) const expected = makeExpectedSessionDevice() expect(NativeClient.setDevice).toHaveBeenNthCalledWith(1, expected) }) it('reports basic device information', async () => { const { sendEvent, sendSession } = makeClient() // give the filestore time to resolve the device ID await nextTick() const event = await sendEvent() expect(event.device).toEqual(makeExpectedEventDevice()) expect(event.getMetadata('device')).toEqual(makeExpectedMetadataDevice()) const session = await sendSession() expect(session.device).toEqual(makeExpectedSessionDevice()) }) it('reports correct locale and OS for macOS', async () => { const process = makeProcess({ platform: 'darwin' }) const { sendEvent, sendSession } = makeClient({ process }) const expectedBeforeNextTick = makeExpectedEventDevice({ osName: 'macOS' }) const event = await sendEvent() expect(event.device).toEqual(expectedBeforeNextTick) await nextTick() const event2 = await sendEvent() expect(event2.device).toEqual(makeExpectedEventDevice({ osName: 'macOS' })) const session = await sendSession() expect(session.device).toEqual(makeExpectedSessionDevice({ osName: 'macOS' })) }) it('reports correct locale and OS for Linux', async () => { const process = makeProcess({ platform: 'linux' }) const { sendEvent, sendSession } = makeClient({ process }) const expectedBeforeNextTick = makeExpectedEventDevice({ osName: 'Linux' }) const event = await sendEvent() expect(event.device).toEqual(expectedBeforeNextTick) await nextTick() const event2 = await sendEvent() expect(event2.device).toEqual(makeExpectedEventDevice({ osName: 'Linux' })) const session = await sendSession() expect(session.device).toEqual(makeExpectedSessionDevice({ osName: 'Linux' })) }) it('reports correct locale and OS for Windows', async () => { // on windows, app.getLocale will return an empty string until the app is ready const app = makeApp() app.getLocale = jest.fn() .mockImplementationOnce(() => '') .mockImplementation(() => 'en-GB') const process = makeProcess({ platform: 'win32' }) const { sendEvent, sendSession } = makeClient({ app, process }) const expectedBeforeNextTick = makeExpectedEventDevice({ osName: 'Windows' }) expectedBeforeNextTick.locale = '' const event = await sendEvent() expect(event.device).toEqual(expectedBeforeNextTick) await nextTick() const event2 = await sendEvent() expect(event2.device).toEqual(makeExpectedEventDevice({ osName: 'Windows' })) const session = await sendSession() expect(session.device).toEqual(makeExpectedSessionDevice({ osName: 'Windows' })) }) // in theory this is impossible as Chromium should always return a primary // display even there is no display; we handle it anyway just to be safe it('does not report screen information if there is no primary display', async () => { const screen = { getPrimaryDisplay: () => undefined, on: () => {} } // @ts-expect-error const { sendEvent, sendSession } = makeClient({ screen }) await nextTick() const expectedEvent = makeExpectedEventDevice({ screenResolution: undefined, screenDensity: undefined }) const expectedSession = makeExpectedSessionDevice({ screenResolution: undefined, screenDensity: undefined }) const event = await sendEvent() expect(event.device).toEqual(expectedEvent) const session = await sendSession() expect(session.device).toEqual(expectedSession) }) it('reports correct screen information if primary display is changed', async () => { const primaryDisplay = makeDisplay() const screen = makeScreen({ primaryDisplay }) const { sendEvent, sendSession } = makeClient({ screen }) await nextTick() const event = await sendEvent() expect(event.device).toEqual(makeExpectedEventDevice()) expect(event.getMetadata('device')).toEqual(makeExpectedMetadataDevice()) const session = await sendSession() expect(session.device).toEqual(makeExpectedSessionDevice()) primaryDisplay.size = { width: 100, height: 200 } primaryDisplay.scaleFactor = 2.5 screen._emit('display-metrics-changed', primaryDisplay, ['bounds', 'scaleFactor']) const event2 = await sendEvent() expect(event2.device).toEqual(makeExpectedEventDevice()) expect(event2.getMetadata('device')).toEqual(makeExpectedMetadataDevice({ screenDensity: 2.5, screenResolution: { width: 100, height: 200 } })) const session2 = await sendSession() expect(session2.device).toEqual(makeExpectedSessionDevice()) }) it('does not update screen information if a secondary display is changed', async () => { const primaryDisplay = makeDisplay({ size: { width: 222, height: 3333 }, scaleFactor: 1000 }) const secondaryDisplay = makeDisplay({ size: { width: 100, height: 200 }, scaleFactor: 2.5 }) const screen = makeScreen({ primaryDisplay }) const { sendEvent, sendSession } = makeClient({ screen }) await nextTick() const expectedEvent = makeExpectedEventDevice() const expectedSession = makeExpectedSessionDevice() const event = await sendEvent() expect(event.device).toEqual(expectedEvent) const session = await sendSession() expect(session.device).toEqual(expectedSession) screen._emit('display-metrics-changed', secondaryDisplay, ['bounds', 'scaleFactor']) const event2 = await sendEvent() expect(event2.device).toEqual(expectedEvent) const session2 = await sendSession() expect(session2.device).toEqual(expectedSession) }) it('does not update screen information if the update is not relevant', async () => { const screen = makeScreen() const NativeClient = makeNativeClient() const { sendEvent, sendSession } = makeClient({ screen, NativeClient }) expect(NativeClient.setDevice).toHaveBeenCalledTimes(1) const event = await sendEvent() expect(event.device).toEqual(makeExpectedEventDevice()) const session = await sendSession() expect(session.device).toEqual(makeExpectedSessionDevice()) screen._emit('display-metrics-changed', makeDisplay({ rotation: 270 }), ['rotation']) expect(NativeClient.setDevice).toHaveBeenCalledTimes(1) }) it('reports correct device.id when one has been cached', async () => { const id = 'aoidjoahefodhadowhjoawjdopajp' const filestore = makeFilestore(id) const { sendEvent, sendSession } = makeClient({ filestore }) await nextTick() const event = await sendEvent() expect(event.device).toEqual(makeExpectedEventDevice({ id })) const session = await sendSession() expect(session.device).toEqual(makeExpectedSessionDevice({ id })) }) it('does not add device.id when one is not created', async () => { const filestore = { getDeviceInfo: jest.fn().mockReturnValue({}) } // @ts-expect-error const { sendEvent, sendSession } = makeClient({ filestore }) await nextTick() const event = await sendEvent() expect(event.device).toEqual(makeExpectedEventDevice({ id: undefined })) expect(event.device).not.toHaveProperty('id') const session = await sendSession() expect(session.device).toEqual(makeExpectedSessionDevice({ id: undefined })) expect(session.device).not.toHaveProperty('id') }) it('handles filestore errors from getDeviceInfo()', async () => { const filestore = { getDeviceInfo () { throw new Error('insert disk 2') }, setDeviceInfo (deviceInfo: Record<string, unknown>) {} } const { client, sendEvent, sendSession } = makeClient({ filestore }) await nextTick() const expectedEvent = makeExpectedEventDevice({ id: undefined }) const expectedSession = makeExpectedSessionDevice({ id: undefined }) const event = await sendEvent() expect(event.device).toEqual(expectedEvent) const session = await sendSession() expect(session.device).toEqual(expectedSession) expect(client._logger.error).toHaveBeenCalledTimes(1) expect(client._logger.error).toHaveBeenCalledWith(new Error('insert disk 2')) }) it('records initial battery and locked state', async () => { const powerMonitor = makePowerMonitor({ usingBattery: true, isLocked: true }) const { sendEvent, sendSession } = makeClient({ powerMonitor }) await nextTick() const expectedMetadata = makeExpectedMetadataDevice({ usingBattery: true, isLocked: true }) const event = await sendEvent() expect(event.device).toEqual(makeExpectedEventDevice()) expect(event.getMetadata('device')).toEqual(expectedMetadata) const session = await sendSession() expect(session.device).toEqual(makeExpectedSessionDevice()) }) it('records changes to battery state', async () => { const powerMonitor = makePowerMonitor() const { sendEvent } = makeClient({ powerMonitor }) await nextTick() const event = await sendEvent() expect(event.getMetadata('device')).toEqual(makeExpectedMetadataDevice({ usingBattery: false })) powerMonitor._emit('on-battery') const event2 = await sendEvent() expect(event2.getMetadata('device')).toEqual(makeExpectedMetadataDevice({ usingBattery: true })) powerMonitor._emit('on-ac') const event3 = await sendEvent() expect(event3.getMetadata('device')).toEqual(makeExpectedMetadataDevice({ usingBattery: false })) }) it('records changes to locked state', async () => { const powerMonitor = makePowerMonitor() const { sendEvent } = makeClient({ powerMonitor }) await nextTick() const event = await sendEvent() expect(event.getMetadata('device')).toEqual(makeExpectedMetadataDevice({ isLocked: false })) powerMonitor._emit('lock-screen') const event2 = await sendEvent() expect(event2.getMetadata('device')).toEqual(makeExpectedMetadataDevice({ isLocked: true })) powerMonitor._emit('unlock-screen') const event3 = await sendEvent() expect(event3.getMetadata('device')).toEqual(makeExpectedMetadataDevice({ isLocked: false })) }) it('records the system idle time', async () => { const powerMonitor = makePowerMonitor({ idleTime: 1234 }) const { sendEvent } = makeClient({ powerMonitor }) await nextTick() const event = await sendEvent() expect(event.getMetadata('device')).toEqual(makeExpectedMetadataDevice({ idleTime: 1234 })) }) it('sets user id to device id if no user id is set', async () => { const { sendEvent, sendSession } = makeClient() await nextTick() const event = await sendEvent() expect(event.getUser().id).toBe(DEFAULTS.id) const session = await sendSession() expect(session.getUser().id).toBe(DEFAULTS.id) }) it('doesn’t override user id if user id is already set', async () => { const expectedId = '912837' const { client, sendEvent, sendSession } = makeClient() client.setUser(expectedId, 'tommy@testun.it', 'Tommy T. Unit') await nextTick() const event = await sendEvent() expect(event.getUser().id).toBe(expectedId) const session = await sendSession() expect(session.getUser().id).toBe(expectedId) }) }) // create a stub of '@bugsnag/electron-filestore' function makeFilestore (id: string|null|undefined = DEFAULTS.id) { let _deviceInfo: Record<string, unknown> = { id } return { getDeviceInfo (): { id?: string|null } { return _deviceInfo }, setDeviceInfo (deviceInfo: Record<string, unknown>) { _deviceInfo = deviceInfo } } } function makeNativeClient () { return { setDevice: jest.fn() } }
the_stack
import { getTestResourceUrl, silenceLoggingAroundFunction } from "@here/harp-test-utils"; import { LogLevel } from "@here/harp-utils"; import { assert } from "chai"; import { ImageItem } from "../lib/image/Image"; import { ImageCache } from "../lib/image/ImageCache"; import { MapViewImageCache } from "../lib/image/MapViewImageCache"; // Mocha discourages using arrow functions, see https://mochajs.org/#arrow-functions class ImageData { constructor(public width: number, public height: number) {} close() { /* mock only */ } } function getNameCount(imageCache: MapViewImageCache): number { return (imageCache as any).m_name2Url.size; } function clearCache() { (ImageCache.instance as any).m_images.clear(); } describe("MapViewImageCache", function () { beforeEach(function () { clearCache(); }); it("#empty", function () { const cache = new MapViewImageCache(); assert.equal(getNameCount(cache), 0); assert.notExists(cache.findImageByName("xxx")); }); it("#addImage with data", function () { const cache = new MapViewImageCache(); const imageData = new ImageData(16, 16); cache.addImage("testImage", imageData); const testImage1 = cache.findImageByName("testImage"); assert.equal(getNameCount(cache), 1); assert.notExists(cache.findImageByName("xxx")); assert.exists(testImage1); assert.equal(imageData, testImage1!.image); }); it("#addImage with url", function () { const cache = new MapViewImageCache(); cache.clear(); const imageName = "headshot.png"; const imageUrl = getTestResourceUrl("@here/harp-mapview", "test/resources/headshot.png"); const imageItem = cache.addImage(imageName, imageUrl, false); assert.isDefined(imageItem); assert.isFalse(imageItem instanceof Promise); const testImage = cache.findImageByName(imageName); assert.exists(testImage); assert.isUndefined(testImage!.image); assert.isFalse(testImage!.loaded); }); if (typeof document !== "undefined") { it("#addImage with load", async function () { this.timeout(5000); const cache = new MapViewImageCache(); cache.clear(); const imageName = "headshot.png"; const imageUrl = getTestResourceUrl( "@here/harp-mapview", "test/resources/headshot.png" ); const promise = cache.addImage(imageName, imageUrl, true); const testImage = cache.findImageByName(imageName); assert.exists(testImage); assert.isUndefined(testImage!.image); assert.isFalse(testImage!.loaded); assert.isTrue(promise instanceof Promise); if (promise instanceof Promise) { await promise; const loadedImageItem = cache.findImageByName(imageName); assert.exists(loadedImageItem); assert.isDefined(loadedImageItem!.image); assert.isTrue(loadedImageItem!.loaded); const image = loadedImageItem!.image!; assert.equal(image.width, 37); assert.equal(image.height, 32); } }); it("#addImage (load cancelled)", async function () { this.timeout(5000); const cache = new MapViewImageCache(); cache.clear(); const imageName = "headshot.png"; const imageUrl = getTestResourceUrl( "@here/harp-mapview", "test/resources/headshot.png" ); const promise = cache.addImage(imageName, imageUrl, true); const testImage = cache.findImageByName(imageName); assert.exists(testImage); assert.isUndefined(testImage!.image); assert.isFalse(testImage!.loaded); assert.isTrue(promise instanceof Promise); // removal leads to cancel assert.isTrue(cache.removeImage(imageName), "remove failed"); if (promise instanceof Promise) { const imageItem = cache.findImageByName(imageName); assert.notExists(imageItem, "image is still in cache"); assert.isTrue(testImage!.cancelled); // result of promise ignored, it depends on timing of load and image generation: await promise; // only assured that cancelled is set to `true`, loaded may also be set to true if // cancelled after/during image generation. assert.isTrue(testImage!.cancelled); } }); it("#loadImage", async function () { const cache = new MapViewImageCache(); cache.clear(); const imageName = "headshot.png"; const imageUrl = getTestResourceUrl( "@here/harp-mapview", "test/resources/headshot.png" ); const imageItem: ImageItem = cache.addImage(imageName, imageUrl, false) as ImageItem; assert.isDefined(imageItem); assert.isFalse(imageItem instanceof Promise); assert.isUndefined(imageItem.image); assert.isFalse(imageItem!.loaded); const promise = imageItem.loadImage(); assert.isTrue(promise instanceof Promise); if (promise instanceof Promise) { await promise; const loadedImageItem = cache.findImageByName(imageName); assert.exists(loadedImageItem); assert.isDefined(loadedImageItem!.image); assert.isTrue(loadedImageItem!.loaded); const image = loadedImageItem!.image!; assert.equal(image.width, 37); assert.equal(image.height, 32); } }); } it("#clear", function () { const cache = new MapViewImageCache(); const imageData = new ImageData(16, 16); cache.addImage("testImage", imageData); cache.addImage("testImage2", imageData); assert.equal(getNameCount(cache), 2); cache.clear(); assert.equal(ImageCache.instance.size, 0, "wrong cache size"); assert.equal(getNameCount(cache), 0, "wrong number of names"); }); it("#add images", function () { const cache = new MapViewImageCache(); const imageData1 = new ImageData(16, 16); const imageData2 = new ImageData(32, 32); cache.addImage("testImage1", imageData1); cache.addImage("testImage2", imageData2); const testImage1 = cache.findImageByName("testImage1"); const testImage2 = cache.findImageByName("testImage2"); assert.equal(getNameCount(cache), 2); assert.exists(testImage1); assert.equal(imageData1, testImage1!.image); assert.exists(testImage2); assert.equal(imageData2, testImage2!.image); }); it("#add images with same url but differing names", function () { const cache = new MapViewImageCache(); cache.addImage("testImage1", "httpx://naxos.de", false); cache.addImage("testImage2", "httpx://naxos.de", false); const testImage1 = cache.findImageByName("testImage1"); const testImage2 = cache.findImageByName("testImage2"); assert.equal(getNameCount(cache), 2, "should have 2 names"); assert.exists(testImage1); assert.exists(testImage2); assert.deepEqual(testImage1, testImage2); }); it("#add images with same name but differing urls", function () { const cache = new MapViewImageCache(); assert.throws(() => { cache.addImage("testImage", "httpx://naxos.de", false); cache.addImage("testImage", "httpx://naxos.de-2", false); }); }); it("#remove image", function () { const cache = new MapViewImageCache(); const imageData1 = new ImageData(16, 16); cache.addImage("testImage1", imageData1); assert.exists(cache.findImageByName("testImage1")); assert.equal(ImageCache.instance.size, 1); assert.equal(getNameCount(cache), 1, "wrong number of names"); const imageRemoved = cache.removeImage("testImage1"); assert.equal(imageRemoved, true); assert.equal(getNameCount(cache), 0, "wrong number of names"); }); it("#remove image 2", function () { const cache = new MapViewImageCache(); cache.addImage("testImage1", "httpx://naxos.de", false); cache.addImage("testImage2", "httpx://naxos.de", false); assert.exists(cache.findImageByName("testImage1")); assert.exists(cache.findImageByName("testImage2")); assert.equal(ImageCache.instance.size, 1, "wrong cache size"); assert.equal(getNameCount(cache), 2, "wrong number of names"); const imageRemoved = cache.removeImage("testImage2"); assert.equal(imageRemoved, true); assert.equal(ImageCache.instance.size, 1, "wrong cache size"); assert.equal(getNameCount(cache), 1, "wrong number of names"); assert.exists(cache.findImageByName("testImage1")); }); it("#remove image by name", function () { const cache = new MapViewImageCache(); const imageData1 = new ImageData(16, 16); const imageData2 = new ImageData(32, 32); cache.addImage("testImage1", imageData1); cache.addImage("testImage2", imageData2); assert.equal(ImageCache.instance.size, 2); const imageRemoved = cache.removeImage("testImage1"); assert.equal(imageRemoved, true); assert.equal(getNameCount(cache), 1, "wrong number of names"); assert.equal(ImageCache.instance.size, 1); }); it("#remove non-existent image returns false", function () { const cache = new MapViewImageCache(); assert.equal(cache.removeImage("xxx"), false); }); }); describe("ImageCache", function () { beforeEach(function () { clearCache(); }); it("#instance", function () { const cache = ImageCache.instance; const instance2 = ImageCache.instance; assert.exists(cache); assert.equal(cache, instance2); }); it("#empty", function () { const cache = ImageCache.instance; assert.equal(cache.size, 0); const found = cache.findImage("xxx"); assert.notExists(found); }); it("#registerImage", function () { const owner = new MapViewImageCache(); const cache = ImageCache.instance; const imageData = new ImageData(16, 16); cache.registerImage(owner, "httpx://naxos.de", imageData); const testImage = cache.findImage("httpx://naxos.de"); assert.equal(cache.size, 1); assert.notExists(cache.findImage("xxx")); assert.exists(testImage); assert.equal(imageData, testImage!.image); }); if (typeof document !== "undefined") { const canvas = document.createElement("canvas"); canvas.width = 37; canvas.height = 32; var ctx = canvas.getContext("2d"); if (ctx) { ctx.fillStyle = "#00FF00"; ctx.fillRect(0, 0, 37, 32); } const image = document.createElement("img"); image.src = getTestResourceUrl("@here/harp-mapview", "test/resources/headshot.png"); it("#addImage, from url", async function () { const owner = new MapViewImageCache(); const cache = ImageCache.instance; const imageUrl = getTestResourceUrl( "@here/harp-mapview", "test/resources/headshot.png" ); const promise = cache.registerImage(owner, imageUrl).loadImage(); const testImage = cache.findImage(imageUrl); assert.exists(testImage); assert.isUndefined(testImage!.image); assert.isFalse(testImage!.loaded); assert.isTrue(promise instanceof Promise); if (promise instanceof Promise) { await promise; const loadedImageItem = cache.findImage(imageUrl); assert.exists(loadedImageItem); assert.isDefined(loadedImageItem!.image); assert.isTrue(loadedImageItem!.loaded); const image = loadedImageItem!.image!; assert.equal(image.width, 37); assert.equal(image.height, 32); } }); it("#loadImage, from url", async function () { const owner = {}; const cache = ImageCache.instance; const imageUrl = getTestResourceUrl( "@here/harp-mapview", "test/resources/headshot.png" ); const cacheItem = cache.registerImage(owner, imageUrl, undefined); const testImage = cache.findImage(imageUrl); assert.exists(testImage); assert.isUndefined(testImage!.image); assert.isFalse(testImage!.loaded); const promise = cacheItem.loadImage(); assert.isTrue(promise instanceof Promise); if (promise instanceof Promise) { await promise; const loadedImageItem = cache.findImage(imageUrl); assert.exists(loadedImageItem); assert.isDefined(loadedImageItem!.image); assert.isTrue(loadedImageItem!.loaded); const image = loadedImageItem!.image!; assert.equal(image.width, 37); assert.equal(image.height, 32); } }); [ { element: canvas, name: "HtmlCanvasElement" }, { element: image, name: "HtmlImageElement" } ].forEach(testSetting => { it("#loadImage, from htmlElement " + testSetting.name, async function () { const owner = {}; const cache = ImageCache.instance; const imageUrl = "htmlElementImage"; const testImage = cache.registerImage(owner, imageUrl, testSetting.element); assert.exists(testImage); assert.isDefined(testImage!.image); assert.isFalse(testImage!.loaded); assert.equal(testImage!.image!.width, 37); assert.equal(testImage!.image!.height, 32); const promise = testImage.loadImage(); assert.isTrue(promise instanceof Promise); if (promise instanceof Promise) { await promise; const loadedImageItem = cache.findImage(imageUrl); assert.exists(loadedImageItem); assert.isDefined(loadedImageItem!.image); assert.isTrue(loadedImageItem!.loaded); const image = loadedImageItem!.image!; assert.equal(image.width, 37); assert.equal(image.height, 32); assert.isDefined(loadedImageItem!.mipMaps); assert.isNotEmpty(loadedImageItem!.mipMaps); } }); }); it("#loadImage, from bad url", async function () { this.timeout(5000); const owner = {}; const cache = ImageCache.instance; const imageUrl = "?"; const imageItem = cache.registerImage(owner, imageUrl) as ImageItem; assert.isDefined(imageItem); assert.isFalse(imageItem instanceof Promise); assert.isUndefined(imageItem.image); assert.isFalse(imageItem!.loaded); const promise = imageItem.loadImage(); const isPromise = promise instanceof Promise; assert.isTrue(isPromise); if (promise instanceof Promise) { await silenceLoggingAroundFunction( "loadImage", async () => { await promise.catch(() => { assert.isRejected(promise); const loadedImageItem = cache.findImage(imageUrl); assert.exists(loadedImageItem); assert.isUndefined(loadedImageItem!.image); assert.isFalse(loadedImageItem!.loaded); }); }, LogLevel.None ); } }); it("#loadImage, from bad HtmlImageElement", async function () { const url = "dummy"; const badImage = document.createElement("img"); badImage.src = "bad source"; const owner = {}; const cache = ImageCache.instance; const testImage = cache.registerImage(owner, url, badImage); assert.exists(testImage); assert.isDefined(testImage!.image); assert.isFalse(testImage!.loaded); const result = testImage.loadImage(); assert.isTrue(result instanceof Promise); const promise = result as Promise<ImageItem | undefined>; assert.isRejected(promise); }); } it("#dispose", function () { const owner = new MapViewImageCache(); const imageData = new ImageData(16, 16); ImageCache.instance.registerImage(owner, "httpx://naxos.de", imageData); ImageCache.dispose(); assert.equal(ImageCache.instance.size, 0); }); it("#register same image in multiple MapViews", function () { const cache = ImageCache.instance; const owner1 = new MapViewImageCache(); const owner2 = new MapViewImageCache(); const imageData1 = new ImageData(16, 16); cache.registerImage(owner1, "httpx://naxos.de", imageData1); cache.registerImage(owner2, "httpx://naxos.de", imageData1); const testImage = cache.findImage("httpx://naxos.de"); assert.equal(cache.size, 1); assert.notExists(cache.findImage("xxx")); assert.exists(testImage); assert.equal(imageData1, testImage!.image); }); it("#register different images in multiple MapViews", function () { const cache = ImageCache.instance; const owner1 = new MapViewImageCache(); const owner2 = new MapViewImageCache(); const imageData1 = new ImageData(16, 16); const imageData2 = new ImageData(32, 32); cache.registerImage(owner1, "httpx://naxos.de", imageData1); cache.registerImage(owner2, "httpx://naxos.de-2", imageData2); const testImage1 = cache.findImage("httpx://naxos.de"); const testImage2 = cache.findImage("httpx://naxos.de-2"); assert.equal(cache.size, 2); assert.notExists(cache.findImage("xxx")); assert.exists(testImage1); assert.equal(imageData1, testImage1!.image); assert.exists(testImage2); assert.equal(imageData2, testImage2!.image); }); it("#clear images in multiple MapViews", function () { const cache = ImageCache.instance; const owner1 = new MapViewImageCache(); const owner2 = new MapViewImageCache(); const imageData1 = new ImageData(16, 16); const imageData2 = new ImageData(32, 32); cache.registerImage(owner1, "httpx://naxos.de", imageData1); cache.registerImage(owner2, "httpx://naxos.de-2", imageData2); cache.clear(owner1); assert.equal(cache.size, 1); assert.notExists(cache.findImage("httpx://naxos.de")); assert.exists(cache.findImage("httpx://naxos.de-2")); }); it("#remove image", function () { const cache = ImageCache.instance; const owner1 = new MapViewImageCache(); const imageData1 = new ImageData(16, 16); cache.registerImage(owner1, "httpx://naxos.de", imageData1); assert.equal(cache.size, 1, "wrong cache size"); const imageRemoved = cache.removeImage("httpx://naxos.de", owner1); assert.equal(imageRemoved, true); assert.equal(cache.size, 0, "wrong cache size"); }); it("#clear images shared in multiple MapViews", function () { const owner1 = new MapViewImageCache(); const owner2 = new MapViewImageCache(); const cache0 = ((owner1 as any).imageCache = new MapViewImageCache()); const cache1 = ((owner2 as any).imageCache = new MapViewImageCache()); const imageData1 = new ImageData(16, 16); const imageData2 = new ImageData(32, 32); cache0.addImage("img0", imageData1); cache0.addImage("img1", imageData2); cache1.addImage("img0", imageData1); cache1.addImage("img1", imageData2); assert.equal(ImageCache.instance.size, 2); assert.equal(getNameCount(cache0), 2); assert.equal(getNameCount(cache1), 2); cache0.clear(); assert.equal(ImageCache.instance.size, 2); assert.equal(getNameCount(cache0), 0); assert.equal(getNameCount(cache1), 2); cache1.clear(); assert.equal(ImageCache.instance.size, 0); assert.equal(getNameCount(cache1), 0); }); it("#share images in multiple MapViews", function () { const cache0 = new MapViewImageCache(); const cache1 = new MapViewImageCache(); const imageData1 = new ImageData(16, 16); const imageData2 = new ImageData(32, 32); const imageItem0 = cache0.addImage("img0", imageData1); const imageItem1 = cache0.addImage("img1", imageData2); cache1.addImage("img0", imageData1); cache1.addImage("img1", imageData2); assert.equal(imageItem0, cache0.findImageByName("img0")); assert.equal(imageItem1, cache0.findImageByName("img1")); assert.equal(imageItem0, cache1.findImageByName("img0")); assert.equal(imageItem1, cache1.findImageByName("img1")); }); it("#remove images shared in multiple MapViews", function () { const cache0 = new MapViewImageCache(); const cache1 = new MapViewImageCache(); const imageData1 = new ImageData(16, 16); const imageData2 = new ImageData(32, 32); cache0.addImage("img0", imageData1); cache0.addImage("img1", imageData2); cache1.addImage("img0", imageData1); cache1.addImage("img1", imageData2); assert.equal(ImageCache.instance.size, 2); assert.isTrue(cache0.removeImage("img0")); assert.equal(ImageCache.instance.size, 2); assert.isTrue(cache1.removeImage("img0")); assert.equal(ImageCache.instance.size, 1); assert.isTrue(cache0.removeImage("img1")); assert.equal(ImageCache.instance.size, 1); assert.isTrue(cache1.removeImage("img1")); assert.equal(ImageCache.instance.size, 0); }); });
the_stack
* ModifySmsTemplate返回参数结构体 */ export interface ModifySmsTemplateResponse { /** * 返回 */ Data?: ModifySmsTemplateDataStruct /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 添加短信人群包信息接口返回 */ export interface SmsAddCrowdPackInfoResponse { /** * 人群包id */ ID: number } /** * PushMmsContent返回参数结构体 */ export interface PushMmsContentResponse { /** * 推送短信返回信息 */ Data?: PushMmsContentResp /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 短信模板创建接口返回 */ export interface AddSmsTemplateDataStruct { /** * 短信模板ID */ TemplateId: number } /** * DescribeMmsInstanceList请求参数结构体 */ export interface DescribeMmsInstanceListRequest { /** * 商户证书 */ License: string /** * 偏移量 */ Offset: number /** * 返回数量 */ Limit: number /** * 业务代码 */ AppSubId?: string /** * 实例标题 */ Title?: string } /** * DescribeMmsInstanceInfo返回参数结构体 */ export interface DescribeMmsInstanceInfoResponse { /** * 彩信实例信息 */ Data?: MmsInstanceInfo /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 发送短信返回 */ export interface SendSmsPaasDataStruct { /** * 发送流水号 */ SerialNo: string /** * 手机号码,e.164标准,+[国家或地区码][手机号] ,示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号。 */ PhoneNumber: string /** * 计费条数 */ Fee: number /** * OK为成功 */ Code: string /** * 短信请求错误码描述 */ Message: string } /** * AddCrowdPackInfo返回参数结构体 */ export interface AddCrowdPackInfoResponse { /** * 接口返回 */ Data?: SmsAddCrowdPackInfoResponse /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * AddSmsSign请求参数结构体 */ export interface AddSmsSignRequest { /** * 商户证书 */ License: string /** * 签名类型。其中每种类型后面标注了其可选的 DocumentType(证明类型): 0:公司(0,1,2,3)。 1:APP(0,1,2,3,4) 。 2:网站(0,1,2,3,5)。 3:公众号或者小程序(0,1,2,3,6)。 4:商标(7)。 5:政府/机关事业单位/其他机构(2,3)。 注:必须按照对应关系选择证明类型,否则会审核失败。 */ SignType: number /** * 证明类型: 0:三证合一。 1:企业营业执照。 2:组织机构代码证书。 3:社会信用代码证书。 4:应用后台管理截图(个人开发APP)。 5:网站备案后台截图(个人开发网站)。 6:小程序设置页面截图(个人认证小程序)。 7:商标注册书 */ DocumentType: number /** * 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ International: number /** * 资质图片url */ ProofImage: string /** * 签名内容 */ SignName: string /** * 签名备注,比如申请原因,使用场景等,可以填空 */ Remark?: string } /** * AddSmsSign返回参数结构体 */ export interface AddSmsSignResponse { /** * 签名id数组 */ Data?: PaasCreateSignResp /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * GetSmsCampaignStatus请求参数结构体 */ export interface GetSmsCampaignStatusRequest { /** * 商户证书 */ License: string /** * 活动ID */ CampaignId: number } /** * DescribeSmsTemplateList返回参数结构体 */ export interface DescribeSmsTemplateListResponse { /** * 返回数据信息 */ Data?: Array<DescribeSmsTemplateListDataStruct> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 彩信实例状态列表 */ export interface MmsInstanceInfoList { /** * 总数据量 */ Total: number /** * 彩信实例状态信息列表 */ List: Array<MmsInstanceInfo> } /** * GetCrowdPackList返回参数结构体 */ export interface GetCrowdPackListResponse { /** * 人群包信息列表 */ Data?: SmsGetCrowdPackListResponse /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 创建超级短信样例返回结果 */ export interface CreateMmsInstanceResp { /** * 返回码:0-成功 其它-失败 */ ReturnCode: number /** * 返回信息 */ ReturnMsg: string /** * 样例id */ InstanceId: number } /** * AddSmsTemplate请求参数结构体 */ export interface AddSmsTemplateRequest { /** * 商户证书 */ License: string /** * 短信签名,创建签名时返回 */ SignID: number /** * 模板名称 */ TemplateName: string /** * 短信内容,动态内容使用占位符{1},{2}等表示 */ TemplateContent: string /** * 短信类型:{0:普通短信,1:营销短信} */ SmsType: number /** * 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ International: number /** * 短信模板标签 */ Remark: string /** * 发送短信活动时配置的落地链接地址,仅用作短信活动 */ Urls?: Array<string> /** * 发送短信活动时用于展示人群包动态参数模板占位符序号或接口发送时变量占位符序号 */ CommonParams?: Array<number> /** * 发送短信活动时用于展示短连接模板占位符序号,仅用作短信活动 */ UrlParams?: Array<number> } /** * DescribeMmsInstanceInfo请求参数结构体 */ export interface DescribeMmsInstanceInfoRequest { /** * 商户证书 */ License: string /** * 彩信实例id */ InstanceId: number } /** * CreateCampaign返回参数结构体 */ export interface CreateCampaignResponse { /** * 活动信息 */ Data?: SmsCreateCampaignResponse /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 发送超级短信返回 */ export interface PushMmsContentResp { /** * 返回码:0-成功 其它-失败 */ ReturnCode: number /** * 返回信息 */ ReturnMsg: string /** * 消息回执id */ MessageId: number } /** * 接口返回给服务商的COS路径等信息 */ export interface UploadFansInfoCosInfo { /** * COS bucket */ Bucket: string /** * COS路径 */ Key: string /** * COS区域 */ Region: string } /** * CreateCampaign请求参数结构体 */ export interface CreateCampaignRequest { /** * 商户证书 */ License: string /** * 短信活动发送时间 */ SendTime: number /** * 短信活动名称 */ Name: string /** * 发送策略 */ Strategies?: Array<PaasStrategy> /** * 废弃 */ TemplateId?: number /** * 废弃 */ CrowdID?: number /** * 活动类型(0-短信,1-超短,不填默认为超短) */ SmsType?: number } /** * 短信子账号额度接口出参 */ export interface SmsAmountDataStruct { /** * 短信活动配额 */ SmsCampaignAmount: number /** * 短信活动消耗配额 */ SmsCampaignConsume: number /** * 短信发送额度 */ SmsSendAmount: number /** * 短信发送消耗额度 */ SmsSendConsume: number /** * 超短活动额度 */ MmsCampaignAmount: number /** * 超短活动消耗额度 */ MmsCampaignConsume: number /** * 超短短信额度 */ MmsSendAmount: number /** * 超短短信消耗额度 */ MmsSendConsume: number } /** * AddCrowdPackInfo请求参数结构体 */ export interface AddCrowdPackInfoRequest { /** * 商户证书 */ License: string /** * 人群包名称 */ Name: string /** * 人群包文件名称,人群包文件必须为utf8编码,动态参数只能是汉字、数字、英文字母的组合,不能包含其他字符 */ FileName: string /** * 人群包描述 */ Desc: string /** * 已经上传好的人群包cos地址 */ CosUrl: string /** * 人群包手机号数量 */ PhoneNum?: number } /** * 短信api成功返回信息 */ export interface SmsSuccessResponse { /** * 成功返回信息 */ Message: string } /** * 短信人群包返回信息 */ export interface SmsGetCrowdPackListResponse { /** * 人群包总数 */ Total: number /** * 人群包返回数据列表 注意:此字段可能返回 null,表示取不到有效值。 */ List: Array<SmsGetCrowdPackList> } /** * 获取短信模板状态返回 */ export interface DescribeSmsTemplateListDataStruct { /** * 模板Id */ TemplateId: number /** * 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ International: number /** * 申请签名状态。其中: 0:表示审核通过。 -1:表示审核未通过或审核失败。 */ StatusCode: number /** * 审核回复,审核人员审核后给出的回复,通常是审核未通过的原因。 */ ReviewReply: string /** * 模板名称。 */ TemplateName: string /** * 提交审核时间,UNIX 时间戳(单位:秒)。 */ CreateTime: number } /** * DeleteMmsInstance返回参数结构体 */ export interface DeleteMmsInstanceResponse { /** * 删除信息返回 */ Data?: DelMmsInstanceData /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifySmsTemplate请求参数结构体 */ export interface ModifySmsTemplateRequest { /** * 商户证书 */ License: string /** * 短信模板id */ TemplateId: number /** * 短信签名,创建签名时返回 */ SignID: number /** * 模板名称 */ TemplateName: string /** * 短信内容,动态内容使用占位符{1},{2}等表示 */ TemplateContent: string /** * 短信类型:{0:普通短信,1:营销短信} */ SmsType: number /** * 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ International: number /** * 短信模板标签 */ Remark: string /** * 发送短信活动时配置的落地链接地址,仅用作短信活动 */ Urls?: Array<string> /** * 发送短信活动时用于展示人群包动态参数模板占位符序号,仅用作短信活动 */ CommonParams?: Array<number> /** * 发送短信活动时用于展示短连接模板占位符序号,仅用作短信活动 */ UrlParams?: Array<number> } /** * 彩信实例审核状态 */ export interface MmsInstanceStateInfo { /** * 运营商 */ Operator: string /** * 审核状态:0未审核,1审核通过,2审核拒绝 */ State: number } /** * 取消活动的返回值Data部分 */ export interface CancelActivityData { /** * 成功返回时的文字描述 */ Message: string } /** * SendSms返回参数结构体 */ export interface SendSmsResponse { /** * 出参数据 */ Data?: Array<SendSmsPaasDataStruct> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 短信发送人群包策略 */ export interface PaasStrategy { /** * 人群包id */ CrowdID: number /** * 待选素材数组 */ Items: Array<PaasStrategyItem> } /** * CancelCampaign返回参数结构体 */ export interface CancelCampaignResponse { /** * 处理结果 */ Data?: CancelActivityData /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 短信活动统计人群包数据 */ export interface SmsCampaignStatisticsCrowdData { /** * 人群包id */ CrowdId: number /** * 人群包名称 */ CrowdName: string /** * 人群包目标触达总数 */ CrowdCount: number /** * 模板列表 */ TemplateList: Array<SmsCampaignStatisticsTemplateData> } /** * DescribeSmsSignList请求参数结构体 */ export interface DescribeSmsSignListRequest { /** * 商户证书 */ License: string /** * 签名ID数组 */ SignIdSet: Array<number> /** * 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ International: number } /** * GetCrowdUploadInfo返回参数结构体 */ export interface GetCrowdUploadInfoResponse { /** * 返回信息 */ Data?: SmsGetCrowdUploadInfoResponse /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 短信获取人群包列表的返回数据信息 */ export interface SmsGetCrowdPackList { /** * 创建时间 */ CreatedAt: string /** * 人群包id */ ID: number /** * 人群包名称 */ Name: string /** * 人群包状态 */ Status: number /** * 人群包手机号数量 */ PhoneNum: number /** * 人群包标签信息 */ Tag: string /** * 人群包md5 */ MD5: string /** * 人群包文件名称 */ FileName: string /** * 人群包描述 */ Desc: string } /** * GetSmsAmountInfo返回参数结构体 */ export interface GetSmsAmountInfoResponse { /** * 短信账号额度接口 */ Data?: SmsAmountDataStruct /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 获取普通短信签名信息返回信息 */ export interface DescribeSmsSignListDataStruct { /** * 签名Id */ SignId: number /** * 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ International: number /** * 申请签名状态。其中: 0:表示审核通过。 -1:表示审核未通过或审核失败。 */ StatusCode: number /** * 审核回复,审核人员审核后给出的回复,通常是审核未通过的原因。 */ ReviewReply: string /** * 签名名称。 */ SignName: string /** * 提交审核时间,UNIX 时间戳(单位:秒)。 */ CreateTime: number } /** * GetCrowdPackList请求参数结构体 */ export interface GetCrowdPackListRequest { /** * 商户证书 */ License: string /** * 偏移量 */ Offset: number /** * 限制返回数量 */ Limit: number /** * 人群包名称,用于过滤人群包 */ Name?: string /** * 人群包状态,默认-1,用于过滤人群包 */ Status?: number } /** * AddSmsTemplate返回参数结构体 */ export interface AddSmsTemplateResponse { /** * 短信模板创建接口返回 */ Data?: AddSmsTemplateDataStruct /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 创建签名返回结构 */ export interface PaasCreateSignResp { /** * 签名id */ SignId: number } /** * 拉取活动状态返回 */ export interface PaasSmsCampaignStatusResp { /** * 0-未发送 1-发送中 2-发送结束 3-发送取消 */ Status: number } /** * DelCrowdPack返回参数结构体 */ export interface DelCrowdPackResponse { /** * 接口返回 */ Data?: SmsSuccessResponse /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DelCrowdPack请求参数结构体 */ export interface DelCrowdPackRequest { /** * 商户证书 */ License: string /** * 人群包id */ ID: number } /** * CreateMmsInstance返回参数结构体 */ export interface CreateMmsInstanceResponse { /** * 创建样例返回信息 */ Data?: CreateMmsInstanceResp /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeSmsTemplateList请求参数结构体 */ export interface DescribeSmsTemplateListRequest { /** * 商户证书 */ License: string /** * 短信模板id数组 */ TemplateIdSet: Array<number> /** * 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。 */ International: number } /** * DeleteMmsInstance请求参数结构体 */ export interface DeleteMmsInstanceRequest { /** * 商户证书 */ License: string /** * 超级短信样例id */ InstanceId: number } /** * 删除超短样例响应 */ export interface DelMmsInstanceData { /** * 样例id */ InstanceId: number } /** * 短信活动策略元素 */ export interface PaasStrategyItem { /** * 短信模板id或超级短信样例id */ Id: number /** * 素材类型 0-普短 1-超短 */ ContentType: number } /** * GetSmsAmountInfo请求参数结构体 */ export interface GetSmsAmountInfoRequest { /** * 商户证书 */ License: string } /** * DelTemplate请求参数结构体 */ export interface DelTemplateRequest { /** * 商户证书 */ License: string /** * 短信模板ID */ TemplateID: number } /** * 创建短信活动返回结构 */ export interface SmsCreateCampaignResponse { /** * 活动id */ CampaignId: number } /** * 短信模板编辑接口出参 */ export interface ModifySmsTemplateDataStruct { /** * 短信模板id 注意:此字段可能返回 null,表示取不到有效值。 */ TemplateId: number } /** * PushMmsContent请求参数结构体 */ export interface PushMmsContentRequest { /** * 商户证书 */ License: string /** * 素材样例id */ InstanceId: number /** * 手机号 */ Tel: string /** * 附带数据字段 */ Session?: string /** * 动态参数key(即申请样例时设置的u_或p_开头的动态参数,要求序号有序) */ DynamicParaKey?: Array<string> /** * 动态参数值,和DynamicParaKey对应 */ DynamicParaValue?: Array<string> } /** * DescribeMmsInstanceList返回参数结构体 */ export interface DescribeMmsInstanceListResponse { /** * 彩信实例信息列表返回 */ Data?: MmsInstanceInfoList /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 创建样例时候content元素 */ export interface CreateMmsInstanceItem { /** * 素材类型:1-文本 2-图片 3-视频 4-音频 */ ContentType: number /** * 素材内容:如果素材是文本类型,直接填写文本内容,否则填写素材文件上传到cos后的url地址 */ Content: string } /** * GetCrowdUploadInfo请求参数结构体 */ export interface GetCrowdUploadInfoRequest { /** * 商户证书 */ License: string /** * 上传文件名称 */ FileName: string } /** * CancelCampaign请求参数结构体 */ export interface CancelCampaignRequest { /** * 商户证书 */ License: string /** * 短信活动id */ CampaignId: number } /** * 短信活动统计响应 */ export interface SmsCampaignStatisticsData { /** * 活动Id */ CampaignId: number /** * 统计数据 */ Statistics: Array<SmsCampaignStatisticsCrowdData> } /** * 彩信实例信息 InstanceId int InstanceName string Status int StatusInfo string AppSubId string Title string Sign string Contents string CreatedAt string */ export interface MmsInstanceInfo { /** * 彩信实例id */ InstanceId: number /** * 彩信实例名称 */ InstanceName: string /** * 状态是否通知 */ Status: number /** * 实例审核状态信息 注意:此字段可能返回 null,表示取不到有效值。 */ StatusInfo: Array<MmsInstanceStateInfo> /** * 业务码 */ AppSubId: string /** * 彩信标题 */ Title: string /** * 签名 */ Sign: string /** * 彩信内容 */ Contents: string /** * 创建时间 */ CreatedAt: string /** * 样例配置的链接地址 注意:此字段可能返回 null,表示取不到有效值。 */ Urls: Array<string> /** * 机型列表 注意:此字段可能返回 null,表示取不到有效值。 */ PhoneType: Array<number> /** * 普通参数序号数组 注意:此字段可能返回 null,表示取不到有效值。 */ CommonParams: Array<number> /** * 链接参数序号数组 注意:此字段可能返回 null,表示取不到有效值。 */ UrlParams: Array<number> } /** * DelTemplate返回参数结构体 */ export interface DelTemplateResponse { /** * 接口返回 */ Data?: SmsSuccessResponse /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 获取短信人群包上传信息返回 */ export interface SmsGetCrowdUploadInfoResponse { /** * 过期时间 */ ExpiredTime: number /** * 会话token */ SessionToken: string /** * 临时密钥id */ TmpSecretId: string /** * 临时密钥 */ TmpSecretKey: string /** * cos信息 */ CosInfo: UploadFansInfoCosInfo } /** * CreateMmsInstance请求参数结构体 */ export interface CreateMmsInstanceRequest { /** * 商户证书 */ License: string /** * 样例名称 */ InstanceName: string /** * 标题 */ Title: string /** * 签名 */ Sign: string /** * 素材内容 */ Contents: Array<CreateMmsInstanceItem> /** * 样例中链接动态变量对应的链接,和占位符顺序一致 */ Urls?: Array<string> /** * 机型列表 */ PhoneType?: Array<number> /** * 发送超短活动时用于展示人群包动态参数模板占位符序号或接口发送时变量占位符序号 */ CommonParams?: Array<number> /** * 发送超短活动时用于展示短连接模板占位符序号,仅用作超短活动 */ UrlParams?: Array<number> } /** * DescribeSmsSignList返回参数结构体 */ export interface DescribeSmsSignListResponse { /** * 返回数据 */ Data?: Array<DescribeSmsSignListDataStruct> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeSmsCampaignStatistics返回参数结构体 */ export interface DescribeSmsCampaignStatisticsResponse { /** * 响应数据 */ Data?: SmsCampaignStatisticsData /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * GetSmsCampaignStatus返回参数结构体 */ export interface GetSmsCampaignStatusResponse { /** * 活动状态 */ Data?: PaasSmsCampaignStatusResp /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeSmsCampaignStatistics请求参数结构体 */ export interface DescribeSmsCampaignStatisticsRequest { /** * 活动id */ CampaignId: number /** * 商户证书 */ License: string } /** * SendSms请求参数结构体 */ export interface SendSmsRequest { /** * 商户证书 */ License: string /** * 手机号码,采用 e.164 标准,格式为+[国家或地区码][手机号],单次请求最多支持200个手机号且要求全为境内手机号,如:+8613800138000 */ Phone: Array<string> /** * 短信模板id(推荐使用模板id发送,使用内容发送时模板id留空) */ TemplateId?: string /** * 模板参数,若无模板参数,则设置为空。 */ Params?: Array<string> /** * 短信签名内容,使用 UTF-8 编码,必须填写已审核通过的签名。注:国内短信为必填参数。 */ Sign?: string /** * 国际/港澳台短信 senderid,国内短信填空 */ SenderId?: string /** * 短信类型:{0:普通短信,1:营销短信},使用内容发送时必填 */ SmsType?: number /** * 是否国际/港澳台短信: 0:表示国内短信。 1:表示国际/港澳台短信。使用内容发送时必填 */ International?: number /** * 发送使用的模板内容,如果有占位符,此处也包括占位符,占位符的实际内容通过Params参数传递,使用模板id发送时此字段为空 */ Content?: string } /** * 短信活动统计模板展示结构 */ export interface SmsCampaignStatisticsTemplateData { /** * 模板或样例id */ TemplateId: string /** * 模板内容 */ TemplateContent: string /** * 触达成功数 */ SendCount: number /** * 短链点击数 */ ClickCount: number }
the_stack
import clone = require('clone'); import agile_keychain = require('./agile_keychain'); import agile_keychain_crypto = require('./agile_keychain_crypto'); import asyncutil = require('./base/asyncutil'); import item_builder = require('./item_builder'); import item_store = require('./item_store'); import key_agent = require('./key_agent'); import sync = require('./sync'); import temp_store = require('./temp_store'); import testLib = require('./test'); interface Env { localStore: temp_store.Store; syncer: sync.Syncer; cloudStore: temp_store.Store; keyAgent: key_agent.KeyAgent; } function setup(): Promise<Env> { const VAULT_PASS = 'testpass'; const VAULT_PASS_ITERATIONS = 100; const VAULT_PASS_HINT = 'testhint'; let keyAgent = new key_agent.SimpleKeyAgent(); let cloudStoreKeyAgent = new key_agent.SimpleKeyAgent(); let cloudStore = new temp_store.Store(cloudStoreKeyAgent, 'Cloud Store'); let localStore = new temp_store.Store(keyAgent, 'Local Store'); let syncer = new sync.CloudStoreSyncer(localStore, cloudStore); return agile_keychain_crypto .generateMasterKey(VAULT_PASS, VAULT_PASS_ITERATIONS) .then(keyList => { let keys = agile_keychain.convertKeys(keyList.list); return asyncutil.all2([ localStore.saveKeys(keys, VAULT_PASS_HINT), cloudStore.saveKeys(keys, VAULT_PASS_HINT), ]); }) .then(() => { return asyncutil.all2([ localStore.unlock(VAULT_PASS), cloudStore.unlock(VAULT_PASS), ]); }) .then(() => { return { localStore: localStore, syncer: syncer, cloudStore: cloudStore, keyAgent: keyAgent, }; }); } // sync items and throw an error if any fail function syncItems(syncer: sync.Syncer) { return syncer.syncItems().then(result => { if (result.failed > 0) { throw new Error(`${result.failed} items failed to sync`); } return result; }); } // create a cloud store, a local store and a syncer. // Add a single item to the cloudStore and the cloudStore, local store, syncer and // a reference to the item in the cloudStore function setupWithItem(): Promise<{ env: Env; item: item_store.Item }> { var env: Env; var item = new item_builder.Builder(item_store.ItemTypes.LOGIN) .setTitle('sync me') .addLogin('jim@acme.org') .addUrl('acme.org') .item(); return setup() .then(_env => { env = _env; return item.saveTo(env.cloudStore); }) .then(() => { return { env: env, item: item, }; }); } testLib.addTest('sync keys and password hint from cloud to local', assert => { let env: Env; return setup() .then(_env => { env = _env; return env.syncer.syncKeys(); }) .then(() => { return asyncutil.all2([ env.localStore.listKeys(), env.localStore.passwordHint(), ]); }) .then(keyAndHint => { let keys = <key_agent.Key[]>keyAndHint[0]; let hint = <string>keyAndHint[1]; assert.equal(keys.length, 1); assert.equal(hint, 'testhint'); }); }); testLib.addTest('sync keys without hint', assert => { let env: Env; return setup() .then(_env => { env = _env; // verify that syncing keys succeeds if the password // hint is not available env.cloudStore.passwordHint = () => { return Promise.reject<string>(new Error('Fail to fetch hint')); }; }) .then(() => { return env.syncer.syncKeys(); }) .then(() => { return asyncutil.all2([ env.localStore.listKeys(), env.localStore.passwordHint(), ]); }) .then((keysAndHint: [key_agent.Key[], string]) => { assert.equal(keysAndHint[0].length, 1); assert.equal(keysAndHint[1], ''); }); }); testLib.addTest('sync items from cloud to local', assert => { var env: Env; // 1. save a new item to the cloudStore var item = new item_builder.Builder(item_store.ItemTypes.LOGIN) .setTitle('sync me') .addLogin('testuser@gmail.com') .addUrl('accounts.google.com') .item(); return setup() .then(_env => { env = _env; return item.saveTo(env.cloudStore); }) .then(() => { // 2. sync and verify that the updated items were // synced to the local store return syncItems(env.syncer); }) .then(syncStats => { assert.equal(syncStats.updated, 1); assert.equal(syncStats.total, 1); return env.localStore.listItems(); }) .then(storeItems => { // 3. update the item in the cloudStore, sync again // and verify that the updates are synced // to the local store assert.equal(storeItems.length, 1); assert.equal(storeItems[0].title, item.title); assert.ok( sync.itemUpdateTimesEqual( storeItems[0].createdAt, item.createdAt ) ); assert.deepEqual(storeItems[0].locations, item.locations); return storeItems[0].getContent(); }) .then(content => { // 3.1. Check that the encrypted content was synced // successfully testLib.assertEqual(assert, content.formFields, [ { id: '', name: 'username', type: item_store.FormFieldType.Text, designation: 'username', value: 'testuser@gmail.com', }, ]); item.title = 'sync me - updated'; return item.save(); }) .then(() => { return syncItems(env.syncer); }) .then(syncStats => { assert.equal(syncStats.updated, 1); assert.equal(syncStats.total, 1); return env.localStore.listItems(); }) .then(storeItems => { assert.equal(storeItems.length, 1); assert.equal(storeItems[0].title, item.title); }); }); testLib.addTest('sync items from local to cloud', assert => { var env: Env; // 1. Save a new item to the store var item = new item_builder.Builder(item_store.ItemTypes.LOGIN) .setTitle('store item') .addLogin('testuser2@gmail.com') .addUrl('acme.org') .item(); return setup() .then(_env => { env = _env; return item.saveTo(env.localStore); }) .then(() => { // 2. Sync and verify that item was added to the cloud store return syncItems(env.syncer); }) .then(syncStats => { assert.equal(syncStats.updated, 1); assert.equal(syncStats.total, 1); return env.cloudStore.listItems(); }) .then(vaultItems => { assert.equal(vaultItems.length, 1); assert.equal(vaultItems[0].title, item.title); assert.ok( sync.itemUpdateTimesEqual( vaultItems[0].updatedAt, item.updatedAt ) ); assert.deepEqual(vaultItems[0].locations, item.locations); return vaultItems[0].getContent(); }) .then(content => { testLib.assertEqual(assert, content.formFields, [ { id: '', name: 'username', type: item_store.FormFieldType.Text, designation: 'username', value: 'testuser2@gmail.com', }, ]); // 3. Update item in store, sync and verify that // cloud store item is updated item.title = 'store item - updated'; return item.save(); }) .then(() => { return syncItems(env.syncer); }) .then(() => { return env.cloudStore.listItems(); }) .then(vaultItems => { assert.equal(vaultItems.length, 1); assert.equal(vaultItems[0].title, item.title); assert.ok( sync.itemUpdateTimesEqual( vaultItems[0].updatedAt, item.updatedAt ) ); }); }); testLib.addTest('merge local and cloud item updates', assert => { var env: Env; var item = new item_builder.Builder(item_store.ItemTypes.LOGIN) .setTitle('acme.org') .addLogin('jim@acme.org') .addUrl('acme.org') .item(); return setup() .then(_env => { env = _env; return item.saveTo(env.localStore); }) .then(() => { return syncItems(env.syncer); }) .then(() => { return env.cloudStore.loadItem(item.uuid); }) .then(vaultItem => { assert.equal(vaultItem.item.title, item.title); assert.equal(item.trashed, vaultItem.item.trashed); assert.ok( sync.itemUpdateTimesEqual( item.updatedAt, vaultItem.item.updatedAt ) ); // update item in cloudStore and store and save to both vaultItem.item.trashed = true; item.title = 'acme.org - client update'; return asyncutil.all2([item.save(), vaultItem.item.save()]); }) .then(() => { return syncItems(env.syncer); }) .then(() => { return asyncutil.all2([ env.localStore.loadItem(item.uuid), env.cloudStore.loadItem(item.uuid), ]); }) .then(items => { var storeItem = <item_store.Item>items[0].item; var vaultItem = <item_store.Item>items[1].item; assert.equal(storeItem.title, vaultItem.title); assert.equal(storeItem.trashed, vaultItem.trashed); assert.ok( sync.itemUpdateTimesEqual( storeItem.updatedAt, vaultItem.updatedAt ) ); }); }); testLib.addTest('report sync progress', assert => { var env: Env; var item = new item_builder.Builder(item_store.ItemTypes.LOGIN) .setTitle('sync me') .addLogin('testuser@gmail.com') .addUrl('accounts.google.com') .item(); var progressUpdates: sync.SyncProgress[] = []; return setup() .then(_env => { env = _env; env.syncer.onProgress.listen(progress => { progressUpdates.push(<sync.SyncProgress>clone(progress)); }); return item.saveTo(env.cloudStore); }) .then(() => { return syncItems(env.syncer); }) .then(finalState => { assert.deepEqual( progressUpdates, [ { state: sync.SyncState.ListingItems, updated: 0, failed: 0, total: 0, active: 0, }, { state: sync.SyncState.SyncingItems, active: 0, updated: 0, failed: 0, total: 1, }, { state: sync.SyncState.SyncingItems, active: 0, updated: 1, failed: 0, total: 1, }, { state: sync.SyncState.Idle, active: 0, updated: 1, failed: 0, total: 1, }, ], 'check that expected progress updates were received' ); assert.deepEqual(finalState, { state: sync.SyncState.Idle, active: 0, failed: 0, updated: 1, total: 1, }); progressUpdates = []; return syncItems(env.syncer); }) .then(() => { assert.deepEqual(progressUpdates, [ { state: sync.SyncState.ListingItems, active: 0, failed: 0, updated: 0, total: 0, }, { state: sync.SyncState.SyncingItems, active: 0, failed: 0, updated: 0, total: 0, }, { state: sync.SyncState.Idle, active: 0, failed: 0, updated: 0, total: 0, }, ]); }); }); const CLOUD_STORE_ID = 'cloud'; testLib.addTest('sync item deletion from cloud to local', assert => { let env: Env; let item: item_store.Item; return setupWithItem() .then(_env => { env = _env.env; item = _env.item; // sync item to local store return syncItems(env.syncer); }) .then(() => { // remove it in the cloud store return item.remove(); }) .then(() => { // sync again return syncItems(env.syncer); }) .then(() => { return env.localStore.listItems({ includeTombstones: true }); }) .then(items => { // verify that the store item was also // deleted assert.equal(items.length, 1); assert.ok(items[0].isTombstone()); // verify that the last-synced revision was cleared return env.localStore.getLastSyncedRevision( item.uuid, CLOUD_STORE_ID ); }) .then(revision => { assert.equal(revision, null); }); }); testLib.addTest('sync item deletion from local to cloud', assert => { let env: Env; return setupWithItem() .then(_env => { env = _env.env; return syncItems(env.syncer); }) .then(() => { return env.localStore.listItems(); }) .then(items => { // remove item in local store assert.equal(items.length, 1); assert.ok(!items[0].isTombstone()); return items[0].remove(); }) .then(() => { return syncItems(env.syncer); }) .then(() => { // verify that deletion was propagated to cloud store return env.cloudStore.listItems(); }) .then(items => { assert.equal(items.length, 0); }); }); testLib.addTest('item deleted in cloud and locally', assert => { let env: Env; let uuid: string; return setupWithItem() .then(_env => { env = _env.env; uuid = _env.item.uuid; return syncItems(env.syncer); }) .then(() => { let deletedLocally = env.localStore .loadItem(uuid) .then(item => item.item.remove()); let deletedInCloud = env.cloudStore .loadItem(uuid) .then(item => item.item.remove()); return asyncutil.all2([deletedLocally, deletedInCloud]); }) .then(() => { return syncItems(env.syncer); }) .then(result => { // the syncer could optimize by handling deletions on both // sides purely locally. For the moment, it reports the item // as being updated assert.equal(result.updated, 1); // sync again. This time the item should not be reported // as being updated. return syncItems(env.syncer); }) .then(result => { assert.equal(result.updated, 0); }); }); testLib.addTest('syncing locked store should fail', assert => { var env: Env; return setupWithItem() .then(_env => { env = _env.env; return env.keyAgent.forgetKeys(); }) .then(() => { return env.keyAgent.listKeys(); }) .then(keys => { return env.syncer.syncItems(); }) .then(result => { assert.equal(result.updated, 0); assert.equal(result.failed, 1); assert.equal(result.total, 1); }); }); testLib.addTest('repeat sync', assert => { return setupWithItem().then(env => { // syncing whilst a sync is already in progress should return // the same promise var synced = env.env.syncer.syncItems(); var synced2 = env.env.syncer.syncItems(); assert.equal(synced, synced2); return synced2; }); }); testLib.addTest('sync many items', assert => { var ITEM_COUNT = 100; var env: Env; return setup() .then(_env => { env = _env; var saves: Promise<void>[] = []; while (saves.length < ITEM_COUNT) { var item = new item_builder.Builder(item_store.ItemTypes.LOGIN) .setTitle('sync me ' + saves.length) .addLogin('testuser' + saves.length + '@gmail.com') .addUrl('signon.acme.org') .item(); saves.push(item.saveTo(env.cloudStore)); } return Promise.all(saves); }) .then(() => { return syncItems(env.syncer); }) .then(() => { return env.localStore.listItems(); }) .then(items => { assert.equal( items.length, ITEM_COUNT, 'synced expected number of items' ); }); }); testLib.addTest('sync should complete if errors occur', assert => { let env: Env; let item: item_store.Item; return setupWithItem() .then(_env => { env = _env.env; item = _env.item; return syncItems(env.syncer); }) .then(() => { return env.cloudStore.loadItem(item.uuid); }) .then(cloudItem => { cloudItem.item.title = 'Updated title'; return cloudItem.item.save(); }) .then(() => { // simulate error syncing a particular item // (eg. concurrent deletion of item from cloud store, // temporary issue with cloud store) let originalLoadItem = env.cloudStore.loadItem.bind(env.cloudStore); env.cloudStore.loadItem = uuid => { if (uuid === item.uuid) { return Promise.reject<item_store.ItemAndContent>( 'Could not load item' ); } else { return originalLoadItem(uuid); } }; return env.syncer.syncItems(); }) .then(result => { assert.equal(result.failed, 1); assert.equal(result.total, 1); // reset error handler and verify that // syncing succeeds delete env.cloudStore.loadItem; return env.syncer.syncItems(); }) .then(result => { assert.equal(result.failed, 0); assert.equal(result.updated, 1); assert.equal(result.total, 1); }); });
the_stack
const isPath = require('is-svg-path') export const typeForm = 'form' export const typeInput = 'input' export const typeTextarea = 'textarea' export const typeSelect = 'select' export const typeCheckbox = 'checkbox' export const typeRadio = 'radio' export const typeButton = 'button' export const typeLabel = 'label' export const typeOption = 'option' export const svgImage = 'svg' // const pathLogo = 'M8.63867 8.97461H2.91602V15H0.445312V0.78125H9.47852V2.77344H2.91602V7.00195H8.63867V8.97461Z' // const pathTailblocks = 'M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5' const fixAppearanceStyle = '-webkit-appearance: auto; -moz-appearance: none; appearance: auto;' export function loadFormComponents(editor: { DomComponents: any TraitManager: any Commands: any }): void { const domc = editor.DomComponents const idTrait = { name: 'id', } const forTrait = { name: 'for', } const nameTrait = { name: 'name', } const placeholderTrait = { name: 'placeholder', } const valueTrait = { name: 'value', } const requiredTrait = { type: 'checkbox', name: 'required', } const checkedTrait = { type: 'checkbox', name: 'checked', } domc.addType(typeForm, { isComponent: (el: { tagName: string }) => el.tagName == 'FORM', model: { defaults: { tagName: 'form', droppable: ':not(form)', draggable: ':not(form)', attributes: { method: 'get' }, traits: [ { type: 'select', name: 'method', options: [ { value: 'get', name: 'GET' }, { value: 'post', name: 'POST' }, ], }, { name: 'action', placeholder: 'Insert URL', }, { type: 'form-next', name: 'form', label: 'New form', }, ], }, }, view: { events: { submit: (e: { preventDefault: () => any }) => e.preventDefault(), }, }, }) // INPUT domc.addType(typeInput, { isComponent: (el: { tagName: string }) => el.tagName == 'INPUT', model: { defaults: { tagName: 'input', draggable: 'form, form *', droppable: false, highlightable: false, attributes: { type: 'text' }, traits: [ nameTrait, placeholderTrait, { type: 'select', name: 'type', options: [ { value: 'text' }, { value: 'email' }, { value: 'password' }, { value: 'number' }, ], }, requiredTrait, ], }, }, extendFnView: ['updateAttributes'], view: { updateAttributes() { this.el.setAttribute('autocomplete', 'off') }, }, }) // TEXTAREA domc.addType(typeTextarea, { extend: typeInput, isComponent: (el: { tagName: string }) => el.tagName == 'TEXTAREA', model: { defaults: { tagName: 'textarea', attributes: {}, traits: [nameTrait, placeholderTrait, requiredTrait], }, }, }) // OPTION domc.addType(typeOption, { isComponent: (el: { tagName: string }) => el.tagName == 'OPTION', model: { defaults: { tagName: 'option', layerable: false, droppable: false, draggable: false, highlightable: false, }, }, }) const createOption = (value: string, name: string) => ({ type: typeOption, components: name, attributes: { value }, }) // SELECT domc.addType(typeSelect, { extend: typeInput, isComponent: (el: { tagName: string }) => el.tagName == 'SELECT', model: { defaults: { tagName: 'select', components: [createOption('opt1', 'Option 1'), createOption('opt2', 'Option 2')], traits: [ nameTrait, { name: 'options', type: 'select-options', }, requiredTrait, ], }, }, view: { events: { mousedown: (e: { preventDefault: () => any }) => e.preventDefault(), }, }, }) // CHECKBOX domc.addType(typeCheckbox, { extend: typeInput, isComponent: (el: { tagName: string; type: string }) => el.tagName == 'INPUT' && el.type == 'checkbox', model: { defaults: { copyable: false, attributes: { type: 'checkbox' }, traits: [idTrait, nameTrait, valueTrait, requiredTrait, checkedTrait], }, }, view: { events: { click: (e: { preventDefault: () => any }) => e.preventDefault(), }, init() { this.listenTo(this.model, 'change:attributes:checked', this.handleChecked) }, handleChecked() { this.el.checked = !!this.model.get('attributes').checked }, }, }) // RADIO domc.addType(typeRadio, { extend: typeCheckbox, isComponent: (el: { tagName: string; type: string }) => el.tagName == 'INPUT' && el.type == 'radio', model: { defaults: { attributes: { type: 'radio' }, }, }, }) domc.addType(typeButton, { extend: typeInput, isComponent: (el: { tagName: string }) => el.tagName == 'BUTTON', model: { defaults: { tagName: 'button', attributes: { type: 'button' }, traits: [ { name: 'text', changeProp: true, }, { type: 'button-next', name: 'button', label: 'New button', }, ], }, init() { const comps = this.components() const tChild = comps.length === 1 && comps.models[0] const chCnt = (tChild && tChild.is('textnode') && tChild.get('content')) || '' const text = chCnt || this.get('text') this.set({ text }) this.on('change:text', this.__onTextChange) text !== chCnt && this.__onTextChange() }, __onTextChange() { this.components(this.get('text')) }, }, view: { events: { click: (e: { preventDefault: () => any }) => e.preventDefault(), }, }, }) // LABEL domc.addType(typeLabel, { extend: 'text', isComponent: (el: { tagName: string }) => el.tagName == 'LABEL', model: { defaults: { tagName: 'label', components: 'Label', traits: [forTrait], }, }, }) // SVG domc.addType(svgImage, { model: { defaults: { tagName: 'svg', components: 'Svg', traits: [ { name: 'viewBox', }, { name: 'stroke', }, { type: 'svg-next', name: 'svg', label: 'Path', }, ], }, }, }) domc.addType('link', { model: { defaults: { traits: [ { type: 'href-next', name: 'href', label: 'New href', }, ], }, }, }) const trtm = editor.TraitManager trtm.addType('href-next', { noLabel: true, createInput() { const el = document.createElement('div') el.style.backgroundColor = 'white' el.innerHTML = ` <select class="href-next__type" style="background-color: #f1f1f1; margin-bottom: 10px; ${fixAppearanceStyle}"> <option value="url">URL</option> <option value="email">Email</option> </select> <div class="href-next__url-inputs" style="background-color: #f1f1f1; margin-bottom: 10px;"> <input class="href-next__url" placeholder="Insert URL"/> </div> <div class="href-next__email-inputs" style="background-color: #f1f1f1;"> <input class="href-next__email" placeholder="Insert email"/> </div> <div class="href-next__newtab-inputs"> <input style="width: auto; ${fixAppearanceStyle}" class="href-next__newtab" type="checkbox"> <label> Open in "New Tab"</label> </div> ` const inputsUrl = <HTMLElement>el.querySelector('.href-next__url-inputs') const inputsEmail = <HTMLElement>el.querySelector('.href-next__email-inputs') const inputType = <HTMLElement>el.querySelector('.href-next__type') const inputNewTab = <HTMLElement>el.querySelector('.href-next__newtab-inputs') inputType.addEventListener('change', (ev) => { switch ((<HTMLInputElement>ev.target).value) { case 'url': inputsUrl.style.display = '' inputsEmail.style.display = 'none' inputNewTab.style.display = '' break case 'email': inputsUrl.style.display = 'none' inputsEmail.style.display = '' inputNewTab.style.display = 'none' break } }) return el }, onEvent({ elInput, component }) { const inputType = elInput.querySelector('.href-next__type') let href = '' switch (inputType.value) { case 'url': const valUrl = elInput.querySelector('.href-next__url').value href = valUrl const valIsNewTab = elInput.querySelector('.href-next__newtab').checked if (valIsNewTab) { component.addAttributes({ target: '_blank' }) } else { component.removeAttributes('target') } break case 'email': const valEmail = elInput.querySelector('.href-next__email').value href = `mailto:${valEmail}` break } component.addAttributes({ href }) }, onUpdate({ elInput, component }) { const href = component.getAttributes().href || '' const inputType = elInput.querySelector('.href-next__type') let type = 'url' const valIsNewTab = elInput.querySelector('.href-next__newtab') if (href.indexOf('mailto:') === 0) { const inputEmail = elInput.querySelector('.href-next__email') const mailTo = href.replace('mailto:', '').split('?') const email = mailTo[0] type = 'email' inputEmail.value = email || '' } else { elInput.querySelector('.href-next__url').value = href } valIsNewTab.checked = component.getAttributes().target === '_blank' inputType.value = type inputType.dispatchEvent(new CustomEvent('change')) }, }) const onClickButtonClear = (src) => `const run = (e) => { if (e.target.getAttribute('data-gjs-type') !== 'button') { ${src} } }; run(arguments[0]) ` trtm.addType('button-next', { noLabel: true, createInput({ trait }) { const el = document.createElement('div') el.style.backgroundColor = 'white' el.innerHTML = ` <select class="button-next__type" style="background-color: #f1f1f1; margin-bottom: 10px; ${fixAppearanceStyle}"> <option value="url">URL</option> <option value="email">Email</option> <option value="submit">Submit</option> </select> <div class="button-next__url-inputs" style="background-color: #f1f1f1; margin-bottom: 10px;"> <input class="button-next__url" placeholder="Insert URL"/> </div> <div class="button-next__email-inputs" style="background-color: #f1f1f1;"> <input class="button-next__email" placeholder="Insert email"/> </div> <div class="button-next__newtab-inputs" style="margin-bottom: 10px;"> <input style="width: auto; ${fixAppearanceStyle}" class="button-next__newtab" type="checkbox"> <label> Open in "New Tab"</label> </div> <!-- <div class="button-next__action-inputs" style="background-color: #f1f1f1; margin-bottom: 10px;"> <input class="button-next__action" placeholder="Insert action URL"/> </div> <div class="button-next__async-inputs"> <input style="width: auto; ${fixAppearanceStyle}" class="button-next__async" type="checkbox"> <label> Async</label> </div> --> ` const inputType = <HTMLElement>el.querySelector('.button-next__type') const inputsUrl = <HTMLElement>el.querySelector('.button-next__url-inputs') inputsUrl.style.display = '' const inputsEmail = <HTMLElement>el.querySelector('.button-next__email-inputs') inputsEmail.style.display = 'none' const inputNewTab = <HTMLElement>el.querySelector('.button-next__newtab-inputs') inputNewTab.style.display = '' inputType.addEventListener('change', (ev) => { const type = (<HTMLInputElement>ev.target).value switch (type) { case 'url': inputsUrl.style.display = '' inputsEmail.style.display = 'none' inputNewTab.style.display = '' break case 'email': inputsUrl.style.display = 'none' inputsEmail.style.display = '' inputNewTab.style.display = 'none' break case 'submit': inputsUrl.style.display = 'none' inputsEmail.style.display = 'none' inputNewTab.style.display = 'none' break } }) return el }, onEvent({ elInput, component }) { const inputType = elInput.querySelector('.button-next__type') let onClickSrc = '' switch (inputType.value) { case 'url': const valUrl = elInput.querySelector('.button-next__url').value const valIsNewTab = elInput.querySelector('.button-next__newtab').checked onClickSrc = valIsNewTab ? `window.open('${valUrl}', '_blank')?.focus()` : `location.href = "${valUrl}"` component.addAttributes({ type: 'button' }) component.addAttributes({ 'data-gjs-sub-type': 'url' }) component.addAttributes({ 'data-gjs-url': valUrl }) component.addAttributes({ 'data-gjs-new-tab': valIsNewTab }) component.removeAttributes('data-gjs-email') component.addAttributes({ onclick: onClickButtonClear(onClickSrc) }) break case 'email': const valEmail = elInput.querySelector('.button-next__email').value onClickSrc = `location.href = "mailto:${valEmail}"` component.addAttributes({ type: 'button' }) component.addAttributes({ 'data-gjs-sub-type': 'email' }) component.addAttributes({ 'data-gjs-email': valEmail }) component.removeAttributes('data-gjs-url') component.removeAttributes('data-gjs-new-tab') component.addAttributes({ onclick: onClickButtonClear(onClickSrc) }) break case 'submit': component.addAttributes({ type: 'submit' }) component.addAttributes({ 'data-gjs-sub-type': 'submit' }) component.removeAttributes('data-gjs-email') component.removeAttributes('data-gjs-url') component.removeAttributes('data-gjs-new-tab') component.removeAttributes('onclick') break } }, onUpdate({ elInput, component }) { const attrs = component.getAttributes() const type = attrs['data-gjs-sub-type'] const inputType = elInput.querySelector('.button-next__type') if (type === 'url') { const inputUrl = elInput.querySelector('.button-next__url') const url = attrs['data-gjs-url'] inputUrl.value = url || '' const inputNewTab = elInput.querySelector('.button-next__newtab') const newTab = attrs['data-gjs-new-tab'] inputNewTab.checked = newTab || false } else if (type === 'email') { const inputEmail = elInput.querySelector('.button-next__email') const email = attrs['data-gjs-email'] inputEmail.value = email || '' } inputType.value = type || 'url' inputType.dispatchEvent(new CustomEvent('change')) }, }) trtm.addType('svg-next', { noLabel: true, createInput() { const el = document.createElement('div') el.style.backgroundColor = 'white' el.innerHTML = ` <div class="svg-next__svg-inputs" style="background-color: #f1f1f1;"> <input class="svg-next__svg" placeholder="Path"/> </div> ` return el }, onEvent({ elInput, component }) { const newPath = elInput.querySelector('.svg-next__svg').value if (newPath === '' || !isPath(newPath)) return const parser = new DOMParser() const htmlDoc = parser.parseFromString(component.toHTML(), 'text/html') const pathEl = htmlDoc.querySelector('path') pathEl?.setAttribute('d', newPath) pathEl?.setAttribute('data-gjs-type', 'svg-in') pathEl?.setAttribute('draggable', 'true') component.replaceWith(htmlDoc.body.innerHTML) }, onUpdate({ elInput, component }) { const parser = new DOMParser() const htmlDoc = parser.parseFromString(component.toHTML(), 'text/html') const path = htmlDoc.querySelector('path')?.getAttribute('d') elInput.querySelector('.svg-next__svg').value = path }, }) trtm.addType('form-next', { noLabel: true, createInput() { const el = document.createElement('div') el.style.backgroundColor = 'white' el.innerHTML = ` <div> <input style="width: auto; ${fixAppearanceStyle}" class="form-next__async" type="checkbox"> <label> Async</label> </div> ` return el }, onEvent({ elInput, component }) { const valIsAsync = elInput.querySelector('.form-next__async').checked component.addAttributes({ 'data-gjs-async': valIsAsync }) // const onClickSrc = ` // const run = (e) => { // if (e.target.getAttribute('data-gjs-type') !== 'button') { // e.preventDefault() // this.form.submit() // } // }; // run(arguments[0]) // ` const content = valIsAsync ? ` e.preventDefault() const params = new URLSearchParams() const body = new FormData(e.target) body.forEach(([f, v]) => params.append(f, v)) const action = e.target.getAttribute('action') const method = e.target.getAttribute('method') fetch(action, { method, ...(method.toUpperCase() !== 'GET' ? {body} : {}) }) .then((e) => e.text().then(d => ({ok: e.ok, text: d}))) .then(({ok, text}) => { let message = ok ? 'All good' : 'Something went wrong' let type = ok ? 'info' : 'error' try { const data = JSON.parse(text) if (data.message) message = data.message } catch(err) {} document.dispatchEvent(new CustomEvent('toast', {detail: {message, type}})) }) for (let el of e.target.elements) el.value = null ` : ` for (let el of e.target.elements) el.value = null e.preventDefault() e.target.submit() ` const onClickSrc = ` const run = (e) => { ${content} }; run(arguments[0]) ` component.addAttributes({ onsubmit: onClickSrc }) }, onUpdate({ elInput, component }) { const attrs = component.getAttributes() const inputAsync = elInput.querySelector('.form-next__async') const isAsync = attrs['data-gjs-async'] inputAsync.checked = isAsync || '' }, }) }
the_stack
import { GlobalProps } from 'ojs/ojvcomponent'; import { ComponentChildren } from 'preact'; import Color = require('../ojcolor'); import { editableValue, editableValueEventMap, editableValueSettableProperties } from '../ojeditablevalue'; import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface ojColorPalette extends editableValue<Color, ojColorPaletteSettableProperties> { displayOptions?: { converterHint?: 'display' | 'none'; helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages?: 'display' | 'none'; validatorHint?: 'display' | 'none'; }; labelDisplay: 'auto' | 'off'; labelledBy: string | null; layout: 'grid' | 'list'; palette: Array<{ color: Color; label?: string; }>; swatchSize: 'xs' | 'sm' | 'lg'; value: Color; translations: { labelNone?: string; }; addEventListener<T extends keyof ojColorPaletteEventMap>(type: T, listener: (this: HTMLElement, ev: ojColorPaletteEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojColorPaletteSettableProperties>(property: T): ojColorPalette[T]; getProperty(property: string): any; setProperty<T extends keyof ojColorPaletteSettableProperties>(property: T, value: ojColorPaletteSettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojColorPaletteSettableProperties>): void; setProperties(properties: ojColorPaletteSettablePropertiesLenient): void; } export namespace ojColorPalette { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged = JetElementCustomEvent<ojColorPalette["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type labelDisplayChanged = JetElementCustomEvent<ojColorPalette["labelDisplay"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojColorPalette["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type layoutChanged = JetElementCustomEvent<ojColorPalette["layout"]>; // tslint:disable-next-line interface-over-type-literal type paletteChanged = JetElementCustomEvent<ojColorPalette["palette"]>; // tslint:disable-next-line interface-over-type-literal type swatchSizeChanged = JetElementCustomEvent<ojColorPalette["swatchSize"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojColorPalette["value"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged = editableValue.describedByChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type disabledChanged = editableValue.disabledChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpChanged = editableValue.helpChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged = editableValue.helpHintsChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged = editableValue.labelEdgeChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged = editableValue.labelHintChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged = editableValue.messagesCustomChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged = editableValue.userAssistanceDensityChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type validChanged = editableValue.validChanged<Color, ojColorPaletteSettableProperties>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ojColorPaletteEventMap extends editableValueEventMap<Color, ojColorPaletteSettableProperties> { 'ojAnimateEnd': ojColorPalette.ojAnimateEnd; 'ojAnimateStart': ojColorPalette.ojAnimateStart; 'displayOptionsChanged': JetElementCustomEvent<ojColorPalette["displayOptions"]>; 'labelDisplayChanged': JetElementCustomEvent<ojColorPalette["labelDisplay"]>; 'labelledByChanged': JetElementCustomEvent<ojColorPalette["labelledBy"]>; 'layoutChanged': JetElementCustomEvent<ojColorPalette["layout"]>; 'paletteChanged': JetElementCustomEvent<ojColorPalette["palette"]>; 'swatchSizeChanged': JetElementCustomEvent<ojColorPalette["swatchSize"]>; 'valueChanged': JetElementCustomEvent<ojColorPalette["value"]>; 'describedByChanged': JetElementCustomEvent<ojColorPalette["describedBy"]>; 'disabledChanged': JetElementCustomEvent<ojColorPalette["disabled"]>; 'helpChanged': JetElementCustomEvent<ojColorPalette["help"]>; 'helpHintsChanged': JetElementCustomEvent<ojColorPalette["helpHints"]>; 'labelEdgeChanged': JetElementCustomEvent<ojColorPalette["labelEdge"]>; 'labelHintChanged': JetElementCustomEvent<ojColorPalette["labelHint"]>; 'messagesCustomChanged': JetElementCustomEvent<ojColorPalette["messagesCustom"]>; 'userAssistanceDensityChanged': JetElementCustomEvent<ojColorPalette["userAssistanceDensity"]>; 'validChanged': JetElementCustomEvent<ojColorPalette["valid"]>; } export interface ojColorPaletteSettableProperties extends editableValueSettableProperties<Color> { displayOptions?: { converterHint?: 'display' | 'none'; helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages?: 'display' | 'none'; validatorHint?: 'display' | 'none'; }; labelDisplay: 'auto' | 'off'; labelledBy: string | null; layout: 'grid' | 'list'; palette: Array<{ color: Color; label?: string; }>; swatchSize: 'xs' | 'sm' | 'lg'; value: Color; translations: { labelNone?: string; }; } export interface ojColorPaletteSettablePropertiesLenient extends Partial<ojColorPaletteSettableProperties> { [key: string]: any; } export type ColorPaletteElement = ojColorPalette; export namespace ColorPaletteElement { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged = JetElementCustomEvent<ojColorPalette["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type labelDisplayChanged = JetElementCustomEvent<ojColorPalette["labelDisplay"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojColorPalette["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type layoutChanged = JetElementCustomEvent<ojColorPalette["layout"]>; // tslint:disable-next-line interface-over-type-literal type paletteChanged = JetElementCustomEvent<ojColorPalette["palette"]>; // tslint:disable-next-line interface-over-type-literal type swatchSizeChanged = JetElementCustomEvent<ojColorPalette["swatchSize"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojColorPalette["value"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged = editableValue.describedByChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type disabledChanged = editableValue.disabledChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpChanged = editableValue.helpChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged = editableValue.helpHintsChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged = editableValue.labelEdgeChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged = editableValue.labelHintChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged = editableValue.messagesCustomChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged = editableValue.userAssistanceDensityChanged<Color, ojColorPaletteSettableProperties>; // tslint:disable-next-line interface-over-type-literal type validChanged = editableValue.validChanged<Color, ojColorPaletteSettableProperties>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ColorPaletteIntrinsicProps extends Partial<Readonly<ojColorPaletteSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAnimateEnd?: (value: ojColorPaletteEventMap['ojAnimateEnd']) => void; onojAnimateStart?: (value: ojColorPaletteEventMap['ojAnimateStart']) => void; ondisplayOptionsChanged?: (value: ojColorPaletteEventMap['displayOptionsChanged']) => void; onlabelDisplayChanged?: (value: ojColorPaletteEventMap['labelDisplayChanged']) => void; onlabelledByChanged?: (value: ojColorPaletteEventMap['labelledByChanged']) => void; onlayoutChanged?: (value: ojColorPaletteEventMap['layoutChanged']) => void; onpaletteChanged?: (value: ojColorPaletteEventMap['paletteChanged']) => void; onswatchSizeChanged?: (value: ojColorPaletteEventMap['swatchSizeChanged']) => void; onvalueChanged?: (value: ojColorPaletteEventMap['valueChanged']) => void; ondescribedByChanged?: (value: ojColorPaletteEventMap['describedByChanged']) => void; ondisabledChanged?: (value: ojColorPaletteEventMap['disabledChanged']) => void; onhelpChanged?: (value: ojColorPaletteEventMap['helpChanged']) => void; onhelpHintsChanged?: (value: ojColorPaletteEventMap['helpHintsChanged']) => void; onlabelEdgeChanged?: (value: ojColorPaletteEventMap['labelEdgeChanged']) => void; onlabelHintChanged?: (value: ojColorPaletteEventMap['labelHintChanged']) => void; onmessagesCustomChanged?: (value: ojColorPaletteEventMap['messagesCustomChanged']) => void; onuserAssistanceDensityChanged?: (value: ojColorPaletteEventMap['userAssistanceDensityChanged']) => void; onvalidChanged?: (value: ojColorPaletteEventMap['validChanged']) => void; children?: ComponentChildren; } declare global { namespace preact.JSX { interface IntrinsicElements { "oj-color-palette": ColorPaletteIntrinsicProps; } } }
the_stack
import {expect} from 'chai'; import { LiteralStringExpression, Node, DebuggerStatement, IdentifierExpression, StaticMemberExpression, VariableDeclarator, FunctionDeclaration, BindingIdentifier, } from 'shift-ast'; import {parseScript as parse, parseScript} from 'shift-parser'; import {RefactorSession} from '../src/refactor-session'; import {RefactorError} from '../src/misc/types'; import {describe} from 'mocha'; //@ts-ignore VSCode bug? VSC is complaining about this import but TypeScript is fine with it. import {Scope} from 'shift-scope'; describe('RefactorSession', () => { it('.query()', () => { const refactor = new RefactorSession(`function foo(){}\nfoo();`); const nodes = refactor.query(`FunctionDeclaration[name.name="foo"]`); expect(nodes.length).to.equal(1); }); describe('.delete()', () => { it('should delete statements', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); refactor.delete(`FunctionDeclaration[name.name="foo"]`); expect(refactor.first()).to.deep.equal(parse('foo();')); }); it('should accept actual nodes', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); refactor.delete(ast.statements[0]); expect(refactor.first()).to.deep.equal(parse('foo();')); }); }); describe('insert', function() { describe('prepend', () => { it('should insert statement before', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); refactor.prepend(`[expression.callee.name="foo"]`, `console.log(0)`); expect(refactor.first()).to.deep.equal(parse('function foo(){}\nconsole.log(0);\nfoo();')); }); it('should accept a function that has access to the nodes queried', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); refactor.prepend( `ExpressionStatement[expression.type="CallExpression"]`, //@ts-ignore (node: Node) => `console.log("Calling ${node.expression.callee.name}()")`, ); expect(refactor.first()).to.deep.equal(parse('function foo(){}\nconsole.log("Calling foo()");\nfoo();')); }); it('should accept a function that returns a shift type', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); refactor.prepend(`ExpressionStatement[expression.type="CallExpression"]`, () => new DebuggerStatement()); expect(refactor.first()).to.deep.equal(parse('function foo(){}\ndebugger;\nfoo();')); }); it('should fail with an error if you try to insert an expression', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); const shouldThrow = () => { refactor.prepend( `ExpressionStatement[expression.type="CallExpression"]`, () => new IdentifierExpression({name: 'breaks'}), ); }; expect(shouldThrow).to.throw(RefactorError); }); it('should fail with an error if you query anything other than a statement or declaration', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); const shouldThrow = () => { refactor.prepend(`IdentifierExpression`, `shouldNotMatter()`); }; expect(shouldThrow).to.throw(RefactorError); }); }); describe('append', () => { it('should insert statements after', () => { let ast = parse(`function foo(){}\nfunction bar(){}\nfoo();`); const refactor = new RefactorSession(ast); refactor.append(`FunctionDeclaration`, `console.log(0)`); expect(refactor.first()).to.deep.equal( parse('function foo(){}\nconsole.log(0)\nfunction bar(){}\nconsole.log(0)\nfoo();'), ); }); }); }); describe('rename', function() { it('rename function declarations', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); refactor.rename(`FunctionDeclaration > BindingIdentifier[name="foo"]`, 'bar'); expect(ast).to.deep.equal(parse('function bar(){}\nbar();')); }); it('rename function calls', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); refactor.rename(`IdentifierExpression[name="foo"]`, 'bar'); expect(ast).to.deep.equal(parse('function bar(){}\nbar();')); }); it('rename BindingIdentifiers', () => { let ast = parse(`const a=2,b=3;a++;b++`); const refactor = new RefactorSession(ast); refactor.rename(`BindingIdentifier[name="a"]`, 'renamed'); expect(ast).to.deep.equal(parse('const renamed=2,b=3;renamed++;b++')); }); it('should be able to consume VariableDeclarators', () => { let ast = parse(`const a=2,b=3;a++;b++`); const refactor = new RefactorSession(ast); refactor.rename(`[binding.name="a"][init.value=2]`, 'renamed'); expect(ast).to.deep.equal(parse('const renamed=2,b=3;renamed++;b++')); }); it('should be able to consume nodes directly', () => { let ast = parse(`const a=2,b=3;a++;b++`); const refactor = new RefactorSession(ast); const declarator = refactor.query('VariableDeclarator[binding.name="a"]') as VariableDeclarator[]; refactor.rename(declarator[0].binding, 'renamed'); expect(ast).to.deep.equal(parse('const renamed=2,b=3;renamed++;b++')); }); }); describe('subSession', () => { it('should scope a refactor session to child nodes via a query', async () => { let r = new RefactorSession(`b;function foo(a){return d}`); let rootIdExprs = r.query('IdentifierExpression'); expect(rootIdExprs.length).to.equal(2); let callExpression = r.subSession('FunctionDeclaration'); expect(callExpression.nodes.length).to.equal(1); let idExpr = callExpression.query('IdentifierExpression'); expect(idExpr.length).to.equal(1); }); it('should scope a refactor session to nodes passed as arguments', async () => { let r = new RefactorSession(`b;function foo(a){return d}`); let rootIdExprs = r.query('IdentifierExpression'); expect(rootIdExprs.length).to.equal(2); let callExpressions = r.subSession('FunctionDeclaration'); expect(callExpressions.nodes.length).to.equal(1); const subSession = r.subSession(callExpressions); let idExpr = subSession.query('IdentifierExpression'); expect(idExpr.length).to.equal(1); }); }); describe('replaceAsync', () => { it('should replace nodes with Node instances', async () => { let script = new RefactorSession(`foo(a)`); await script.replaceAsync( `IdentifierExpression[name="a"]`, async (node: Node) => await new IdentifierExpression({name: 'b'}), ); expect(script.first()).to.deep.equal(parse('foo(b)')); }); it('should accept same nodes and move on without changes', async () => { let script = new RefactorSession(`foo(a)`); await script.replaceAsync(`IdentifierExpression[name="a"]`, async (node: any) => node); expect(script.first()).to.deep.equal(parse('foo(a)')); //@ts-ignore expect(script.first().statements[0].expression.arguments[0]).to.equal( //@ts-ignore script.first().statements[0].expression.arguments[0], ); }); }); describe('first', () => { it('should return the first node', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); expect(refactor.first()).to.equal(ast); }); }); describe('replace', function() { it('should replace statements', () => { let ast = parse(`function foo(){}\nfoo();`); const refactor = new RefactorSession(ast); refactor.replace(`FunctionDeclaration[name.name="foo"]`, `console.log(0)`); expect(refactor.first()).to.deep.equal(parse('console.log(0);foo();')); }); it('should replace expressions', () => { let ast = parse(`foo(a)`); const refactor = new RefactorSession(ast); refactor.replace(`IdentifierExpression[name="a"]`, `bar()`); expect(refactor.first()).to.deep.equal(parse('foo(bar())')); }); it('should accept a node list as a replacement', () => { let ast = parse(`foo(a)`); const refactor = new RefactorSession(ast); const callExpressions = refactor.query('CallExpression'); refactor.replace(callExpressions, '`foo`'); expect(refactor.first()).to.deep.equal(parse('`foo`')); }); it('should be able to pass a function in to replace', () => { let ast = parse(`foo(a)`); const refactor = new RefactorSession(ast); refactor.replace( `IdentifierExpression[name="a"]`, // @ts-ignore (node: Node) => new IdentifierExpression({name: node.name + 'b'}), ); expect(refactor.first()).to.deep.equal(parse('foo(ab)')); }); it('should throw on an async replacement function', () => { let ast = parse(`foo(a)`); const refactor = new RefactorSession(ast); const fn = () => { refactor.replace( `IdentifierExpression[name="a"]`, async (node: any) => await new IdentifierExpression({name: 'b'}), ); }; expect(fn).to.throw(); }); it('should accept source containing a lone string from a passed function (catch directive case)', () => { let ast = parse(`foo(a)`); const refactor = new RefactorSession(ast); //@ts-ignore refactor.replace(`IdentifierExpression[name="a"]`, (node: Node) => `"${node.name}"`); expect(refactor.first()).to.deep.equal(parse("foo('a')")); }); it('should accept raw source from a passed function to replace expressions', () => { let ast = parse(`foo(a)`); const refactor = new RefactorSession(ast); refactor.replace(`IdentifierExpression[name="a"]`, (node: any) => `true`); expect(refactor.first()).to.deep.equal(parse('foo(true)')); }); it('should accept raw source from a passed function to replace statements', () => { let ast = parse(`a;foo(a);b;`); const refactor = new RefactorSession(ast); refactor.replace(`ExpressionStatement[expression.type="CallExpression"]`, (node: any) => `console.log(test)`); expect(refactor.first()).to.deep.equal(parse('a;console.log(test);b;')); }); }); describe('replaceRecursive', function() { it('should replace until the query is empty', () => { let ast = parse(`a["b"]["c"]`); const refactor = new RefactorSession(ast); refactor.replaceRecursive( `ComputedMemberExpression[expression.type="LiteralStringExpression"]`, (node: Node) => //@ts-ignore new StaticMemberExpression({object: node.object, property: node.expression.value}), ); expect(refactor.first()).to.deep.equal(parse('a.b.c')); }); }); it('.findOne()', () => { const refactor = new RefactorSession(`function foo(){}\nfunction bar(){}`); const node = refactor.findOne(`FunctionDeclaration[name.name="foo"]`) as FunctionDeclaration; expect(node.name.name).to.equal('foo'); function shouldBreak() { refactor.findOne(`FunctionDeclaration`); } expect(shouldBreak).to.throw(); }); it('.findParents()', () => { const refactor = new RefactorSession(`function foo(){}\nfunction bar(){}`); const nodes = refactor.find(`BindingIdentifier`); expect(nodes.length).to.equal(2); const parents = refactor.findParents(nodes); expect(parents.length).to.equal(2); }); it('.findReferences()', () => { const refactor = new RefactorSession(`function foo(){}\nfoo();var a = foo();`); const fn = refactor.findOne(`FunctionDeclaration[name.name="foo"]`) as FunctionDeclaration; expect(refactor.findReferences(fn).length).to.equal(2); }); it('.findDeclarations()', () => { const refactor = new RefactorSession(`function foo(){}\nfoo();var a = foo();`); const fn = refactor.findOne(`FunctionDeclaration[name.name="foo"]`) as FunctionDeclaration; expect(refactor.findDeclarations(fn).length).to.equal(1); }); describe('.findMatchingExpression()', () => { it('should find nodes by complete sample source', () => { const $script = new RefactorSession(`function foo(){}\nfoo(); a = foo(); b = foo(2); b = foo();`); let nodes: Node[] = $script.findMatchingExpression('b = foo()'); expect(nodes.length).to.equal(1); //@ts-ignore blindly poking deeply expect(nodes[0]).to.deep.equal($script.first().statements[4].expression); }); }); describe('.findMatchingStatement()', () => { it('should find nodes by complete sample source', () => { const $script = new RefactorSession(`function foo(){}\nfoo(); a = foo(); b = foo(2); b = foo();`); let nodes = $script.findMatchingStatement('b = foo(2)'); expect(nodes.length).to.equal(1); //@ts-ignore blindly poking deeply expect(nodes[0]).to.deep.equal($script.first().statements[3]); }); it('should find nodes by partial sample source', () => { const $script = new RefactorSession(`function foo(a,b){ return a+b;}\n function bar(){}`); let nodes = $script.findMatchingStatement('function foo(a,b){}'); expect(nodes.length).to.equal(1); //@ts-ignore blindly poking deeply expect(nodes[0]).to.deep.equal($script.first().statements[0]); }); }); it('.queryFrom()', () => { let ast = parse(`var a = 2; function foo(){var a = 4}`); const refactor = new RefactorSession(ast); const nodes = refactor.query(`FunctionDeclaration[name.name="foo"]`); const innerNodes = refactor.queryFrom(nodes, `VariableDeclarator[binding.name="a"]`); expect(innerNodes.length).to.equal(1); }); describe('.print()', () => { it('should print a structurally equivalent program', () => { let ast = parse(`var a = 2; function foo(){var a = 4}`); const refactor = new RefactorSession(ast); const newSource = refactor.print(); expect(ast).to.deep.equal(parse(newSource)); }); it('should take in and print any ast', () => { let ast = parse(`var a = 2; function foo(){var a = 4}`); const refactor = new RefactorSession(ast); const newSource = refactor.print(new LiteralStringExpression({value: 'hi'})); expect(newSource).to.equal('"hi"'); }); }); describe('.closest()', () => { it('should walk up a tree looking for a matching selector', () => { let ast = parse(`var a = 2; function foo(){var b = 4}`); const refactor = new RefactorSession(ast); const innerBinding = refactor.query('BindingIdentifier[name="b"]'); const parentStatement = refactor.closest(innerBinding, 'VariableDeclarationStatement'); expect(parentStatement.length).to.equal(1); }); it('should accept generic Statement|Expression queries', () => { let ast = parse(`var a = 2; function foo(){var b = 4}`); const refactor = new RefactorSession(ast); const innerBinding = refactor.query('BindingIdentifier[name="b"]'); const parentStatement = refactor.closest(innerBinding, ':statement'); expect(parentStatement.length).to.equal(1); }); it("should find all selected nodes' parents", () => { let ast = parse(`function someFunction() { interestingFunction(); } function otherFunction() { interestingFunction(); }`); const refactor = new RefactorSession(ast); const calls = refactor.query('CallExpression[callee.name="interestingFunction"]'); const decls = refactor.closest(calls, ':statement'); expect(decls.length).to.equal(2); }); }); describe('lookupVariableByName', function() { it('should return variables by name', () => { let ast = parse(`var a = 2; var b = 3; (function(b){ var a = "foo" }())`); const refactor = new RefactorSession(ast); const varsA = refactor.globalSession.lookupVariableByName('a'); expect(varsA).to.be.lengthOf(2); const varsB = refactor.globalSession.lookupVariableByName('b'); expect(varsB).to.be.lengthOf(2); }); }); it('.lookupVariable() should return variable lookup by Identifier node', () => { let ast = parse(`var a = 2; function foo(){var b = 4}`); const refactor = new RefactorSession(ast); const innerBinding = refactor.query('BindingIdentifier[name="b"]') as BindingIdentifier[]; const lookup = refactor.globalSession.lookupVariable(innerBinding); expect(lookup).to.be.ok; expect(lookup.declarations.length).to.equal(1); }); it('.lookupScope() should return variable scope', () => { let ast = parse(`var a = 2; function foo(){var b = 4}`); const refactor = new RefactorSession(ast); const innerBinding = refactor.query('BindingIdentifier[name="b"]') as BindingIdentifier[]; const lookup = refactor.globalSession.lookupScope(innerBinding) as Scope; expect(lookup).to.be.ok; expect(lookup.astNode).to.equal(ast.statements[1]); }); it('.cleanup()', () => { let ast = parse(``); const refactor = new RefactorSession(ast); expect(() => refactor.cleanup()).to.not.throw(); }); });
the_stack
import { PromiseError, Component } from "./../errors/promise-error"; import { print, TypeMessage, printSeparator } from "../messages/console-log"; import { FunctionInfo } from "./structs/function-info"; import { AccountInfo } from "./structs/account-info"; import { CompilationResult } from "./structs/compilation-output"; import { DeploymentError, DeploymentResult, DeploymentOutput, } from "./structs/deployment-output"; const Web3 = require("web3"); // HttpProvider does not support subscriptions for ganache-cli // let web3 = new Web3(Web3.givenProvider || "http://localhost:8545"); let web3 = new Web3( new Web3.providers.WebsocketProvider("ws://localhost:8545") ); export let setProvider = (newProvider: string) => { web3.setProvider(newProvider); }; export let getProvider = () => { return web3.currentProvider; }; export let deploySmartContractSync = ( contractInfo: CompilationResult, accountInfo: AccountInfo, args?: any[] ) => { return new Promise<DeploymentOutput>((resolve, reject) => { try { let contractEncoding = encodeSmartContract( contractInfo.abi, contractInfo.bytecode, args ); let deploymentResult = new DeploymentResult(contractInfo.contractName); contractEncoding[0] .deploy(contractEncoding[1]) .send(formatJsonInput(accountInfo)) .on("error", (error: any) => { reject( new DeploymentError(contractInfo.contractName, error.toString()) ); }) .on("receipt", (receipt: any) => { deploymentResult.gasCost = receipt.gasUsed; deploymentResult.transactionHash = receipt.transactionHash; }) .then((contractInstance: any) => { deploymentResult.contractAddress = contractInstance.options.address; resolve(deploymentResult); }) .catch((error: any) => { console.log(error); reject( new DeploymentError(contractInfo.contractName, error.toString()) ); }); } catch (error) { reject(new DeploymentError(contractInfo.contractName, error.toString())); } }); }; export let deploySmartContractAsync = ( contractInfo: CompilationResult, accountInfo: AccountInfo, args?: any[] ) => { return new Promise<any>((resolve, reject) => { try { let contractEncoding = encodeSmartContract( contractInfo.abi, contractInfo.bytecode, args ); contractEncoding[0] .deploy(contractEncoding[1]) .send(formatJsonInput(accountInfo)) .on("error", (error: any) => { reject( new DeploymentError(contractInfo.contractName, error.toString()) ); }) .on("transactionHash", (transactionHash: any) => { resolve(transactionHash); }) .catch((error: any) => { reject( new DeploymentError(contractInfo.contractName, error.toString()) ); }); } catch (error) { reject(new DeploymentError(contractInfo.contractName, error.toString())); } }); }; let encodeSmartContract = ( contractAbi: string, contractBytecode: string, args?: any[] ) => { let deploy_contract = new web3.eth.Contract(JSON.parse(contractAbi)); let payload = args ? { data: contractBytecode, arguments: args, } : { data: contractBytecode, }; return [deploy_contract, payload]; }; export let execContractFunctionSync = ( contractAddress: string, contractAbi: string, functionInfo: FunctionInfo, accountInfo: AccountInfo, args?: Array<any> ) => { return new Promise<DeploymentOutput>((resolve, reject) => { let encodedFunction = encodeFunctionCall(functionInfo, contractAbi, args); web3.eth .sendTransaction({ from: accountInfo.from, to: contractAddress, data: encodedFunction, gas: accountInfo.gas, }) .then((receipt) => { resolve( new DeploymentResult( functionInfo.functionName, receipt.transactionHash, contractAddress, receipt.gasUsed ) ); }) .catch((error: any) => { reject( new DeploymentError(functionInfo.functionName, error.toString()) ); }); }); }; export let execContractFunctionAsync = ( contractAddress: string, contractAbi: string, functionInfo: FunctionInfo, accountInfo: AccountInfo, args?: Array<any> ) => { return new Promise<any>((resolve, reject) => { try { let encodedFunction = encodeFunctionCall(functionInfo, contractAbi, args); web3.eth .sendTransaction({ from: accountInfo.from, to: contractAddress, data: encodedFunction, gas: accountInfo.gas, }) .once("transactionHash", (transactionHash) => { resolve(transactionHash); }) .on("error", (error: any) => { print(error, TypeMessage.error); reject( new PromiseError( `Invalid execution of function ${functionInfo.functionName}`, error, [new Component("ethereum-adapter", "executeContractFunctionSync")] ) ); }); } catch (error) { print(error, TypeMessage.error); reject( new PromiseError( `Invalid execution of function ${functionInfo.functionName}`, error, [new Component("ethereum-adapter", "executeContractFunctionSync")] ) ); } }); }; export let callContractFunction = ( contractAddress: string, contractAbi: string, functionInfo: FunctionInfo, accountInfo: AccountInfo, args?: Array<any> ) => { return new Promise<any>((resolve, reject) => { try { let encodedFunction = encodeFunctionCall(functionInfo, contractAbi, args); web3.eth .call({ to: contractAddress, data: encodedFunction, gas: accountInfo.gas, }) .then((callResult: string) => { resolve( functionInfo.fullInfo ? decodeParametersFull(functionInfo.returnType, callResult) : decodeParameter(functionInfo.returnType, callResult) ); }) .catch((error: any) => { reject( new PromiseError( `Error calling function ${functionInfo.functionName}`, error, [new Component("ethereum-adapter", "callContractFunction")] ) ); }); } catch (error) { reject( new PromiseError( `Error Encoding function ${functionInfo.functionName}`, error, [new Component("ethereum-adapter", "callContractFunction")] ) ); } }); }; export let isValidBlockchainAddress = (address: string): boolean => { if (address === "0x0000000000000000000000000000000000000000") return false; return web3.utils.isAddress(address); }; export let isValidBlockchainAddressList = (addresses: Array<string>) => { for (let i = 0; i < addresses.length; i++) if (!isValidBlockchainAddress(addresses[i])) return false; return true; }; export let defaultDeployment = () => { return new Promise<AccountInfo>((resolve, reject) => { Promise.all([web3.eth.getAccounts(), web3.eth.getGasPrice()]).then( (res) => { resolve(new AccountInfo(res[0][0], web3.utils.toHex(4700000), res[1])); } ); }); }; export let subscribeToLog = async ( contractAddress: string, contractAbi: string, eventInfo: FunctionInfo, functionCallback: any ) => { try { let subscription = web3.eth.subscribe( "logs", { fromBlock: await web3.eth.getBlockNumber(), address: contractAddress, topics: [encodeEventFromAbi(eventInfo, contractAbi)], }, (error: any, result: any) => { if (result) { { web3.eth .getTransactionReceipt(result.transactionHash) .then((transactionInfo) => { functionCallback( result.transactionHash, transactionInfo.gasUsed, decodeEventLogFromAbi(eventInfo, contractAbi, result.data) ); subscription.unsubscribe(); }); } } else { functionCallback("", error); subscription.unsubscribe(); } } ); } catch (error) { print("ERROR IN ETHEREUM ADAPTER", TypeMessage.error); print(error, TypeMessage.error); printSeparator(); } }; export let listenForTransactionMined = async ( transactionHash: string, functionCallback: any ) => { web3.eth .getTransactionReceipt(transactionHash) .then((transactionInfo: any) => { if (transactionInfo) { functionCallback(transactionHash, transactionInfo); } else { subscribeToNewBlock(transactionHash, functionCallback); } }); }; let subscribeToNewBlock = (transactionHash: string, functionCallback: any) => { let subscription = web3.eth .subscribe("newBlockHeaders") .on("data", (blockHeader: any) => { web3.eth .getTransactionReceipt(transactionHash) .then((transactionInfo: any) => { if (transactionInfo) { functionCallback(transactionHash, transactionInfo); subscription.unsubscribe(); } }); }) .on("error", (error: any) => { console.log(error); }); }; export let toBinaryArray = (inputNumber: any) => { return parseInt(inputNumber).toString(2).split("").reverse(); }; ////////////////////////////////////////////// ////////////// PRIVATE FUNCTIONS ///////////// ////////////////////////////////////////////// let encodeEventFromAbi = (eventInfo: FunctionInfo, contractAbi: string) => { let eventAbi = extractEventFromAbi(eventInfo, contractAbi); return eventAbi ? web3.eth.abi.encodeEventSignature(eventAbi) : undefined; }; let decodeEventLogFromAbi = ( eventInfo: FunctionInfo, contractAbi: string, encodedData: string ) => { let eventAbi = extractEventFromAbi(eventInfo, contractAbi); return eventAbi ? web3.eth.abi.decodeLog(eventAbi.inputs, encodedData) : undefined; }; let decodeParametersFull = (paramTypes: string, data: string) => { let paramList = paramTypes.split(","); let decoded = web3.eth.abi.decodeParameters(paramList, data); return decoded; }; let decodeParameter = (paramType: string, data: string) => { let decoded = web3.eth.abi.decodeParameter(paramType, data); if (paramType.includes("bytes32")) { if (decoded instanceof Array) return decoded.map((element) => { return web3.utils.hexToUtf8(element); }); return web3.utils.hexToUtf8(decoded); } return decoded; }; let extractEventFromAbi = (eventInfo: FunctionInfo, contractAbi: string) => { let jsonAbi: Array<any> = JSON.parse(contractAbi); return jsonAbi.find((element) => { if ( element.name !== eventInfo.functionName || eventInfo.paramTypes.length !== element.inputs.length ) { return false; } let input: Array<any> = element.inputs; for (let i = 0; i < input.length; i++) { if (input[i].type !== eventInfo.paramTypes[i]) return false; } return true; }); }; let encodeParameters = (types: Array<string>, values: Array<any>) => { return web3.eth.abi.encodeParameters( types, fixBytes32(types, valuesToString(values)) ); }; let encodeFunctionCall = ( functionInfo: FunctionInfo, contractAbi: string, parameters: Array<any> ) => { let jsonAbi: Array<any> = JSON.parse(contractAbi); let functionAbi = jsonAbi.find((element) => { if ( element.name !== functionInfo.functionName || functionInfo.paramTypes.length !== element.inputs.length ) { return false; } let input: Array<any> = element.inputs; for (let i = 0; i < input.length; i++) { if (input[i].type !== functionInfo.paramTypes[i]) return false; } return true; }); let fixedParams = parameters ? fixBytes32(functionInfo.paramTypes, valuesToString(parameters)) : []; return functionAbi ? web3.eth.abi.encodeFunctionCall(functionAbi, fixedParams) : undefined; }; let valuesToString = (values: Array<any>): Array<any> => { let fixedValues: Array<any> = values.map((element) => { if (element instanceof Array) { let res: Array<any> = valuesToString(element); return res; } else { return element.toString(); } }); return fixedValues; }; let fixBytes32 = (types: Array<string>, values: Array<any>) => { for (let i = 0; i < types.length; i++) { if (types[i] === "bytes32") { if ((values[i] as string).length > 32) values[i] = (values[i] as string).slice(0, 31); values[i] = web3.utils.fromAscii(values[i]); } } return values; }; let formatJsonInput = (accountInfo: AccountInfo) => { return { from: accountInfo.from, gas: accountInfo.gas, gasPrice: accountInfo.gasPrice, }; };
the_stack
let DaclFlags = { 'NO_ACCESS_CONTROL': 'NULL_ACL', 'AR': 'SE_DACL_AUTO_INHERIT_REQ ', 'AI': 'SE_DACL_AUTO_INHERITED ', 'P': 'SE_DACL_PROTECTED' } let AceTypes = { 'A': 'ALLOW', 'D': 'DENY' } let AceFlags = { 'CI': 'CONTAINER_INHERIT', 'OI': 'OBJECT_INHERIT', 'NP': 'NO_PROPAGATE_INHERIT', 'IO': 'INHERIT_ONLY', 'ID': 'INHERITED', 'SA': 'SUCCESSFUL_ACCESS', 'FA': 'FAILED_ACCESS' } let AccountSidsMap = { 'AN': 'Anonymous Logon', 'AO': 'Account Operators', 'RU': 'Alias to allow previous Windows 2000', 'AU': 'Authenticated Users', 'BA': 'Built-in Administrators', 'BG': 'Built in Guests', 'BO': 'Backup Operators', 'BU': 'Built-in Users', 'CA': 'Certificate Server Administrators', 'CG': 'Creator Group', 'CO': 'Creator Owner', 'DA': 'Domain Administrators', 'DC': 'Domain Computers', 'DD': 'Domain Controllers', 'DG': 'Domain Guests', 'DU': 'Domain Users', 'EA': 'Enterprise Administrators', 'ED': 'Enterprise Domain Controllers', 'WD': 'Everyone', 'PA': 'Group Policy Administrators', 'IU': 'Interactively logged-on user', 'LA': 'Local Administrator', 'LG': 'Local Guest', 'LS': 'Local Service Account', 'SY': 'Local System', 'NU': 'Network Logon User', 'NO': 'Network Configuration Operators', 'NS': 'Network Service Account', 'PO': 'Printer Operators', 'PS': 'Self', 'PU': 'Power Users', 'RS': 'RAS Servers group', 'RD': 'Terminal Server Users', 'RE': 'Replicator', 'RC': 'Restricted Code', 'SA': 'Schema Administrators', 'SO': 'Server Operators', 'SU': 'Service Logon User' } export var AccountSidsRevMap = { 'Anonymous Logon':'AN', 'Account Operators':'AO', 'Alias to allow previous Windows 2000':'RU', 'Authenticated Users':'AU', 'Built-in Administrators':'BA', 'Built in Guests':'BG', 'Backup Operators':'BO', 'Built-in Users':'BU', 'Certificate Server Administrators':'CA', 'Creator Group':'CG', 'Creator Owner':'CO', 'Domain Administrators':'DA', 'Domain Computers':'DC', 'Domain Controllers':'DD', 'Domain Guests':'DG', 'Domain Users':'DU', 'Enterprise Administrators':'EA', 'Enterprise Domain Controllers':'ED', 'Everyone':'WD', 'Group Policy Administrators':'PA', 'Interactively logged-on user':'IU', 'Local Administrator':'LA', 'Local Guest':'LG', 'Local Service Account':'LS', 'Local System':'SY', 'Network Logon User':'NU', 'Network Configuration Operators':'NO', 'Network Service Account':'NS', 'Printer Operators':'PO', 'Self':'PS', 'Power Users':'PU', 'RAS Servers group':'RS', 'Terminal Server sers':'RD', 'Replicator':'RE', 'Restricted Code':'RC', 'Schema Administrators':'SA', 'Server Operators':'SO', 'Service Logon User':'SU' } let AceRights = { // Generic access rights 'GA': 'GENERIC_ALL', 'GR': 'GENERIC_READ', 'GW': 'GENERIC_WRITE', 'GX': 'GENERIC_EXECUTE', // Standard access rights 'RC': 'READ_CONTROL', 'SD': 'DELETE', 'WD': 'WRITE_DAC', 'WO': 'WRITE_OWNER', // Directory service object access rights 'RP': 'ADS_RIGHT_DS_READ_PROP', 'WP': 'ADS_RIGHT_DS_WRITE_PROP', 'CC': 'ADS_RIGHT_DS_CREATE_CHILD', 'DC': 'ADS_RIGHT_DS_DELETE_CHILD', 'LC': 'ADS_RIGHT_ACTRL_DS_LIST', 'SW': 'ADS_RIGHT_DS_SELF', 'LO': 'ADS_RIGHT_DS_LIST_OBJECT', 'DT': 'ADS_RIGHT_DS_DELETE_TREE', 'CR': 'ADS_RIGHT_DS_CONTROL_ACCESS', // File access rights 'FA': 'FILE_ALL_ACCESS', 'FR': 'FILE_GENERIC_READ', 'FW': 'FILE_GENERIC_WRITE', 'FX': 'FILE_GENERIC_EXECUTE', // Registry key access rights 'KA': 'KEY_ALL_ACCESS', 'KR': 'KEY_READ', 'KW': 'KEY_WRITE', 'KX': 'KEY_EXECUTE', // Mandatory label rights 'NR': 'SYSTEM_MANDATORY_LABEL_NO_READ_UP', 'NW': 'SYSTEM_MANDATORY_LABEL_NO_WRITE_UP', 'NX': 'SYSTEM_MANDATORY_LABEL_NO_EXECUTE' } export var AceRightsRevMap = { // Generic access rights 'GENERIC_ALL': 'GA', 'GENERIC_READ':'GR', 'GENERIC_WRITE':'GW', 'GENERIC_EXECUTE':'GX', // Standard access rights 'READ_CONTROL':'RC', 'DELETE':'SD', 'WRITE_DAC':'WD', 'WRITE_OWNER':'WO', // Directory service object access rights 'ADS_RIGHT_DS_READ_PROP':'RP', 'ADS_RIGHT_DS_WRITE_PROP':'WP', 'ADS_RIGHT_DS_CREATE_CHILD':'CC', 'ADS_RIGHT_DS_DELETE_CHILD':'DC', 'ADS_RIGHT_ACTRL_DS_LIST':'LC', 'ADS_RIGHT_DS_SELF':'SW', 'ADS_RIGHT_DS_LIST_OBJECT':'LO', 'ADS_RIGHT_DS_DELETE_TREE':'DT', 'ADS_RIGHT_DS_CONTROL_ACCESS':'CR', // File access rights 'FILE_ALL_ACCESS':'FA', 'FILE_GENERIC_READ':'FR', 'FILE_GENERIC_WRITE':'FW', 'FILE_GENERIC_EXECUTE':'FX', // Registry key access rights 'KEY_ALL_ACCESS':'KA', 'KEY_READ':'KR', 'KEY_WRITE':'KW', 'KEY_EXECUTE':'KX', // Mandatory label rights 'SYSTEM_MANDATORY_LABEL_NO_READ_UP':'NR', 'SYSTEM_MANDATORY_LABEL_NO_WRITE_UP':'NW', 'SYSTEM_MANDATORY_LABEL_NO_EXECUTE':'NX' } export class SDDLParser{ parseSDDL(sddl:string):any{ let i:number = 0; let pos:number = 0; let blockMap:any = {}; let sddlObj:any = {}; sddlObj.value = sddl; while (i != -1) { i = sddl.indexOf(':', pos+1) if (i == -1) { break } else if (pos > 0) { blockMap[sddl[pos-1]] = sddl.substring(pos+1, i-1); } pos = i } if(pos > 0) { blockMap[sddl[pos-1]] = sddl.substring(pos+1); } //parse Onwer sddlObj.ownerValue = blockMap['O']; if(blockMap['O']){ if(AccountSidsMap[blockMap['O']]){ sddlObj.wellKnownOwner = AccountSidsMap[blockMap['O']]; }else{ sddlObj.owner = blockMap['O']; } } //parse Group if(blockMap['G']){ if(AccountSidsMap[blockMap['G']]){ sddlObj.wellKnownGroup = AccountSidsMap[blockMap['G']]; }else{ sddlObj.group = blockMap['G']; } } //parse DACL if(blockMap['D']){ sddlObj.dacl = this.parseDACL(blockMap['D']); } return sddlObj; } parseDaclFlags(flags:string):any{ let flagMap={}; let keys = Object.keys(DaclFlags); let incr = 0; while (flags.length > 0) { for (let i = 0; i < keys.length; i++) { let flag = keys[i] if(!flagMap[DaclFlags[flag]]){ flagMap[DaclFlags[flag]] = false; } if (flags.length >= flag.length && flags.substring(0, flag.length) == flag) { incr = flag.length flagMap[DaclFlags[flag]] = true; } } flags = flags.substring(incr) } return flagMap; } getAllRights() { let allRights = []; for(let k in AceRights){ allRights.push(AceRights[k]); } return allRights; } parseAceFlags(flags:string):any{ let flagMap={}; let keys = Object.keys(AceFlags); let incr = 0; while (flags.length > 0) { for (let i = 0; i < keys.length; i++) { let flag = keys[i] if(!flagMap[AceFlags[flag]]){ flagMap[AceFlags[flag]] = false; } if (flags.length >= flag.length && flags.substring(0, flag.length) == flag) { incr = flag.length flagMap[AceFlags[flag]] = true; } } flags = flags.substring(incr) } return flagMap; } parseAceRights(rights:string){ let rightMap={}; let keys = Object.keys(AceRights); let incr = 0; let rightsArr = []; while (rights.length > 0) { for (let i = 0; i < keys.length; i++) { let right = keys[i] if(!rightMap[AceRights[right]]){ rightMap[AceRights[right]] = false; } if (rights.length >= right.length && rights.substring(0, right.length) == right) { incr = right.length rightMap[AceRights[right]] = true; rightsArr.push({ 'value': right, 'details': AceRights[right] }) } } rights = rights.substring(incr) } return [rightsArr,rightMap]; } parseACEs(aceString:string):any{ let aceObj:any = {}; aceString = aceString.replace('(',''); aceString = aceString.replace(')',''); aceString = aceString.replace(')',''); aceObj.value = aceString; let aceComponents = aceString.split(';'); if(aceComponents.length < 6) return aceObj; //parse ACE type if(aceComponents[0].length > 0){ aceObj.type = {}; aceObj.type = AceTypes[aceComponents[0]]; } //parse ACE Flags if(aceComponents[1].length > 0){ aceObj.flagsMap = {}; aceObj.flagsMap = this.parseAceFlags(aceComponents[1]); } //parse rights if(aceComponents[2].length > 0){ aceObj.rightsMap = {}; aceObj.rightsArr = []; aceObj.rightsValue = aceComponents[2]; let retRights = this.parseAceRights(aceComponents[2]); aceObj.rightsArr = retRights[0]; aceObj.rightsMap = retRights[1]; } //parse Account SID if(aceComponents[5].length > 0){ if(AccountSidsMap[aceComponents[5]]){ aceObj.accountSID = AccountSidsMap[aceComponents[5]]; }else{ aceObj.accountSID = aceComponents[5]; } } return aceObj; } parseDACL(dacl:string):any{ let pos = dacl.indexOf('('); let flags = ''; let aces = ''; let daclObj:any = {}; if(pos != -1){ flags = dacl.substring(0,pos); aces = dacl.substring(pos); }else{ // If no ACEs are present flags = dacl; } // Parse the flags daclObj.daclFlags = this.parseDaclFlags(flags); // Parse the ACEs daclObj.aces = [] let acesArr = aces.split('('); for(let i = 0; i < acesArr.length; i++){ acesArr[i] = acesArr[i].trim(); if(acesArr[i].length){ daclObj.aces.push(this.parseACEs(acesArr[i] + ')')); } } return daclObj; } }
the_stack
import axios, { AxiosRequestConfig, AxiosResponse, AxiosInstance } from "axios"; import { notification, message, Modal } from 'ant-design-vue'; import { cloneLoop } from "@/lib/clone"; import cookies from 'vue-cookies'; import qs from 'qs'; /** 全局Assembly */ export const enum AssemblyResources { /** 解析MD5 */ md5 = 'md5' } export function getToken(key): string { let cookie = document.cookie.split(";").map(i => i ? i.trim() : '').find(str => str.startsWith(key + '=')); if (cookie) { const val = cookie?.split('=')?.[1]; return val || ''; } else { return ''; } }; /** 生成随机组件Id */ export function createModelId(len = 36) { let s: Array<string> = []; let hexDigits = "abcdefghijklmnopqrstuvwxyz"; for (let i = 0; i < len; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 26), 1); } // s[8] = s[13] = s[18] = s[23] = "-"; let uuid = s.join(""); return uuid; } /** 生成随机数字Id */ export function createNumberId(len = 36) { let s: Array<string> = []; let hexDigits = "0123456789"; for (let i = 0; i < len; i++) { s[i] = hexDigits.substr(Math.floor(Math.random() * 10), 1); } // s[8] = s[13] = s[18] = s[23] = "-"; let uuid = s.join(""); return uuid; } /** * 日期格式化 * @param {Date} [date=new Date()] 日期 * @param {string} [fmt='yyyy-MM-dd'] 格式化参数 * @return {string} 格式化后的日期 */ export function dateFormat(date: string | Date = new Date(), fmt: string = "yyyy-MM-dd"):string { if (!date) return ""; if (typeof(date) === 'string') date = new Date(date); // @ts-ignore if (date == 'Invalid Date') return ""; let o:object = { "M+" : date.getMonth()+1, //月份 "d+" : date.getDate(), //日 "H+" : date.getHours(), //小时 "m+" : date.getMinutes(), //分 "s+" : date.getSeconds(), //秒 "q+" : Math.floor((date.getMonth()+3)/3), //季度 "S" : date.getMilliseconds() //毫秒 }; let _fmt = fmt; if(/(y+)/.test(fmt)) _fmt = _fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)); for(let k in o) if(new RegExp("("+ k +")").test(_fmt)) _fmt = _fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); return _fmt; }; Date.prototype.format = function(fmt = 'yyyy-MM-dd') { return dateFormat(this, fmt); } /** 交互数组中两段数值的位置 */ export function arrChange(arr: Array<any>, num1: number, num2: number, num1length: number = 1, num2length: number = 1) { if(num1 > num2) [num1, num2, num1length, num2length] = [num2, num1, num2length, num1length]; return arr.slice(0, num1) .concat(arr.slice(num2, num2 + num2length)) .concat(arr.slice(num1 + num1length, num2)) .concat(arr.slice(num1, num1 + num1length)) .concat(arr.slice(num2 + num2length)); } /** 移动组件树中某一项的位置 */ export function moveNodeOfTree( tree: Array<any>, id: string | number, pid: string | number, insertSlotIndex?: number, prop: string = 'id' ) { let _tree = cloneLoop(tree); let _node = null; let _oldIndex = -1; let _orderIndex: number | undefined; let _isOver = false; const _cb = (parentNode, fn) => { if (parentNode?.children?.length) { for (let index = 0; index < parentNode.children.length; index++) { _isOver || _cb(parentNode.children[index], fn); let _re = fn(parentNode, index); if (_re) return; } } }; _cb({ children: _tree, id: '' }, (parentNode, index): boolean => { if (!_isOver) { if (parentNode.id == '') { if (parentNode.children[index].id == id) { _orderIndex = undefined; _isOver = true; return true; } } else { for (let i = 0; i < parentNode.children[index].length; i++) { if (parentNode.children[index][i].id == id) { _orderIndex = i; _isOver = true; return true; } } } } return false; }); _isOver = false; _cb({ children: _tree, id: '' }, (parentNode, index): boolean => { if (!_isOver) { if (_orderIndex != undefined) { if (parentNode.children[index][_orderIndex]?.[prop] == id) { _oldIndex = index; _node = parentNode.children[index][_orderIndex]; parentNode.children[index].splice(_orderIndex, 1); _isOver = true; return true; } } else if (parentNode.children[index][prop] == id) { _oldIndex = index; _node = parentNode.children[index]; parentNode.children.splice(index, 1); _isOver = true; return true; } } return false; }); if (!pid) { _tree.push(_node); return _tree; } else { _isOver = false; _cb({ children: _tree, id: '' }, (parentNode, index): boolean => { if (!_isOver) { if (insertSlotIndex == undefined) { if (parentNode.id == '') { let _insertIndex = pid ? parentNode.children.findIndex(i => i.id == pid) : parentNode.children.length; parentNode.children.splice(_insertIndex, 0, _node); _isOver = true; return true; } } else if (parentNode.children[index][prop] == pid && insertSlotIndex != undefined && _node) { parentNode.children[index].children[insertSlotIndex].push(_node); _isOver = true; return true; } } return false; }); } return _tree; } /** 获取LocalStorage的值 */ export function getLocalstorge(item: string): string | null { return window.localStorage.getItem(item) || null; } //Base64转Buffer export function base64ToBuffer(b: string): Uint8Array { const str = atob(b); const buffer = new Uint8Array(str.length); for (let i = 0; i < str.length; i++) { buffer[i] = str.charCodeAt(i); } return buffer; } export function initAPI(api: object) { let re = {}; const fn = (parent: any, reParent: any, url: string) => { if (parent) { Object.keys(parent).forEach((key: string) => { if (parent[key]) { if (typeof parent[key] !== 'function') { reParent[key] = {}; fn(parent[key], reParent[key], `${url.endsWith('/') ? (url + '/') : url}${key}`); } else { reParent[key] = parent[key].bind(`${url}/${key}/`); } } }); } }; fn(api, re, ''); return re; }; let loginExpired = false; const default_config = { timeout: 30000 }; /** * Get请求 * @param {string} url URL地址 * @param {object} params 参数 * @param {AxiosRequestConfig} config */ export function get(url: string, params?: object, config: AxiosRequestConfig = {}, _axios: AxiosInstance = axios):Promise<any> { loginExpired = false; return new Promise((resolve, reject) => { _axios.get(url, { cancelToken: new axios.CancelToken(cancel => config.cancel = cancel), params: { ...params }, ...config, ...default_config, headers: { Authorization: getToken('Authorization') || '', ...config.headers }, }).then(d => { if (d.data.isSuccess !== false) { resolve(d.data.result || d.data); } else { Modal.error({ title: '警告', content: d.data.errors.message, }); console.error(d.data.exception); } }).catch(err => { if (err.response && err.response.status == 401) { if (!loginExpired) { localStorage.removeItem('Authorization'); // message.info('登录超时,请重新登陆。'); notification.warning({ message: '系统提示', description: '登录超时,请重新登陆。', }); loginExpired = true; } else { setTimeout(() => { loginExpired = false; }, 1000); } reject(err); return; } if (err.response && err.response.data) { notification.error({ message: '[Get Error]' + url, description: err.response.data.errMsg, }); console.error(err.response.data.errMsg); } else if (err.message) { notification.error({ message: '[Get Error]' + url, description: err.message, }); console.error(err.message); } reject(err); }) }); }; /** * Post请求 * @param {string} url URL地址 * @param {object} params 参数 * @param {AxiosRequestConfig} config */ export function post(url: string, params: object = {}, config: AxiosRequestConfig = {}, _axios: AxiosInstance = axios):Promise<any> { return new Promise((resolve, reject) => { let _headers = { 'Content-Type': 'application/json', Authorization: getToken('Authorization') || '', ...config.headers }; _axios.post(url, _headers['Content-Type'] == 'application/x-www-form-urlencoded' ? qs.stringify({ ...params }) : { ...params }, { cancelToken: new axios.CancelToken(cancel => config.cancel = cancel), ...default_config, ...config, headers: _headers }).then(d => { if (d.data.isSuccess !== false) { resolve(d.data.result || d.data); } else { Modal.error({ title: '警告', content: d.data.errors.message, }); console.error(d.data.exception); } }).catch(err => { if(err.response && err.response.data) { notification.error({ message: '[Post Error]' + url, description: err.response.data.errMsg || err.response.data.title, }); console.error(err.response.data.errMsg); } else if(err.response) { notification.error({ message: '[Post Error]' + url, description: err.message, }); console.error(err.message); } reject(err); }); }); }; /** * Upload请求 * @param {string} url URL地址 * @param {object} params 参数 * @param {AxiosRequestConfig} config */ export function upload(url: string, params: object, config: AxiosRequestConfig = {}, _axios: AxiosInstance = axios):Promise<any> { return new Promise((resolve, reject) => { let _params = new FormData(); Object.entries(params).forEach(([key, value]) => { _params.append(key, value); }); _axios.post(url, _params, { cancelToken: new axios.CancelToken(cancel => config.cancel = cancel), ...config, headers: { Authorization: getToken('Authorization') || '', "Content-Type": "multipart/form-data", ...config.headers }, }).then(d => { resolve(d.data); }).catch(err => { if(err.response && err.response.data) { notification.error({ message: '[Upload Error]' + url, description: err.response.data.errMsg || err.response.data.title, }); console.error(err.response.data.errMsg); } else if(err.response) { notification.error({ message: '[Upload Error]' + url, description: err.message, }); console.error(err.message); } reject(err); }); }); }; /** 获取默认的分页参数 */ export function getPagination(config: object = {}): object { return { pageSizeOptions: ['10', '20', '40'], showQuickJumper: true, showSizeChanger: true, defaultCurrent: 1, current: 1, defaultPageSize: 10, ...config }; } /** 将数字插入千分位符 */ export function thousandNum(money: number | string): string { if(!isNaN(Number(money))) { return money.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } else { throw new TypeError('添加千分位符失败,当前参数为:' + money); } } /** 筛选对象的属性 */ export function filterObj(obj: Record<string, any>, outKeys: string[] = [], inKeys: string[] = []): Record<string, any> { let keys = Object.keys(obj); if (outKeys.length) { keys = keys.filter(i => !outKeys.includes(i)); } if (inKeys.length) { keys = keys.filter(i => inKeys.includes(i)); } // @ts-ignore return Object.assign.apply({}, [{}].concat(keys.map(i => ({ [i]: obj[i] })))); } /** 获取Url参数 */ export function getParams() { return new URLSearchParams(location.search.replace(/\?/ig, "")); } function fakeClick(obj) { let ev = document.createEvent("MouseEvents"); ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); obj.dispatchEvent(ev); } /** 下载文件 */ export function downLoadFile(name: string, data: string) { let urlObject = window.URL || window.webkitURL || window; let export_blob = new Blob([data]); let save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a") save_link.setAttribute('href', urlObject.createObjectURL(export_blob)); save_link.setAttribute('download', name); fakeClick(save_link); } /** 递归函数 */ export function recursive(formVariables: Array<Record<string, any>>, callback?: { filter?: (variable: Record<string, any>, chain: Array<Record<string, any>>) => boolean, map?: (variable: Record<string, any>, chain: Array<Record<string, any>>) => any }, childField: string = 'children'): Array<Record<string, any>> { if (!callback) { return formVariables; } let _list: Array<Record<string, any>> = []; // 递归 const _cb = (newParent: Record<string, any>, parent: Record<string, any>, chain: Array<Record<string, any>>) => { if (callback?.filter?.(newParent, chain) === false) { return; } let _item = { ...parent, children: [] }; chain.push(_item); if (parent?.children?.length) { for (let i = 0; i < parent.children.length; i++) { _cb(_item, parent.children[i], chain); } } newParent.children.push(callback.map?.(_item, chain) || _item); }; formVariables.forEach(item => { let _item = { ...item, children: [] }; if (callback?.filter?.(_item, []) === false) { return; } if (item?.children?.length) { for (let i = 0; i < item.children.length; i++) { _cb(_item, item.children[i], [_item]); } } _list.push(callback.map?.(_item, [_item]) || _item); }); return _list; } export default { getToken, dateFormat, getLocalstorge, initAPI, get, post, getPagination, thousandNum, getParams, downLoadFile, recursive, filterObj };
the_stack
import { BunyanProvider, Logger, LogLevel } from './BunyanProvider' import { ImproperSeekToBlockError, ImproperStartAtBlockError, ReloadHistoryError, UnresolvedForkError, } from './errors' import { ActionReader, ActionReaderOptions, Block, BlockInfo, BlockMeta, NextBlock, ReaderInfo, } from './interfaces' const defaultBlock: Block = { blockInfo: { blockNumber: 0, blockHash: '', previousBlockHash: '', timestamp: new Date(0), }, actions: [], } /** * Reads blocks from a blockchain, outputting normalized `Block` objects. */ export abstract class AbstractActionReader implements ActionReader { protected startAtBlock: number protected headBlockNumber: number = 0 protected currentBlockNumber: number protected onlyIrreversible: boolean protected currentBlockData: Block = defaultBlock protected lastIrreversibleBlockNumber: number = 0 protected blockHistory: Block[] = [] protected log: Logger protected initialized: boolean = false constructor(options: ActionReaderOptions = {}) { const optionsWithDefaults = { startAtBlock: 1, onlyIrreversible: false, logSource: 'AbstractActionReader', logLevel: 'info' as LogLevel, ...options, } this.startAtBlock = optionsWithDefaults.startAtBlock this.currentBlockNumber = optionsWithDefaults.startAtBlock - 1 this.onlyIrreversible = optionsWithDefaults.onlyIrreversible this.log = BunyanProvider.getLogger(optionsWithDefaults) } /** * Loads, processes, and returns the next block, updating all relevant state. Return value at index 0 is the `Block` * instance; return value at index 1 boolean `isRollback` determines if the implemented `AbstractActionHandler` needs * to potentially reverse processed blocks (in the event of a fork); return value at index 2 boolean `isNewBlock` * indicates if the `Block` instance returned is the same one that was just returned from the last call of * `nextBlock`. */ public async getNextBlock(): Promise<NextBlock> { const blockMeta: BlockMeta = { isRollback: false, isNewBlock: false, isEarliestBlock: false, } if (!this.initialized) { this.log.info('Action Reader was not initialized before started, so it is being initialized now') await this.initialize() } this.log.debug('Getting last irreversible block number...') const lastIrreversibleStart = Date.now() this.lastIrreversibleBlockNumber = await this.getLastIrreversibleBlockNumber() const lastIrreversibleTime = Date.now() - lastIrreversibleStart this.log.debug( `Got last irreversible block number: ${this.lastIrreversibleBlockNumber} (${lastIrreversibleTime}ms)` ) if (this.currentBlockNumber === this.headBlockNumber) { this.headBlockNumber = await this.getLatestNeededBlockNumber() } if (this.currentBlockNumber < this.headBlockNumber) { const unvalidatedBlockData = await this.loggedGetBlock( this.currentBlockNumber + 1, 'next block' ) const expectedHash = this.currentBlockData.blockInfo.blockHash const actualHash = this.currentBlockNumber ? unvalidatedBlockData.blockInfo.previousBlockHash : defaultBlock.blockInfo.blockHash if (expectedHash === actualHash) { this.acceptBlock(unvalidatedBlockData) blockMeta.isNewBlock = true } else { this.logForkDetected(unvalidatedBlockData, expectedHash, actualHash) await this.resolveFork() blockMeta.isNewBlock = true blockMeta.isRollback = true // Reset for safety, as new fork could have less blocks than the previous fork this.headBlockNumber = await this.getLatestNeededBlockNumber() } } blockMeta.isEarliestBlock = this.currentBlockNumber === this.startAtBlock return { block: this.currentBlockData, blockMeta, lastIrreversibleBlockNumber: this.lastIrreversibleBlockNumber, } } /** * Performs all required initialization for the reader. */ public async initialize(): Promise<void> { this.log.debug('Initializing Action Reader...') const setupStart = Date.now() await this.setup() const betweenSetupAndInit = Date.now() await this.initBlockState() this.initialized = true const setupTime = betweenSetupAndInit - setupStart const initTime = Date.now() - betweenSetupAndInit const initializeTime = setupTime + initTime this.log.debug( `Initialized Action Reader (${setupTime}ms setup + ${initTime}ms block state init = ${initializeTime}ms)` ) } /** * Changes the state of the `AbstractActionReader` instance to have just processed the block at the given block * number. If the block exists in its temporary block history, it will use this, otherwise it will fetch the block * using `getBlock`. * * The next time `nextBlock()` is called, it will load the block after this input block number. */ public async seekToBlock(blockNumber: number): Promise<void> { this.log.debug(`Seeking to block ${blockNumber}...`) const seekStart = Date.now() this.headBlockNumber = await this.getLatestNeededBlockNumber() if (blockNumber < this.startAtBlock) { throw new ImproperStartAtBlockError(blockNumber, this.startAtBlock) } if (blockNumber > this.headBlockNumber + 1) { throw new ImproperSeekToBlockError(blockNumber) } this.currentBlockNumber = blockNumber - 1 await this.reloadHistory() const seekTime = Date.now() - seekStart this.log.debug(`Seeked to block ${blockNumber} (${seekTime}ms)`) } /** * Information about the current state of the Action Reader */ public get info(): ReaderInfo { return { currentBlockNumber: this.currentBlockNumber, startAtBlock: this.startAtBlock, headBlockNumber: this.headBlockNumber, onlyIrreversible: this.onlyIrreversible, lastIrreversibleBlockNumber: this.lastIrreversibleBlockNumber, } } /** * Loads the number of the latest block. */ protected abstract async getHeadBlockNumber(): Promise<number> /** * Loads the number of the most recent irreversible block. */ protected abstract async getLastIrreversibleBlockNumber(): Promise<number> /** * Loads a block with the given block number, returning a promise for a `Block`. * * @param blockNumber The number of the block to load */ protected abstract async getBlock(blockNumber: number): Promise<Block> /** * Idempotently performs any required setup. */ protected abstract async setup(): Promise<void> /** * Incrementally rolls back reader state one block at a time, comparing the blockHistory with * newly fetched blocks. Fork resolution is finished when either the current block's previous hash * matches the previous block's hash, or when history is exhausted. */ protected async resolveFork() { if (this.blockHistory.length === 0) { await this.addPreviousBlockToHistory() } // Pop off blocks from cached block history and compare them with freshly fetched blocks while (this.blockHistory.length > 0) { if (this.blockHistory.length === 0) { await this.addPreviousBlockToHistory() } const [previousBlockData] = this.blockHistory.slice(-1) this.log.info(`Refetching Block ${this.currentBlockData.blockInfo.blockNumber}...`) this.currentBlockData = await this.loggedGetBlock( this.currentBlockData.blockInfo.blockNumber, 'resolving fork', ) const { blockInfo: currentBlockInfo } = this.currentBlockData const { blockInfo: previousBlockInfo } = previousBlockData if (currentBlockInfo.previousBlockHash === previousBlockInfo.blockHash) { this.logForkResolved(currentBlockInfo, previousBlockInfo) break } this.logForkMismatch(currentBlockInfo, previousBlockInfo) this.currentBlockData = previousBlockData this.blockHistory.pop() } if (this.blockHistory.length === 0) { await this.addPreviousBlockToHistory() } this.currentBlockNumber = this.blockHistory[this.blockHistory.length - 1].blockInfo.blockNumber + 1 } private async initBlockState() { this.lastIrreversibleBlockNumber = await this.getLastIrreversibleBlockNumber() this.headBlockNumber = await this.getLatestNeededBlockNumber() if (this.currentBlockNumber < 0) { this.currentBlockNumber = this.headBlockNumber + this.currentBlockNumber this.startAtBlock = this.currentBlockNumber + 1 } await this.reloadHistory() } private async getLatestNeededBlockNumber() { if (this.onlyIrreversible) { return this.lastIrreversibleBlockNumber } else { const headBlockFetchStart = Date.now() this.log.debug('Getting head block number...') const headBlockNumber = await this.getHeadBlockNumber() const headBlockFetchTime = Date.now() - headBlockFetchStart this.log.debug(`Got head block number: ${headBlockNumber} (${headBlockFetchTime}ms)`) return headBlockNumber } } private acceptBlock(blockData: Block) { this.blockHistory.push(this.currentBlockData) this.pruneHistory() this.currentBlockData = blockData this.currentBlockNumber = this.currentBlockData.blockInfo.blockNumber } private range(start: number, end: number): number[] { if (start > end) { return [] } return Array(end - start).fill(0).map((_, i: number) => i + start) } private pruneHistory() { let toDelete = 0 for (const block of this.blockHistory) { if (block.blockInfo.blockNumber < this.lastIrreversibleBlockNumber) { toDelete += 1 } else { break } } if (toDelete === this.blockHistory.length) { this.blockHistory = [this.blockHistory[this.blockHistory.length - 1]] return } this.blockHistory.splice(0, toDelete) } private async reloadHistory(maxTries = 10) { if (this.currentBlockNumber === 0) { this.blockHistory = [] this.currentBlockData = defaultBlock return } if (this.currentBlockNumber === 1) { this.blockHistory = [defaultBlock] this.currentBlockData = await this.loggedGetBlock( 1, 'reloading history first block edge case' ) return } let historyRange = this.range(this.lastIrreversibleBlockNumber, this.currentBlockNumber + 1) if (historyRange.length <= 1) { historyRange = [this.currentBlockNumber - 1, this.currentBlockNumber] } let microForked = true let tryCount = 0 while (microForked) { microForked = false this.blockHistory = [] for (const blockNumber of historyRange) { const historyBlock = await this.loggedGetBlock( blockNumber, 'reloading history' ) if (this.blockHistory.length === 0) { this.blockHistory.push(historyBlock) continue } const latestHistoryBlockHash = this.blockHistory[this.blockHistory.length - 1].blockInfo.blockHash if (latestHistoryBlockHash !== historyBlock.blockInfo.previousBlockHash) { this.log.info('Microforked while reloading history!') this.log.info(` EXPECTED: ${latestHistoryBlockHash}`) this.log.info(` RECEIVED: ${historyBlock.blockInfo.previousBlockHash}`) this.log.info(`Scrapping history and trying again (try ${tryCount + 1})`) microForked = true break } this.blockHistory.push(historyBlock) } tryCount += 1 if (tryCount === maxTries) { throw new ReloadHistoryError() } } this.currentBlockData = this.blockHistory.pop()! } private async addPreviousBlockToHistory(checkIrreversiblility: boolean = true) { if (this.currentBlockData.blockInfo.blockNumber < this.lastIrreversibleBlockNumber && checkIrreversiblility) { throw new UnresolvedForkError() } this.blockHistory.push( await this.loggedGetBlock( this.currentBlockData.blockInfo.blockNumber - 1, 'populating history', ) ) } private async loggedGetBlock(blockNumber: number, logContext: string): Promise<Block> { const getBlockStart = Date.now() this.log.debug(`Getting block ${blockNumber}... (${logContext})`) const block = await this.getBlock(blockNumber) const getBlockFetchTime = Date.now() - getBlockStart this.log.debug(`Got block ${blockNumber} (${getBlockFetchTime}ms; ${block.actions.length} actions)`) return block } private logForkDetected(unvalidatedBlockData: Block, expectedHash: string, actualHash: string) { this.log.info('!! FORK DETECTED !!') this.log.info(` MISMATCH:`) this.log.info(` ✓ NEW Block ${unvalidatedBlockData.blockInfo.blockNumber} previous: ${actualHash}`) this.log.info(` ✕ OLD Block ${this.currentBlockNumber} id: ${expectedHash}`) } private logForkResolved(currentBlockInfo: BlockInfo, previousBlockInfo: BlockInfo) { this.log.info(' MATCH:') this.log.info(` ✓ NEW Block ${currentBlockInfo.blockNumber} previous: ${currentBlockInfo.previousBlockHash}`) // tslint:disable-line this.log.info(` ✓ OLD Block ${previousBlockInfo.blockNumber} id: ${previousBlockInfo.blockHash}`) this.log.info('!! FORK RESOLVED !!') } private logForkMismatch(currentBlockInfo: BlockInfo, previousBlockInfo: BlockInfo) { this.log.info(' MISMATCH:') this.log.info(` ✓ NEW Block ${currentBlockInfo.blockNumber} previous: ${currentBlockInfo.previousBlockHash}`) this.log.info(` ✕ OLD Block ${previousBlockInfo.blockNumber} id: ${previousBlockInfo.blockHash}`) } }
the_stack
import { isSingleText, isAlignCenter, isOnlyContainer, utils } from "./handleTypeLayout"; import { CLASS_TYPE } from './const'; import { Layer } from './types'; /** * 规则 * 1.父元素width不为auto * @param {Array} data * @param {Object} parent */ const isTowSpan = (data: Layer[], parent: Layer) => { // if (data.length == 2 && parent.structure.width != "auto") { if (data.length == 2 && parent) { let firstItem = data[0]; let secondItem = data[1]; if ( firstItem.structure.x + firstItem.structure.width / 2 < parent.structure.x + parent.structure.width / 2 && secondItem.structure.x >= parent.structure.x + parent.structure.width / 2 && (secondItem.structure.x - firstItem.structure.x - firstItem.structure.width) * 0.2 > parent.structure.width + parent.structure.x - secondItem.structure.x - secondItem.structure.width && parent.structure.width > 750 * 0.7 ) { return true; } } }; const layoutTowSpan = (data: Layer[], parent: Layer) => { let firstItem = data[0]; let secondItem = data[1]; firstItem.class_name = 'left'; firstItem.class_type = CLASS_TYPE.RELY_ON_PARENT; secondItem.class_name = 'right'; secondItem.class_type = CLASS_TYPE.RELY_ON_PARENT; parent.style = { ...parent.style, display: "flex", justifyContent: "space-between", flexDirection: 'row', }; if (utils.isAlignMiddle(data, parent)) { if (!utils.isSameParentHeight(data, parent)) { parent.style = { ...parent.style, alignItems: "center" }; } } else { firstItem.style = { ...firstItem.style, marginTop: firstItem.structure.y - parent.structure.y }; secondItem.style = { ...secondItem.style, marginTop: secondItem.structure.y - parent.structure.y }; } firstItem.style = { ...firstItem.style, marginLeft: firstItem.structure.x - parent.structure.x }; if (isSingleText(firstItem) || isOnlyContainer(firstItem)) { delete firstItem.style.width; } secondItem.style = { ...secondItem.style, marginRight: parent.structure.x + parent.structure.width - secondItem.structure.x - secondItem.structure.width }; if ( isSingleText(secondItem) || (isOnlyContainer(secondItem) && secondItem.children && secondItem.children.length < 2) ) { delete secondItem.style.width; } return data; }; // 判断是否是图片文案居中的情况 const isimgTextCeneter = (data: Layer[], parent: Layer) => { if (data.length !== 2) return false; // 只有两个元素的情况 const isAlignCenter = (data, parent) => { // 两个元素组合位于父元素中间 let firstItem = data[0]; let secondItem = data[1]; let leftDis = firstItem.structure.x - parent.structure.x; let rightDis = parent.structure.x + parent.structure.width - secondItem.structure.x - secondItem.structure.width; return Math.abs(leftDis - rightDis) < 2; }; let existImgLayer = data.find(item => item.type == "Image"); let existTextLayer = data.find(item => item.type == "Text"); if (existImgLayer && existTextLayer && isAlignCenter(data, parent)) { return true; } return false; }; const layoutImgTextCeneter = (data: Layer[], parent: Layer) => { let firstItem = data[0]; let secondItem = data[1]; if ( isSingleText(firstItem) ) { delete firstItem.style.width; } if ( isSingleText(secondItem) ) { delete secondItem.style.width; } parent.style = { ...parent.style, display: "flex", flexDirection: 'row', }; if (!utils.isHorizontalCloseParent(data, parent)) { parent.style = { ...parent.style, justifyContent: "center" }; } if (utils.isAlignMiddle(data, parent)) { if (!utils.isVerticalCloseParent(data, parent)) { parent.style = { ...parent.style, alignItems: "center" }; } } else { for (let item of data) { item.style = { ...item.style, marginTop: item.structure.y - parent.structure.y } } } secondItem.style = { ...secondItem.style, marginLeft: secondItem.structure.x - firstItem.structure.x - firstItem.structure.width }; return data; }; const isEqualBolck = (data: Layer[], parent: Layer) => { if ( data.length >= 2 && utils.isEqualWidth(data) && utils.isEqualHeight(data) && utils.isSameSpacing(data) && data[0].structure.x == parent.structure.x && Math.abs( data[data.length - 1].structure.x + data[data.length - 1].structure.width - parent.structure.x - parent.structure.width ) < 2 ) { // 至少两个子元素 return true; } return false; }; const layoutEqualBlock = (data: Layer[], parent: Layer) => { parent.style = { ...parent.style, display: "flex", justifyContent: "space-between" }; data = data.map(item => { item.class_name = 'li'; item.class_type = CLASS_TYPE.RELY_ON_CHILD_AND_PARENT; return item; }); return data; }; const isBetweenItemList = (data, parent) => { if (Array.isArray(data) && data.length > 2 && parent) { let firstBetween = data[1].structure.x + data[1].structure.width * 0.5 - (data[0].structure.x + data[0].structure.width * 0.5); for (let i = 2; i < data.length; i++) { const item = data[i]; if (item.name != "ItemList") { return false; } if ( Math.abs( data[i].structure.x + data[i].structure.width * 0.5 - (data[i - 1].structure.x + data[i - 1].structure.width * 0.5) - firstBetween ) > 4 ) { return false; } } return true; } return false; }; const layoutBetweenItemList = (data: Layer[], parent: Layer) => { parent.style = { ...parent.style, display: "flex", flexDirection: 'row', justifyContent: "space-between", }; for (let i = 0; i < data.length; i++) { if (!data[i].style) { data[i].style = {}; } data[i].class_name = "li"; data[i].class_type = CLASS_TYPE.RELY_ON_CHILD_AND_PARENT; } if (isAlignCenter(data, parent)) { parent.style = { ...parent.style, alignItems: "center" }; } else { for (let i = 0; i < data.length; i++) { data[i].style = { ...data[i].style, marginTop: data[i].structure.y - parent.structure.y }; } } //第一个元素 if (data[0].structure.x != parent.structure.x) { parent.style = { ...parent.style, paddingLeft: data[0].structure.x - parent.structure.x }; } //最后一个元素 if ( data[data.length - 1].structure.x + data[data.length - 1].structure.width != parent.structure.x + parent.structure.width ) { parent.style = { ...parent.style, paddingRight: parent.structure.x + parent.structure.width -data[data.length - 1].structure.x - data[data.length - 1].structure.width }; } //不设置宽度 for (let i = 0; i < data.length; i++) { delete data[i].style.width } return data; } /** * 行布局 */ export const isRow = (data) => { let flag = true; if (Array.isArray(data) && data.length > 1) { data = data.sort((a, b) => a.structure.x - b.structure.x); for (let i = 0; i < data.length; i++) { const item = data[i]; flag = false; for (let j = i; j < data.length; j++) { const itemJ = data[j]; if ( (item.structure.y <= itemJ.structure.y && itemJ.structure.y < item.structure.y + item.structure.width) || (itemJ.structure.y <= item.structure.y && item.structure.y < itemJ.structure.y + itemJ.structure.width) ) { flag = true; } } } } return flag; } export const layoutRow = (data, parent) => { if (Array.isArray(data) && data.length > 1) { data = data.sort((a, b) => a.structure.x - b.structure.x); if (parent) { if (!parent.style) { parent.style = {}; } //两列两边对齐样式 if (isTowSpan(data, parent)) { return layoutTowSpan(data, parent); } //itemList情况切符合间距相同 if (isBetweenItemList(data, parent)) { return layoutBetweenItemList(data, parent); } // 多个子元素,宽度一样,第一个和最后一个紧挨父元素情况 if (isEqualBolck(data, parent)) { return layoutEqualBlock(data, parent); } // // 子元素组合位于父元素中间位置, 所有子元素垂直方向上居中 if (isimgTextCeneter(data, parent)) { return layoutImgTextCeneter(data, parent); } parent.style = { ...parent.style, display: "flex", flexDirection: "row" }; // 水平居中 if (parent.isCenter) { parent.style = { ...parent.style, width: "auto", justifyContent: "center" }; delete parent.style.marginLeft; } // 垂直方向 if (utils.isAlignMiddle(data, parent)) { if (!utils.isSameParentHeight(data, parent)) { parent.style = { ...parent.style, alignItems: "center" }; } } else { for (let i = 0; i < data.length; i++) { data[i].style = { ...data[i].style, marginTop: data[i].structure.y - parent.structure.y }; } } for (let i = 0; i < data.length; i++) { const item = data[i]; if (!data[i].style) { data[i].style = {}; } if (i == 0) { data[i].style = { ...data[i].style, marginLeft: item.structure.x - parent.structure.x }; } else { data[i].style = { ...data[i].style, marginLeft: item.structure.x - data[i - 1].structure.x - data[i - 1].structure.width }; } } if ( (isSingleText(data[data.length - 1]) && data[data.length - 1].style.textAlign === "left") || isOnlyContainer(data[data.length - 1]) ) { data[data.length - 1].style.width = "auto"; } } } return data; }
the_stack
import { RED_REGEX } from '../lib/dom-misc' import { TimeGridViewWrapper } from '../lib/wrappers/TimeGridViewWrapper' import { DayGridViewWrapper } from '../lib/wrappers/DayGridViewWrapper' // SEE ALSO: event-color.js describe('background events', () => { pushOptions({ initialDate: '2014-11-04', scrollTime: '00:00', }) describe('when in month view', () => { pushOptions({ initialView: 'dayGridMonth' }) describe('when LTR', () => { it('render correctly on a single day', () => { let calendar = initCalendar({ events: [{ title: 'hi', start: '2014-11-04', display: 'background', }], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid let allBgEls = dayGridWrapper.getBgEventEls() expect(allBgEls.length).toBe(1) expect(dayGridWrapper.getBgEventEls(1).length).toBe(1) expect(allBgEls[0]).toBeLeftOf(dayGridWrapper.getDayEl('2014-11-05')) expect(dayGridWrapper.getEventEls().length).toBe(0) }) it('render correctly spanning multiple weeks', () => { let calendar = initCalendar({ events: [{ title: 'hi', start: '2014-11-04', end: '2014-11-11', display: 'background', }], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid let allBgEls = dayGridWrapper.getBgEventEls() expect(allBgEls.length).toBe(2) expect(dayGridWrapper.getBgEventEls(1).length).toBe(1) expect(dayGridWrapper.getBgEventEls(2).length).toBe(1) expect(allBgEls[0]).toBeRightOf(dayGridWrapper.getDayEl('2014-11-03')) expect(allBgEls[1]).toBeLeftOf(dayGridWrapper.getDayEl('2014-11-12')) expect(dayGridWrapper.getEventEls().length).toBe(0) }) it('render correctly when two span on top of each other', () => { let calendar = initCalendar({ events: [ { start: '2014-11-04', end: '2014-11-07', display: 'background', }, { start: '2014-11-05', end: '2014-11-08', display: 'background', }, ], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid let allBgEls = dayGridWrapper.getBgEventEls() expect(allBgEls.length).toBe(2) expect(dayGridWrapper.getBgEventEls(1).length).toBe(2) expect(allBgEls[0]).toBeRightOf(dayGridWrapper.getDayEl('2014-11-02')) expect(allBgEls[1]).toBeLeftOf(dayGridWrapper.getDayEl('2014-11-08')) expect(dayGridWrapper.getEventEls().length).toBe(0) }) it('renders "business hours" on whole days', () => { let calendar = initCalendar({ businessHours: true, }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid expect(dayGridWrapper.getNonBusinessDayEls().length).toBe(12) // there are 6 weeks. 2 weekend days each }) }) describe('when RTL', () => { pushOptions({ direction: 'rtl' }) it('render correctly on a single day', () => { let calendar = initCalendar({ events: [{ title: 'hi', start: '2014-11-04', display: 'background', }], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid let allBgEls = dayGridWrapper.getBgEventEls() expect(allBgEls.length).toBe(1) expect(dayGridWrapper.getBgEventEls(1).length).toBe(1) expect(allBgEls[0]).toBeRightOf(dayGridWrapper.getDayEl('2014-11-06')) expect(dayGridWrapper.getEventEls().length).toBe(0) }) it('render correctly spanning multiple weeks', () => { let calendar = initCalendar({ events: [{ title: 'hi', start: '2014-11-04', end: '2014-11-11', display: 'background', }], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid let allBgEls = dayGridWrapper.getBgEventEls() expect(allBgEls.length).toBe(2) expect(dayGridWrapper.getBgEventEls(1).length).toBe(1) expect(dayGridWrapper.getBgEventEls(2).length).toBe(1) expect(allBgEls[0]).toBeLeftOf(dayGridWrapper.getDayEl('2014-11-02')) expect(allBgEls[1]).toBeRightOf(dayGridWrapper.getDayEl('2014-11-12')) expect(dayGridWrapper.getEventEls().length).toBe(0) }) }) describe('when inverse', () => { describe('when LTR', () => { it('render correctly on a single day', () => { let calendar = initCalendar({ events: [{ title: 'hi', start: '2014-11-04', display: 'inverse-background', }], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid expect(dayGridWrapper.getBgEventEls().length).toBe(7) expect(dayGridWrapper.getBgEventEls(0).length).toBe(1) expect(dayGridWrapper.getBgEventEls(1).length).toBe(2) expect(dayGridWrapper.getBgEventEls(2).length).toBe(1) expect(dayGridWrapper.getBgEventEls(3).length).toBe(1) expect(dayGridWrapper.getBgEventEls(4).length).toBe(1) expect(dayGridWrapper.getBgEventEls(5).length).toBe(1) let secondRowBgEls = dayGridWrapper.getBgEventEls(1) expect(secondRowBgEls[0]) .toBeLeftOf(dayGridWrapper.getDayEl('2014-11-05')) expect(secondRowBgEls[1]) .toBeRightOf(dayGridWrapper.getDayEl('2014-11-03')) expect(dayGridWrapper.getEventEls().length).toBe(0) }) it('render correctly spanning multiple weeks', () => { let calendar = initCalendar({ events: [{ title: 'hi', start: '2014-11-04', end: '2014-11-11', display: 'inverse-background', }], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid expect(dayGridWrapper.getBgEventEls().length).toBe(6) expect(dayGridWrapper.getBgEventEls(0).length).toBe(1) expect(dayGridWrapper.getBgEventEls(1).length).toBe(1) expect(dayGridWrapper.getBgEventEls(2).length).toBe(1) expect(dayGridWrapper.getBgEventEls(3).length).toBe(1) expect(dayGridWrapper.getBgEventEls(4).length).toBe(1) expect(dayGridWrapper.getBgEventEls(5).length).toBe(1) expect(dayGridWrapper.getBgEventEls(1)[0]) .toBeLeftOf(dayGridWrapper.getDayEl('2014-11-05')) expect(dayGridWrapper.getBgEventEls(2)[0]) .toBeRightOf(dayGridWrapper.getDayEl('2014-11-09')) expect(dayGridWrapper.getEventEls().length).toBe(0) }) it('render correctly when starts before start of month', () => { let calendar = initCalendar({ events: [{ start: '2014-10-24', end: '2014-11-06', display: 'inverse-background', }], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid expect(dayGridWrapper.getBgEventEls().length).toBe(5) expect(dayGridWrapper.getBgEventEls(0).length).toBe(0) expect(dayGridWrapper.getBgEventEls(1).length).toBe(1) expect(dayGridWrapper.getBgEventEls(2).length).toBe(1) expect(dayGridWrapper.getBgEventEls(3).length).toBe(1) expect(dayGridWrapper.getBgEventEls(4).length).toBe(1) expect(dayGridWrapper.getBgEventEls(5).length).toBe(1) expect(dayGridWrapper.getBgEventEls(1)) .toBeRightOf(dayGridWrapper.getDayEl('2014-11-04')) }) it('render correctly when ends after end of month', () => { let calendar = initCalendar({ events: [{ start: '2014-11-27', end: '2014-12-08', display: 'inverse-background', }], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid expect(dayGridWrapper.getBgEventEls().length).toBe(5) expect(dayGridWrapper.getBgEventEls(0).length).toBe(1) expect(dayGridWrapper.getBgEventEls(1).length).toBe(1) expect(dayGridWrapper.getBgEventEls(2).length).toBe(1) expect(dayGridWrapper.getBgEventEls(3).length).toBe(1) expect(dayGridWrapper.getBgEventEls(4).length).toBe(1) expect(dayGridWrapper.getBgEventEls(5).length).toBe(0) expect(dayGridWrapper.getBgEventEls(4)) .toBeLeftOf(dayGridWrapper.getDayEl('2014-11-28')) }) it('render correctly with two related events, in reverse order', () => { let calendar = initCalendar({ events: [ { groupId: 'hi', start: '2014-11-06', display: 'inverse-background', }, { groupId: 'hi', start: '2014-11-04', display: 'inverse-background', }, ], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid expect(dayGridWrapper.getBgEventEls().length).toBe(8) expect(dayGridWrapper.getBgEventEls(0).length).toBe(1) expect(dayGridWrapper.getBgEventEls(1).length).toBe(3) expect(dayGridWrapper.getBgEventEls(2).length).toBe(1) expect(dayGridWrapper.getBgEventEls(3).length).toBe(1) expect(dayGridWrapper.getBgEventEls(4).length).toBe(1) expect(dayGridWrapper.getBgEventEls(5).length).toBe(1) }) }) describe('when RTL', () => { pushOptions({ direction: 'rtl' }) it('render correctly on a single day', () => { let calendar = initCalendar({ events: [{ title: 'hi', start: '2014-11-04', display: 'inverse-background', }], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid expect(dayGridWrapper.getBgEventEls().length).toBe(7) expect(dayGridWrapper.getBgEventEls(0).length).toBe(1) expect(dayGridWrapper.getBgEventEls(1).length).toBe(2) expect(dayGridWrapper.getBgEventEls(2).length).toBe(1) expect(dayGridWrapper.getBgEventEls(3).length).toBe(1) expect(dayGridWrapper.getBgEventEls(4).length).toBe(1) expect(dayGridWrapper.getBgEventEls(5).length).toBe(1) }) }) }) describe('when in month view', () => { it('can be activated when rendering set on the source', () => { let calendar = initCalendar({ initialView: 'dayGridMonth', eventSources: [{ display: 'background', events: [{ start: '2014-11-04', }], }], }) let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid expect(dayGridWrapper.getBgEventEls().length).toBe(1) expect(dayGridWrapper.getEventEls().length).toBe(0) }) }) describe('when in timeGrid view and timed event', () => { it('can be activated when rendering set on the source', () => { let calendar = initCalendar({ initialView: 'timeGridWeek', eventSources: [{ display: 'background', events: [{ start: '2014-11-04T01:00:00', }], }], }) let viewWrapper = new TimeGridViewWrapper(calendar) expect(viewWrapper.dayGrid.getEventEls().length).toBe(0) expect(viewWrapper.timeGrid.getBgEventEls().length).toBe(1) }) }) }) describe('when in week view', () => { pushOptions({ initialView: 'timeGridWeek' }) describe('when LTR', () => { it('render correctly on one day', () => { let calendar = initCalendar({ events: [{ start: '2014-11-04T01:00:00', end: '2014-11-04T05:00:00', display: 'background', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid let allBgEvents = timeGridWrapper.getBgEventEls() expect(allBgEvents.length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(1) // column expect(timeGridWrapper.getEventEls().length).toBe(0) // no fg events let rect = allBgEvents[0].getBoundingClientRect() let topDiff = Math.abs(rect.top - timeGridWrapper.getTimeTop('01:00:00')) // TODO: make more exact let bottomDiff = Math.abs(rect.bottom - timeGridWrapper.getTimeTop('05:00:00')) expect(topDiff).toBeLessThanOrEqual(1) expect(bottomDiff).toBeLessThanOrEqual(1) }) it('render correctly spanning multiple days', () => { let calendar = initCalendar({ events: [{ start: '2014-11-04T01:00:00', end: '2014-11-05T05:00:00', display: 'background', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid expect(timeGridWrapper.getBgEventEls().length).toBe(2) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(3).length).toBe(1) }) it('render correctly when two span on top of each other', () => { let calendar = initCalendar({ events: [ { start: '2014-11-04T01:00:00', end: '2014-11-05T05:00:00', display: 'background', }, { start: '2014-11-04T03:00:00', end: '2014-11-05T08:00:00', display: 'background', }, ], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid expect(timeGridWrapper.getBgEventEls().length).toBe(4) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(2) expect(timeGridWrapper.queryBgEventsInCol(3).length).toBe(2) // TODO: maybe check y coords }) describe('when businessHours', () => { it('renders correctly if assumed default', () => { let calendar = initCalendar({ businessHours: true, }) let viewWrapper = new TimeGridViewWrapper(calendar) expect(viewWrapper.dayGrid.getNonBusinessDayEls().length).toBe(2) // whole days in the day area expect(viewWrapper.timeGrid.getNonBusinessDayEls().length).toBe(12) // strips of gray on the timed area }) it('renders correctly if custom', () => { let calendar = initCalendar({ businessHours: { startTime: '02:00', endTime: '06:00', daysOfWeek: [1, 2, 3, 4], // Mon-Thu }, }) let viewWrapper = new TimeGridViewWrapper(calendar) // whole days expect(viewWrapper.dayGrid.getNonBusinessDayEls().length).toBe(2) // each multi-day stretch is one element // time area let timeGridWrapper = viewWrapper.timeGrid expect(timeGridWrapper.getNonBusinessDayEls().length).toBe(11) expect(timeGridWrapper.queryNonBusinessSegsInCol(0).length).toBe(1) expect(timeGridWrapper.queryNonBusinessSegsInCol(1).length).toBe(2) expect(timeGridWrapper.queryNonBusinessSegsInCol(2).length).toBe(2) expect(timeGridWrapper.queryNonBusinessSegsInCol(3).length).toBe(2) expect(timeGridWrapper.queryNonBusinessSegsInCol(4).length).toBe(2) expect(timeGridWrapper.queryNonBusinessSegsInCol(5).length).toBe(1) expect(timeGridWrapper.queryNonBusinessSegsInCol(6).length).toBe(1) }) }) }) describe('when RTL', () => { pushOptions({ direction: 'rtl', }) it('render correctly on one day', () => { let calendar = initCalendar({ events: [{ start: '2014-11-04T01:00:00', end: '2014-11-04T05:00:00', display: 'background', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid let allBgEls = timeGridWrapper.getBgEventEls() expect(allBgEls.length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(1) let rect = allBgEls[0].getBoundingClientRect() let topDiff = Math.abs(rect.top - timeGridWrapper.getTimeTop('01:00:00')) let bottomDiff = Math.abs(rect.bottom - timeGridWrapper.getTimeTop('05:00:00')) expect(topDiff).toBeLessThanOrEqual(1) // TODO: tighten up expect(bottomDiff).toBeLessThanOrEqual(1) }) it('render correctly spanning multiple days', () => { let calendar = initCalendar({ events: [{ start: '2014-11-04T01:00:00', end: '2014-11-05T05:00:00', display: 'background', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid expect(timeGridWrapper.getBgEventEls().length).toBe(2) expect(timeGridWrapper.queryBgEventsInCol(3).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(1) }) describe('when businessHours', () => { it('renders correctly if custom', () => { let calendar = initCalendar({ businessHours: { startTime: '02:00', endTime: '06:00', daysOfWeek: [1, 2, 3, 4], // Mon-Thu }, }) let viewWrapper = new TimeGridViewWrapper(calendar) // whole days let dayGridWrapper = viewWrapper.dayGrid expect(dayGridWrapper.getNonBusinessDayEls().length).toBe(2) // each stretch of days is one element // time area let timeGridWrapper = viewWrapper.timeGrid expect(timeGridWrapper.getNonBusinessDayEls().length).toBe(11) expect(timeGridWrapper.queryNonBusinessSegsInCol(0).length).toBe(1) expect(timeGridWrapper.queryNonBusinessSegsInCol(1).length).toBe(2) expect(timeGridWrapper.queryNonBusinessSegsInCol(2).length).toBe(2) expect(timeGridWrapper.queryNonBusinessSegsInCol(3).length).toBe(2) expect(timeGridWrapper.queryNonBusinessSegsInCol(4).length).toBe(2) expect(timeGridWrapper.queryNonBusinessSegsInCol(5).length).toBe(1) expect(timeGridWrapper.queryNonBusinessSegsInCol(6).length).toBe(1) }) }) }) describe('when inverse', () => { describe('when LTR', () => { it('render correctly on one day', () => { let calendar = initCalendar({ events: [{ start: '2014-11-04T01:00:00', end: '2014-11-04T05:00:00', display: 'inverse-background', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid expect(timeGridWrapper.getBgEventEls().length).toBe(8) expect(timeGridWrapper.queryBgEventsInCol(0).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(1).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(2) expect(timeGridWrapper.queryBgEventsInCol(3).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(4).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(5).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(6).length).toBe(1) // TODO: maybe check y coords }) it('render correctly spanning multiple days', () => { let calendar = initCalendar({ events: [{ start: '2014-11-04T01:00:00', end: '2014-11-05T05:00:00', display: 'inverse-background', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid expect(timeGridWrapper.getBgEventEls().length).toBe(7) expect(timeGridWrapper.queryBgEventsInCol(0).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(1).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(3).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(4).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(5).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(6).length).toBe(1) // TODO: maybe check y coords }) it('render correctly when starts before start of week', () => { let calendar = initCalendar({ events: [{ start: '2014-10-30T01:00:00', end: '2014-11-04T05:00:00', display: 'inverse-background', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid expect(timeGridWrapper.getBgEventEls().length).toBe(5) expect(timeGridWrapper.queryBgEventsInCol(0).length).toBe(0) expect(timeGridWrapper.queryBgEventsInCol(1).length).toBe(0) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(3).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(4).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(5).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(6).length).toBe(1) // TODO: maybe check y coords }) it('render correctly when ends after end of week', () => { let calendar = initCalendar({ events: [{ start: '2014-11-04T01:00:00', end: '2014-11-12T05:00:00', display: 'inverse-background', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid expect(timeGridWrapper.getBgEventEls().length).toBe(3) expect(timeGridWrapper.queryBgEventsInCol(0).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(1).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(1) // TODO: maybe check y coords }) it('render correctly with two related events, in reverse order', () => { let calendar = initCalendar({ events: [ { groupId: 'hello', start: '2014-11-05T01:00:00', end: '2014-11-05T05:00:00', display: 'inverse-background', }, { groupId: 'hello', start: '2014-11-03T01:00:00', end: '2014-11-03T05:00:00', display: 'inverse-background', }, ], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid expect(timeGridWrapper.getBgEventEls().length).toBe(9) expect(timeGridWrapper.queryBgEventsInCol(0).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(1).length).toBe(2) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(3).length).toBe(2) expect(timeGridWrapper.queryBgEventsInCol(4).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(5).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(6).length).toBe(1) // TODO: maybe check y coords }) it('render correctly with two related events, nested', () => { let calendar = initCalendar({ events: [ { groupId: 'hello', start: '2014-11-05T01:00:00', end: '2014-11-05T05:00:00', display: 'inverse-background', }, { groupId: 'hello', start: '2014-11-05T02:00:00', end: '2014-11-05T04:00:00', display: 'inverse-background', }, ], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid let allBgEls = timeGridWrapper.getBgEventEls() expect(allBgEls.length).toBe(8) expect(timeGridWrapper.queryBgEventsInCol(0).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(1).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(3).length).toBe(2) expect(timeGridWrapper.queryBgEventsInCol(4).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(5).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(6).length).toBe(1) expect(allBgEls[3].getBoundingClientRect().top) .toBeLessThan(timeGridWrapper.getTimeTop('01:00:00')) expect(allBgEls[4].getBoundingClientRect().bottom) .toBeGreaterThan(timeGridWrapper.getTimeTop('05:00:00')) }) }) describe('when RTL', () => { pushOptions({ direction: 'rtl', }) it('render correctly on one day', () => { let calendar = initCalendar({ events: [{ start: '2014-11-04T01:00:00', end: '2014-11-04T05:00:00', display: 'inverse-background', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid expect(timeGridWrapper.getBgEventEls().length).toBe(8) expect(timeGridWrapper.queryBgEventsInCol(0).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(1).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(2).length).toBe(2) expect(timeGridWrapper.queryBgEventsInCol(3).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(4).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(5).length).toBe(1) expect(timeGridWrapper.queryBgEventsInCol(6).length).toBe(1) // TODO: maybe check y coords }) }) describe('when out of view range', () => { it('should still render', () => { let calendar = initCalendar({ events: [{ start: '2014-01-01T01:00:00', end: '2014-01-01T05:00:00', display: 'inverse-background', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid expect(timeGridWrapper.getBgEventEls().length).toBe(7) }) }) }) it('can have custom Event Object color', () => { let calendar = initCalendar({ events: [{ start: '2014-11-04T01:00:00', display: 'background', color: 'red', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid let bgEl = timeGridWrapper.getBgEventEls()[0] expect($(bgEl).css('background-color')).toMatch(RED_REGEX) }) it('can have custom Event Object backgroundColor', () => { let calendar = initCalendar({ events: [{ start: '2014-11-04T01:00:00', display: 'background', backgroundColor: 'red', }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid let bgEl = timeGridWrapper.getBgEventEls()[0] expect($(bgEl).css('background-color')).toMatch(RED_REGEX) }) it('can have custom Event Source color', () => { let calendar = initCalendar({ eventSources: [{ color: 'red', events: [{ start: '2014-11-04T01:00:00', display: 'background', }], }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid let bgEl = timeGridWrapper.getBgEventEls()[0] expect($(bgEl).css('background-color')).toMatch(RED_REGEX) }) it('can have custom Event Source backgroundColor', () => { let calendar = initCalendar({ eventSources: [{ backgroundColor: 'red', events: [{ start: '2014-11-04T01:00:00', display: 'background', }], }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid let bgEl = timeGridWrapper.getBgEventEls()[0] expect($(bgEl).css('background-color')).toMatch(RED_REGEX) }) it('is affected by global eventColor', () => { let calendar = initCalendar({ eventColor: 'red', eventSources: [{ events: [{ start: '2014-11-04T01:00:00', display: 'background', }], }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid let bgEl = timeGridWrapper.getBgEventEls()[0] expect($(bgEl).css('background-color')).toMatch(RED_REGEX) }) it('is affected by global eventBackgroundColor', () => { let calendar = initCalendar({ eventBackgroundColor: 'red', eventSources: [{ events: [{ start: '2014-11-04T01:00:00', display: 'background', }], }], }) let timeGridWrapper = new TimeGridViewWrapper(calendar).timeGrid let bgEl = timeGridWrapper.getBgEventEls()[0] expect($(bgEl).css('background-color')).toMatch(RED_REGEX) }) }) })
the_stack
import util = require('util'); import _ = require('lodash'); import Promise = require('bluebird'); import bunyan = require('bunyan'); import uuid = require('node-uuid'); import SocketIO = require('socket.io'); import webSocket = require('ws'); import Subscription = require('../subscription/subscription'); import Map = require('../util/map'); import conf = require('../config'); import Interface = require('../interface'); import blpSession = require('../middleware/blp-session'); import SocketIOWrapper = require('./socket-io-wrapper'); import WSWrapper = require('./ws-wrapper'); // Type used for subscription input from request body type SubscriptionOption = { correlationId: number; security: string; fields: string[]; options?: any; } type ISubscription = Interface.ISubscription; // GLOBAL var LOGGER: bunyan.Logger = bunyan.createLogger(conf.get('loggerOptions')); // PUBLIC FUNCTIONS export function sioOnConnect(s: SocketIO.Socket): void { var socket: Interface.ISocket = new SocketIOWrapper(s, LOGGER.child({req_id: uuid.v4()})); onConnect(socket); } export function wsOnConnect(s: webSocket): void { var socket: Interface.ISocket = new WSWrapper(s, LOGGER.child({req_id: uuid.v4()})); onConnect(socket); } // PRIVATE FUNCTIONS function getCorrelationIds(subscriptions: ISubscription[]): number[] { return subscriptions.map((s: ISubscription): number => { return s.correlationId; }); } function onConnect(socket: Interface.ISocket): void { socket.log.info({Address: socket.getIP()}, 'Client connected.'); if (conf.get('https.enable') && conf.get('logging.clientDetail')) { socket.log.debug({cert: socket.getCert()}, 'Client certificate.'); } // Get blpSession var blpSocketSession = blpSession.getSocketSession(socket) .catch((err: Error): any => { socket.log.error(err); if (socket.isConnected()) { socket.sendError('Unexpected error: ' + err.message); socket.disconnect(); } }); // Create subscriptions store var activeSubscriptions = new Map<ISubscription>(); var receivedSubscriptions = new Map<ISubscription>(); blpSocketSession.then((socket: Interface.ISocket): void => { // Clean up sockets for cases where the underlying session terminated unexpectedly socket.blpSession.once('SessionTerminated', (): void => { if (socket.isConnected()) { var message = 'blpSession terminated unexpectedly.'; socket.log.debug(message); socket.sendError(message); socket.disconnect(); } }); }); // Subscribe socket.on('subscribe', (data: Object[]): void => { socket.log.info('Subscribe request received'); // Log body if configured if (conf.get('logging.reqBody')) { socket.log.debug({body: data}, 'Subscribe body.'); } // Validate input options if (!data || !data.length) { var message = 'No valid subscriptions found.'; socket.log.debug(message); socket.sendError(message); return; } var errMessage: string; var isValid: boolean = _.every(data, (s: SubscriptionOption): boolean => { if (!_.has(s, 'correlationId') || !_.isNumber(s.correlationId) || !_.has(s, 'security') || !_.isString(s.security) || !_.has(s, 'fields') || !_.isArray(s.fields)) { errMessage = 'Invalid subscription option.'; return false; } if (receivedSubscriptions.has(s.correlationId)) { errMessage = util.format('Correlation Id %d already exist.', s.correlationId); return false; } return true; }); if (!isValid) { socket.log.debug(errMessage); socket.sendError(errMessage); return; } if (data.length !== _(data).pluck('correlationId').uniq().value().length) { errMessage = 'Duplicate correlation Id received.'; socket.log.debug(errMessage); socket.sendError(errMessage); return; } // Create Subscription object array and add event listeners var subscriptions = _.map(data, (s: SubscriptionOption): ISubscription => { var sub = new Subscription(s.correlationId, s.security, s.fields, s.options); // Add event listener for each subscription sub.on('data', (data: any): void => { socket.log.debug({data: {cid: sub.correlationId, time: process.hrtime()}}, 'Data received'); // Emit the data // TODO: Acknowledgement callback function? socket.sendData(sub.correlationId, data); socket.log.info('Data sent'); }); // Must subscribe to the 'error' event; otherwise EventEmitter will throw an exception // that was occurring from the underlying blpapi.Session. It is the assumed that the // blpapi.Session properly cleans up the subscription (i.e., 'unsubscribe()' should not // be called). sub.on('error', (err: Error): void => { socket.log.error(err, 'blpapi.Session subscription error occurred.'); socket.sendError(err.message); remove(sub); }); receivedSubscriptions.set(sub.correlationId, sub); return sub; }); blpSocketSession.then((socket: Interface.ISocket): void => { // Subscribe user request through blpapi-wrapper // TODO: Support authorized identity. socket.blpSession.subscribe(subscriptions, undefined).then((): void => { if (socket.isConnected()) { subscriptions.forEach((s: ISubscription): void => { activeSubscriptions.set(s.correlationId, s); }); socket.log.debug('Subscribed'); socket.notifySubscribed(getCorrelationIds(subscriptions)); } else { // Unsubscribe if socket already closed unsubscribe(subscriptions); } }).catch( (err: Error): void => { socket.log.error(err, 'Error Subscribing'); subscriptions.forEach(remove); if (socket.isConnected()) { socket.sendError(err.message); } }); }); }); // Unsubscribe socket.on('unsubscribe', (data: { 'correlationIds': number[] }): void => { socket.log.info('Unsubscribe request received'); // Log body if configured if (conf.get('logging.reqBody')) { socket.log.debug({body: data}, 'Unsubscribe body.'); } if (!activeSubscriptions.size) { var message = 'No active subscriptions'; socket.log.debug(message); socket.sendError(message); return; } var subscriptions: ISubscription[] = []; if (!data) { // If no correlation Id specified // the default behavior is to unsubscribe all active subscriptions subscriptions = activeSubscriptions.values(); } else { // If we do receive data object, first check if it is valid(empty list is INVALID) if (!_.has(data, 'correlationIds') || !_.isArray(data.correlationIds) || !data.correlationIds.length) { message = 'Invalid unsubscribe data received.'; socket.log.debug(message); socket.sendError(message); return; } // Next, validate all correlation Ids // Will error if any invalid correlation Id received var errMessage: string; var isAllValid = _.every(_.uniq(data.correlationIds), (cid: number): boolean => { if (activeSubscriptions.has(cid)) { subscriptions.push(activeSubscriptions.get(cid)); return true; } errMessage = util.format('Invalid correlation Id %d received.', cid); return false; }); if (!isAllValid) { socket.log.debug(errMessage); socket.sendError(errMessage); return; } } unsubscribe(subscriptions, true /* notify */); }); // Disconnect socket.on('disconnect', (): void => { // Unsubscribe all active subscriptions if (activeSubscriptions.size) { unsubscribe(activeSubscriptions.values()); } socket.log.info('Client disconnected.'); }); function remove(s: ISubscription): void { s.removeAllListeners(); activeSubscriptions.delete(s.correlationId); receivedSubscriptions.delete(s.correlationId); } function unsubscribe(subscriptions: ISubscription[], notify: boolean = false): void { blpSocketSession.then((socket: Interface.ISocket): void => { socket.blpSession.unsubscribe(subscriptions); subscriptions.forEach(remove); socket.log.debug({ activeSubscriptions: activeSubscriptions.size }, 'Unsubscribed.'); if (notify && socket.isConnected()) { socket.notifyUnsubscribed(getCorrelationIds(subscriptions)); } }).catch((err: Error): void => { socket.log.error(err, 'Error Unsubscribing'); if (notify && socket.isConnected()) { socket.sendError('Error unsubscribing'); } }); } }
the_stack
import { CleanRegexRule, createRuleListener, getDocUrl } from "../rules-util"; import { mention } from "../format"; import { elementsToCharacterClass, FirstConsumedChar, getFirstCharConsumedBy, getParentPrefixAndSuffix, matchingDirection, underAStar, } from "../ast-util"; import { Alternative, Assertion, CapturingGroup, CharacterClassElement, Element, Flags, Group, Pattern, } from "regexpp/ast"; import { CharSet } from "refa"; import { findIndex, findLastIndex, Simple } from "../util"; import { toCharSet } from "../char-util"; type CharElementArray = Readonly<Simple<CharacterClassElement>>[]; interface CharacterAlternative { isCharacter: true; alternative: Alternative; elements: CharElementArray; char: CharSet; } interface NonCharacterAlternative { isCharacter: false; alternative: Alternative; } interface GenericCharAlt { isCharacter: true; raw: string; char: CharSet; elements: CharElementArray; } interface GenericNonCharAlt { isCharacter: false; raw: string; firstChar: FirstConsumedChar; } /** * Tries to convert the given element into character class elements. * * The returned array may be empty. */ function toCharacterClassElement(element: Element): CharElementArray | null { if (element.type === "CharacterSet") { // normal dot is not possible (it technically is but it's complicated) if (element.kind === "any") { return null; } else { return [element]; } } else if (element.type === "CharacterClass") { if (!element.negate) { return [...element.elements]; } // we can't (easily) combine negated character classes // but can if the only element is a character set if (element.elements.length === 1 && element.elements[0].type === "CharacterSet") { const set = element.elements[0]; if (set.kind === "property") { const p = set.raw.substr(0, 2); const raw = (set.negate ? p.toLowerCase() : p.toUpperCase()) + set.raw.substr(2); return [ { type: "CharacterSet", kind: set.kind, key: set.key, value: set.value, negate: !set.negate, raw, }, ]; } else { const raw = set.negate ? set.raw.toLowerCase() : set.raw.toUpperCase(); return [ { type: "CharacterSet", kind: set.kind, negate: !set.negate, raw, }, ]; } } return null; } else if (element.type === "Character") { return [element]; } else { return null; } } /** * Given alternatives, this will return an array in which each alternative is categorized by whether it contains only a * single character (that can be combined with other characters in a character class) or not. */ function categorizeAlternatives( alternatives: readonly Alternative[], flags: Flags ): (CharacterAlternative | NonCharacterAlternative)[] { return alternatives.map(alternative => { if (alternative.elements.length === 1) { const elements = toCharacterClassElement(alternative.elements[0]); if (elements) { return /** @type {CharacterAlternative} */ { isCharacter: true, alternative, elements, char: toCharSet(elements, flags), }; } } return /** @type {NonCharacterAlternative} */ { isCharacter: false, alternative, }; }); } function containsCharacterClass(alts: Iterable<CharacterAlternative | NonCharacterAlternative>): boolean { for (const alt of alts) { if (alt.isCharacter && alt.alternative.elements.length === 1) { const e = alt.alternative.elements[0]; if (e.type === "CharacterClass") { return true; } } } return false; } function combineElements(alternatives: readonly (CharacterAlternative | NonCharacterAlternative)[]): CharElementArray { const elements: CharElementArray = []; for (const a of alternatives) { if (a.isCharacter) { elements.push(...a.elements); } } return elements; } function toGenericAlts( alternatives: readonly (CharacterAlternative | NonCharacterAlternative)[], flags: Flags ): (GenericCharAlt | GenericNonCharAlt)[] { const result: (GenericCharAlt | GenericNonCharAlt)[] = []; for (const a of alternatives) { if (a.isCharacter) { result.push({ isCharacter: true, elements: a.elements, char: a.char, raw: a.alternative.raw, }); } else { result.push({ isCharacter: false, firstChar: getFirstCharConsumedBy(a.alternative, matchingDirection(a.alternative), flags), raw: a.alternative.raw, }); } } return result; } function optimizeCharacterAlternatives( alternatives: (GenericCharAlt | GenericNonCharAlt)[], flags: Flags, reorder: boolean ): void { function merge(a: GenericCharAlt, b: GenericCharAlt): GenericCharAlt { const elements = [...a.elements, ...b.elements]; return { isCharacter: true, char: a.char.union(b.char), elements, raw: elementsToCharacterClass(elements), }; } function mergeRuns() { for (let i = 1; i < alternatives.length; i++) { const prev = alternatives[i - 1]; const curr = alternatives[i]; if (prev.isCharacter && curr.isCharacter) { alternatives[i - 1] = merge(prev, curr); alternatives.splice(i, 1); i--; } } } function mergeWithReorder() { // Here's how the merge algorithm works: // // We go through all alternatives from left to right. If we find a character alternative A, we will merge all // following character alternatives into it until // 1) we find a non-character alternative with a first character that can be the empty string, // 2) we find a non-character alternative B such that the union of first character in B is the "all" set, or // 3) we find a character alternative C such that C is not disjoint with the union of all the first characters // of all non-character alternatives between A and C. // // This re-ordering approach has the following properties: // a) It keeps the order of non-character alternatives and the order of character alternatives intact. // b) It runs in O(n) with n being the number of alternatives. for (let i = 0; i < alternatives.length - 1; i++) { let curr = alternatives[i]; if (!curr.isCharacter) { continue; } /** * The union of all character sets a char alternative has to be disjoint with in order to be moved. */ let nonCharTotal: CharSet | undefined = undefined; for (let j = i + 1; j < alternatives.length; j++) { const far = alternatives[j]; if (far.isCharacter) { // character alternative if (nonCharTotal === undefined || far.char.isDisjointWith(nonCharTotal)) { curr = merge(curr, far); alternatives.splice(j, 1); j--; } else { break; } } else { // non-character alternative if (!far.firstChar.empty) { if (nonCharTotal === undefined) { nonCharTotal = far.firstChar.char; } else { nonCharTotal = nonCharTotal.union(far.firstChar.char); } if (nonCharTotal.isAll) { // Since, it's impossible for any non-empty character set to be disjoint with the "all" set, // we can stop right here. break; } } else { // this means that the `far` alternative accepts the empty word. // Since we don't know what comes after the alternative, we have to assume that it may be any // character, meaning that `nonCharTotal` will be set to the "all" character set. break; } } } alternatives[i] = curr; } } if (reorder) { mergeWithReorder(); } else { mergeRuns(); } } /** * Return whether all character alternatives are disjoint with each other. */ function findNonDisjointAlt( alternatives: Iterable<CharacterAlternative | NonCharacterAlternative> ): CharacterAlternative | null { let total: CharSet | undefined = undefined; for (const a of alternatives) { if (a.isCharacter) { if (total === undefined) { total = a.char; } else { if (!total.isDisjointWith(a.char)) { return a; } total = total.union(a.char); } } } return null; } function totalIsAll(alternatives: Iterable<CharacterAlternative | NonCharacterAlternative>): boolean { let total: CharSet | undefined = undefined; for (const a of alternatives) { if (a.isCharacter) { if (total === undefined) { total = a.char; } else { total = total.union(a.char); } } } return total !== undefined && total.isAll; } export default { meta: { type: "suggestion", docs: { description: "Prefer character classes wherever possible instead of alternations.", url: getDocUrl(/* #GENERATED */ "prefer-character-class"), }, fixable: "code", }, create(context) { return createRuleListener(({ visitAST, flags, replaceElement, reportElement, reportElements }) => { function process(node: Pattern | CapturingGroup | Group | Assertion): void { if (!("alternatives" in node)) { return; } if (node.alternatives.length < 2) { // we need at least 2 alternatives with characters to make this work return; } const alts = categorizeAlternatives(node.alternatives, flags); const characterAlternativesCount = alts.filter(a => a.isCharacter).length; if (characterAlternativesCount < 2) { // we need at least 2 character alternatives return; } if (alts.every(a => a.isCharacter)) { // all alternatives are characters // // We will only suggest to merge the characters if // 1) there are >= 3 character alternatives, or // 2) the characters of the character alternatives are not disjoint, or // 3) the union of all character alternatives is the "all" set. if ( alts.length >= 3 || findNonDisjointAlt(alts) || totalIsAll(alts) || containsCharacterClass(alts) ) { const [prefix, suffix] = node.type === "Group" ? ["", ""] : getParentPrefixAndSuffix(node); const replacement = prefix + elementsToCharacterClass(combineElements(alts)) + suffix; context.report({ message: `This can be replaced with ${mention(replacement)}.`, ...replaceElement(node, replacement, { // the replacement might depend on the i flag dependsOnFlags: true, }), }); } return; } // This is the general case: // We have both character and non-character alternatives. The following will try to merge character // alternatives and might even re-order alternatives to do so. // // We will only try to optimize alternatives if // 1) there are >= 3 character alternatives, or // 2) the characters of the character alternatives are not disjoint, or // 3) the union of all character alternatives is the "all" set. const nonDisjointAlt = findNonDisjointAlt(alts); if ( nonDisjointAlt || characterAlternativesCount >= 3 || totalIsAll(alts) || containsCharacterClass(alts) ) { const genericAlts = toGenericAlts(alts, flags); optimizeCharacterAlternatives(genericAlts, flags, true); const [prefix, suffix] = getParentPrefixAndSuffix(node); const newRaw = prefix + genericAlts.map(a => a.raw).join("|") + suffix; if (newRaw !== node.raw) { // Something (don't know what exactly) was changed // Try to narrow down the range of which alternatives changed as much as possible. // This won't change that we replace the whole element but it will give a lot more precise error // messages for elements with many alternatives. const firstChanged = findIndex(genericAlts, (a, i) => a.raw !== node.alternatives[i].raw); const lastChanged = findLastIndex( genericAlts, (a, i) => a.raw !== node.alternatives[node.alternatives.length + i - genericAlts.length].raw ); const changedNodes = [ node.alternatives[firstChanged], node.alternatives[node.alternatives.length + lastChanged - genericAlts.length], ]; const displayRaw = firstChanged === 0 && lastChanged === genericAlts.length - 1 ? newRaw : genericAlts .slice(firstChanged, lastChanged + 1) .map(a => a.raw) .join("|"); context.report({ message: `This can be replaced with ${mention(displayRaw)}.`, ...replaceElement(node, newRaw, { // the replacement might depend on the i flag dependsOnFlags: true, }), ...reportElements(changedNodes), }); return; } } // If we made it here, we couldn't optimize any character alternatives. // But there might still be unmerged non-disjoint character alternatives that can cause exponential // backtracking. We can't fix them but we can at least warn the user. if (nonDisjointAlt) { let expMessage; if (underAStar(node)) { expMessage = "\nThis ambiguity is very likely to cause exponential backtracking."; } else { expMessage = ""; } context.report({ message: `The set of characters accepted by ${mention( nonDisjointAlt.alternative )} is not disjoint with the set of characters accepted by previous alternatives.` + " Try to remove this ambiguity." + expMessage, ...reportElement(nonDisjointAlt.alternative), }); return; } } visitAST({ onAssertionEnter: process, onCapturingGroupEnter: process, onGroupEnter: process, onPatternEnter: process, }); }); }, } as CleanRegexRule;
the_stack
import { CSSResultGroup, LitElement, TemplateResult, html, unsafeCSS, PropertyValues, } from 'lit'; import { BrowseMediaSource, ExtendedHomeAssistant, CameraConfig, JSMPEGConfig, LiveConfig, MediaShowInfo, WebRTCConfig, FrigateCardError, LiveOverrides, LiveProvider, frigateCardConfigDefaults, } from '../types.js'; import { EmblaOptionsType } from 'embla-carousel'; import { HomeAssistant } from 'custom-card-helpers'; import { customElement, property, state } from 'lit/decorators.js'; import { ref } from 'lit/directives/ref'; import { until } from 'lit/directives/until.js'; import { BrowseMediaUtil } from '../browse-media-util.js'; import { ConditionState, getOverriddenConfig } from '../card-condition.js'; import { FrigateCardMediaCarousel } from './media-carousel.js'; import { FrigateCardNextPreviousControl } from './next-prev-control.js'; import { ThumbnailCarouselTap } from './thumbnail-carousel.js'; import { View } from '../view.js'; import { localize } from '../localize/localize.js'; import { contentsChanged, dispatchErrorMessageEvent, dispatchExistingMediaShowInfoAsEvent, dispatchMediaShowEvent, dispatchMessageEvent, dispatchPauseEvent, dispatchPlayEvent, getCameraIcon, getCameraTitle, homeAssistantSignPath, } from '../common.js'; import { renderProgressIndicator } from '../components/message.js'; import JSMpeg from '@cycjimmy/jsmpeg-player'; import liveStyle from '../scss/live.scss'; import liveFrigateStyle from '../scss/live-frigate.scss'; import liveJSMPEGStyle from '../scss/live-jsmpeg.scss'; import liveWebRTCStyle from '../scss/live-webrtc.scss'; // Number of seconds a signed URL is valid for. const URL_SIGN_EXPIRY_SECONDS = 24 * 60 * 60; // Number of seconds before the expiry to trigger a refresh. const URL_SIGN_REFRESH_THRESHOLD_SECONDS = 1 * 60 * 60; @customElement('frigate-card-live') export class FrigateCardLive extends LitElement { @property({ attribute: false }) protected hass?: HomeAssistant & ExtendedHomeAssistant; @property({ attribute: false }) protected view?: Readonly<View>; @property({ attribute: false }) protected cameras?: Map<string, CameraConfig>; @property({ attribute: false }) protected liveConfig?: LiveConfig; @property({ attribute: false }) protected liveOverrides?: LiveOverrides; @property({ attribute: false }) protected conditionState?: ConditionState; set preloaded(preloaded: boolean) { this._preloaded = preloaded; if (!preloaded && this._savedMediaShowInfo) { dispatchExistingMediaShowInfoAsEvent(this, this._savedMediaShowInfo); } } // Whether or not the live view is currently being preloaded. @state() protected _preloaded?: boolean; // MediaShowInfo object from the underlying live object. In the case of // pre-loading it may be propagated upwards later. protected _savedMediaShowInfo?: MediaShowInfo; /** * Handler for media show events that special cases preloaded live views. * @param e The media show event. */ protected _mediaShowHandler(e: CustomEvent<MediaShowInfo>): void { this._savedMediaShowInfo = e.detail; if (this._preloaded) { // If live is being pre-loaded, don't let the event propogate upwards yet // as the media is not really being shown. e.stopPropagation(); } } /** * Render thumbnails carousel. * @returns A rendered template or void. */ protected renderThumbnails(config: LiveConfig): TemplateResult | void { if (!this.liveConfig || !this.view) { return; } const fetchThumbnailsThenRender = async (): Promise<TemplateResult | void> => { if (!this.hass || !this.cameras || !this.view) { return; } const browseMediaParams = BrowseMediaUtil.getBrowseMediaQueryParameters( config.controls.thumbnails.media, this.cameras.get(this.view.camera), ); if (!browseMediaParams) { return; } let parent: BrowseMediaSource | null; try { parent = await BrowseMediaUtil.browseMediaQuery(this.hass, browseMediaParams); } catch (e) { return dispatchErrorMessageEvent(this, (e as Error).message); } if (BrowseMediaUtil.getFirstTrueMediaChildIndex(parent) != null) { return html`<frigate-card-thumbnail-carousel .target=${parent} .view=${this.view} .config=${config.controls.thumbnails} .highlightSelected=${false} @frigate-card:carousel:tap=${(ev: CustomEvent<ThumbnailCarouselTap>) => { const mediaType = browseMediaParams.mediaType; if (mediaType && this.view && ['snapshots', 'clips'].includes(mediaType)) { new View({ view: mediaType === 'clips' ? 'clip' : 'snapshot', camera: this.view.camera, target: ev.detail.target, childIndex: ev.detail.childIndex, }).dispatchChangeEvent(this); } }} > </frigate-card-thumbnail-carousel>`; } }; // Don't render a progress indicator for live thumbnails, as it's jarring // during live-carousel scrolling (the progress indicator repeatedly // flashes). Just render nothing during loading. return html`${until(fetchThumbnailsThenRender(), html``)}`; } /** * Master render method. * @returns A rendered template. */ protected render(): TemplateResult | void { if (!this.hass || !this.liveConfig || !this.cameras) { return; } const config = getOverriddenConfig( this.liveConfig, this.liveOverrides, this.conditionState, ) as LiveConfig; // Note use of liveConfig and not config below -- the carousel will // independently override the liveconfig to reflect the camera in the // carousel (not necessarily the selected camera). return html` ${config.controls.thumbnails.mode === 'above' ? this.renderThumbnails(config) : ''} <frigate-card-live-carousel .hass=${this.hass} .view=${this.view} .cameras=${this.cameras} .liveConfig=${this.liveConfig} .preloaded=${this._preloaded} .conditionState=${this.conditionState} .liveOverrides=${this.liveOverrides} @frigate-card:media-show=${this._mediaShowHandler} @frigate-card:change-view=${(ev: CustomEvent) => { if (this._preloaded) { // Don't allow change-view events to propagate upwards if the card // is only preloaded rather than being live displayed. These events // could be triggered if the camera is switched and the carousel // moves to focus on that camera -- as the card isn't actually being // displayed, do not allow the view to actually be updated. ev.stopPropagation(); } }} > </frigate-card-live-carousel> ${config.controls.thumbnails.mode === 'below' ? this.renderThumbnails(config) : ''} `; } /** * Get styles. */ static get styles(): CSSResultGroup { return unsafeCSS(liveStyle); } } @customElement('frigate-card-live-carousel') export class FrigateCardLiveCarousel extends FrigateCardMediaCarousel { @property({ attribute: false }) protected hass?: HomeAssistant & ExtendedHomeAssistant; @property({ attribute: false }) protected view?: Readonly<View>; @property({ attribute: false }) protected cameras?: Map<string, CameraConfig>; @property({ attribute: false }) protected liveConfig?: LiveConfig; @property({ attribute: false }) protected liveOverrides?: LiveOverrides; @property({ attribute: false }) protected preloaded?: boolean; @property({ attribute: false }) protected conditionState?: ConditionState; // Index between camera name and slide number. protected _cameraToSlide: Record<string, number> = {}; /** * The updated lifecycle callback for this element. * @param changedProperties The properties that were changed in this render. */ updated(changedProperties: PropertyValues): void { if ( changedProperties.has('cameras') || changedProperties.has('liveConfig') || changedProperties.has('preloaded') ) { // All of these properties may fundamentally change the contents/size of // the DOM, and the carousel should be reset when they change. this._destroyCarousel(); } if (changedProperties.has('view')) { const oldView = changedProperties.get('view') as View | undefined; if ( this._carousel && oldView && this.view?.camera && this.view?.camera != oldView.camera ) { const slide: number | undefined = this._cameraToSlide[this.view.camera]; if (slide !== undefined && slide !== this.carouselSelected()) { this.carouselScrollTo(slide); } } } super.updated(changedProperties); } /** * Get the Embla options to use. * @returns An EmblaOptionsType object or undefined for no options. */ protected _getOptions(): EmblaOptionsType { let startIndex = -1; if (this.cameras && this.view) { startIndex = Array.from(this.cameras.keys()).indexOf(this.view.camera); } return { startIndex: startIndex < 0 ? undefined : startIndex, draggable: this.liveConfig?.draggable, }; } /** * Returns the number of slides to lazily load. 0 means all slides are lazy * loaded, 1 means that 1 slide on each side of the currently selected slide * should lazy load, etc. `null` means lazy loading is disabled and everything * should load simultaneously. * @returns */ protected _getLazyLoadCount(): number | null { // Defaults to fully-lazy loading. return this.liveConfig?.lazy_load === false ? null : 0; } /** * Get slides to include in the render. * @returns The slides to include in the render and an index keyed by camera * name to slide number. */ protected _getSlides(): [TemplateResult[], Record<string, number>] { if (!this.cameras) { return [[], {}]; } const slides: TemplateResult[] = []; const cameraToSlide: Record<string, number> = {}; for (const [camera, cameraConfig] of this.cameras) { const slide = this._renderLive(camera, cameraConfig, slides.length); if (slide) { cameraToSlide[camera] = slides.length; slides.push(slide); } } return [slides, cameraToSlide]; } /** * Handle the user selecting a new slide in the carousel. */ protected _selectSlideSetViewHandler(): void { if (!this._carousel || !this.view || !this.cameras) { return; } const selectedSnap = this._carousel.selectedScrollSnap(); this.view .evolve({ camera: Array.from(this.cameras.keys())[selectedSnap], previous: this.view, }) .dispatchChangeEvent(this); } /** * Lazy load a slide. * @param _index The slide number to lazy load. * @param slide The slide to lazy load. */ protected _lazyLoadSlide(_index: number, slide: HTMLElement): void { const liveProvider = slide.querySelector( 'frigate-card-live-provider', ) as FrigateCardLiveProvider; if (liveProvider) { liveProvider.disabled = false; } } protected _renderLive( camera: string, cameraConfig: CameraConfig, slideIndex: number, ): TemplateResult | void { if (!this.liveConfig) { return; } // The conditionState object contains the currently live camera, which (in // the carousel for example) is not necessarily the live camera this // <frigate-card-live-provider> is rendering right now. const conditionState = Object.assign({ ...this.conditionState, camera: camera, }); const config = getOverriddenConfig( this.liveConfig, this.liveOverrides, conditionState, ) as LiveConfig; return html` <div class="embla__slide"> <frigate-card-live-provider ?disabled=${this._isLazyLoading()} .cameraConfig=${cameraConfig} .label=${getCameraTitle(this.hass, cameraConfig)} .liveConfig=${config} .hass=${this.hass} @frigate-card:media-show=${(e: CustomEvent<MediaShowInfo>) => this._mediaShowEventHandler(slideIndex, e)} > </frigate-card-live-provider> </div>`; } protected _getCameraNeighbors(): [CameraConfig | null, CameraConfig | null] { if (!this.cameras || !this.view || !this.hass) { return [null, null]; } const keys = Array.from(this.cameras.keys()); const currentIndex = keys.indexOf(this.view.camera); if (currentIndex < 0) { return [null, null]; } let prev: CameraConfig | null = null, next: CameraConfig | null = null; if (currentIndex > 0) { prev = this.cameras.get(keys[currentIndex - 1]) ?? null; } if (currentIndex + 1 < this.cameras.size) { next = this.cameras.get(keys[currentIndex + 1]) ?? null; } return [prev, next]; } /** * Handle updating of the next/previous controls when the carousel is moved. */ protected _selectSlideNextPreviousHandler(): void { const updateNextPreviousControl = ( control: FrigateCardNextPreviousControl, direction: 'previous' | 'next', ): void => { const [prev, next] = this._getCameraNeighbors(); const target = direction == 'previous' ? prev : next; control.disabled = target == null; control.title = getCameraTitle(this.hass, target); control.icon = getCameraIcon(this.hass, target); }; if (this._previousControlRef.value) { updateNextPreviousControl(this._previousControlRef.value, 'previous'); } if (this._nextControlRef.value) { updateNextPreviousControl(this._nextControlRef.value, 'next'); } } /** * Render the element. * @returns A template to display to the user. */ protected render(): TemplateResult | void { const [slides, cameraToSlide] = this._getSlides(); this._cameraToSlide = cameraToSlide; if (!slides || !this.liveConfig) { return; } const config = getOverriddenConfig( this.liveConfig, this.liveOverrides, this.conditionState, ) as LiveConfig; const [prev, next] = this._getCameraNeighbors(); return html` <div class="embla"> <frigate-card-next-previous-control ${ref(this._previousControlRef)} .direction=${'previous'} .controlConfig=${config.controls.next_previous} .label=${getCameraTitle(this.hass, prev)} .icon=${getCameraIcon(this.hass, prev)} ?disabled=${prev == null} @click=${() => { this._nextPreviousHandler('previous'); }} > </frigate-card-next-previous-control> <div class="embla__viewport"> <div class="embla__container">${slides}</div> </div> <frigate-card-next-previous-control ${ref(this._nextControlRef)} .direction=${'next'} .controlConfig=${config.controls.next_previous} .label=${getCameraTitle(this.hass, next)} .icon=${getCameraIcon(this.hass, next)} ?disabled=${next == null} @click=${() => { this._nextPreviousHandler('next'); }} > </frigate-card-next-previous-control> </div> `; } } @customElement('frigate-card-live-provider') export class FrigateCardLiveProvider extends LitElement { @property({ attribute: false }) protected hass?: HomeAssistant & ExtendedHomeAssistant; @property({ attribute: false }) protected cameraConfig?: CameraConfig; @property({ attribute: false }) protected liveConfig?: LiveConfig; // Whether or not to disable this entity. If `true`, no contents are rendered // until this attribute is set to `false` (this is useful for lazy loading). @property({ attribute: true, type: Boolean }) public disabled = false; // Label that is used for ARIA support and as tooltip. @property({ attribute: false }) public label = ''; protected _getResolvedProvider(): LiveProvider { if (this.cameraConfig?.live_provider === 'auto') { if (this.cameraConfig?.webrtc?.entity || this.cameraConfig?.webrtc?.url) { return 'webrtc'; } else if (this.cameraConfig?.camera_entity) { return 'frigate'; } else if (this.cameraConfig?.camera_name) { return 'frigate-jsmpeg'; } return frigateCardConfigDefaults.cameras.live_provider; } return ( this.cameraConfig?.live_provider || frigateCardConfigDefaults.cameras.live_provider ); } /** * Master render method. * @returns A rendered template. */ protected render(): TemplateResult | void { if (this.disabled || !this.hass || !this.liveConfig || !this.cameraConfig) { return; } // Set title and ariaLabel from the provided label property. this.title = this.label; this.ariaLabel = this.label; const provider = this._getResolvedProvider(); return html` ${provider == 'frigate' ? html` <frigate-card-live-frigate .hass=${this.hass} .cameraEntity=${this.cameraConfig.camera_entity} > </frigate-card-live-frigate>` : provider == 'webrtc' ? html`<frigate-card-live-webrtc .hass=${this.hass} .cameraConfig=${this.cameraConfig} .webRTCConfig=${this.liveConfig.webrtc} > </frigate-card-live-webrtc>` : html` <frigate-card-live-jsmpeg .hass=${this.hass} .cameraConfig=${this.cameraConfig} .jsmpegConfig=${this.liveConfig.jsmpeg} > </frigate-card-live-jsmpeg>`} `; } } @customElement('frigate-card-live-frigate') export class FrigateCardLiveFrigate extends LitElement { @property({ attribute: false }) protected hass?: HomeAssistant & ExtendedHomeAssistant; @property({ attribute: false }) protected cameraEntity?: string; /** * Master render method. * @returns A rendered template. */ protected render(): TemplateResult | void { if (!this.hass) { return; } if (!this.cameraEntity || !(this.cameraEntity in this.hass.states)) { return dispatchMessageEvent( this, localize('error.no_live_camera'), 'mdi:camera-off', ); } return html` <frigate-card-ha-camera-stream .hass=${this.hass} .stateObj=${this.hass.states[this.cameraEntity]} .controls=${true} .muted=${true} > </frigate-card-ha-camera-stream>`; } /** * Get styles. */ static get styles(): CSSResultGroup { return unsafeCSS(liveFrigateStyle); } } // Create a wrapper for the WebRTC element // - https://github.com/AlexxIT/WebRTC @customElement('frigate-card-live-webrtc') export class FrigateCardLiveWebRTC extends LitElement { @property({ attribute: false, hasChanged: contentsChanged }) protected webRTCConfig?: WebRTCConfig; @property({ attribute: false }) protected cameraConfig?: CameraConfig; protected hass?: HomeAssistant & ExtendedHomeAssistant; /** * Create the WebRTC element. May throw. */ protected _createWebRTC(): HTMLElement | undefined { // eslint-disable-next-line @typescript-eslint/no-explicit-any const webrtcElement = customElements.get('webrtc-camera') as any; if (webrtcElement) { const webrtc = new webrtcElement(); const config = { ...this.webRTCConfig }; // If the live WebRTC configuration does not specify a URL/entity to use, // then take values from the camera configuration instead (if there are // any). if (!config.url) { config.url = this.cameraConfig?.webrtc?.url; } if (!config.entity) { config.entity = this.cameraConfig?.webrtc?.entity; } webrtc.setConfig(config); webrtc.hass = this.hass; return webrtc; } else { throw new FrigateCardError(localize('error.webrtc_missing')); } } /** * Master render method. * @returns A rendered template. */ protected render(): TemplateResult | void { if (!this.hass) { return; } let webrtcElement: HTMLElement | undefined; try { webrtcElement = this._createWebRTC(); } catch (e) { return dispatchErrorMessageEvent( this, e instanceof FrigateCardError ? (e as FrigateCardError).message : localize('error.webrtc_reported_error') + ': ' + (e as Error).message, ); } return html`${webrtcElement}`; } /** * Updated lifecycle callback. */ public updated(): void { // Extract the video component after it has been rendered and generate the // media load event. this.updateComplete.then(() => { const video = this.renderRoot.querySelector('#video') as HTMLVideoElement; if (video) { const onloadedmetadata = video.onloadedmetadata; const onplay = video.onplay; const onpause = video.onpause; video.onloadedmetadata = (e) => { if (onloadedmetadata) { onloadedmetadata.call(video, e); } dispatchMediaShowEvent(this, video); }; video.onplay = (e) => { if (onplay) { onplay.call(video, e); } dispatchPlayEvent(this); }; video.onpause = (e) => { if (onpause) { onpause.call(video, e); } dispatchPauseEvent(this); }; } }); } /** * Get styles. */ static get styles(): CSSResultGroup { return unsafeCSS(liveWebRTCStyle); } } @customElement('frigate-card-live-jsmpeg') export class FrigateCardLiveJSMPEG extends LitElement { @property({ attribute: false }) protected cameraConfig?: CameraConfig; @property({ attribute: false, hasChanged: contentsChanged }) protected jsmpegConfig?: JSMPEGConfig; protected hass?: HomeAssistant & ExtendedHomeAssistant; protected _jsmpegCanvasElement?: HTMLCanvasElement; protected _jsmpegVideoPlayer?: JSMpeg.VideoElement; protected _refreshPlayerTimerID?: number; /** * Get a signed player URL. * @returns A URL or null. */ protected async _getURL(): Promise<string | null> { if (!this.hass || !this.cameraConfig?.client_id || !this.cameraConfig?.camera_name) { return null; } let response: string | null | undefined; try { response = await homeAssistantSignPath( this.hass, `/api/frigate/${this.cameraConfig.client_id}` + `/jsmpeg/${this.cameraConfig.camera_name}`, URL_SIGN_EXPIRY_SECONDS, ); } catch (err) { console.warn(err); return null; } if (!response) { return null; } return response.replace(/^http/i, 'ws'); } /** * Create a JSMPEG player. * @param url The URL for the player to connect to. * @returns A JSMPEG player. */ protected async _createJSMPEGPlayer(url: string): Promise<JSMpeg.VideoElement> { return new Promise<JSMpeg.VideoElement>((resolve) => { let videoDecoded = false; const player = new JSMpeg.VideoElement( this, url, { canvas: this._jsmpegCanvasElement, hooks: { play: () => { dispatchPlayEvent(this); }, pause: () => { dispatchPauseEvent(this); }, }, }, { pauseWhenHidden: false, protocols: [], audio: false, videoBufferSize: 1024 * 1024 * 4, // Override with user-specified options. ...this.jsmpegConfig?.options, onVideoDecode: () => { // This is the only callback that is called after the dimensions // are available. It's called on every frame decode, so just // ignore any subsequent calls. if (!videoDecoded && this._jsmpegCanvasElement) { videoDecoded = true; dispatchMediaShowEvent(this, this._jsmpegCanvasElement); resolve(player); } }, }, ); }); } /** * Reset / destroy the player. */ protected _resetPlayer(): void { if (this._refreshPlayerTimerID) { window.clearTimeout(this._refreshPlayerTimerID); this._refreshPlayerTimerID = undefined; } if (this._jsmpegVideoPlayer) { try { this._jsmpegVideoPlayer.destroy(); } catch (err) { // Pass. } this._jsmpegVideoPlayer = undefined; } if (this._jsmpegCanvasElement) { this._jsmpegCanvasElement.remove(); this._jsmpegCanvasElement = undefined; } } /** * Component connected callback. */ connectedCallback(): void { super.connectedCallback(); if (this.isConnected) { this.requestUpdate(); } } /** * Component disconnected callback. */ disconnectedCallback(): void { if (!this.isConnected) { this._resetPlayer(); } super.disconnectedCallback(); } /** * Refresh the JSMPEG player. */ protected async _refreshPlayer(): Promise<void> { this._resetPlayer(); this._jsmpegCanvasElement = document.createElement('canvas'); this._jsmpegCanvasElement.className = 'media'; if (!this.cameraConfig?.camera_name) { return dispatchErrorMessageEvent( this, localize('error.no_camera_name') + `: ${JSON.stringify(this.cameraConfig)}`, ); } const url = await this._getURL(); if (url) { this._jsmpegVideoPlayer = await this._createJSMPEGPlayer(url); this._refreshPlayerTimerID = window.setTimeout(() => { this.requestUpdate(); }, (URL_SIGN_EXPIRY_SECONDS - URL_SIGN_REFRESH_THRESHOLD_SECONDS) * 1000); } else { dispatchErrorMessageEvent(this, localize('error.jsmpeg_no_sign')); } } /** * Master render method. */ protected render(): TemplateResult | void { const _render = async (): Promise<TemplateResult | void> => { await this._refreshPlayer(); if (!this._jsmpegVideoPlayer || !this._jsmpegCanvasElement) { return dispatchErrorMessageEvent(this, localize('error.jsmpeg_no_player')); } return html`${this._jsmpegCanvasElement}`; }; return html`${until(_render(), renderProgressIndicator())}`; } /** * Get styles. */ static get styles(): CSSResultGroup { return unsafeCSS(liveJSMPEGStyle); } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormPurchase_Order { interface tab__0898DBC4_7C5F_4D66_963F_628E881B178B_Sections { _0898DBC4_7C5F_4D66_963F_628E881B178B_SECTION_2: DevKit.Controls.Section; _58B0EA4F_855F_4143_8703_D34B3849F302: DevKit.Controls.Section; tab_5_section_1: DevKit.Controls.Section; } interface tab_Address_Sections { tab_3_section_1: DevKit.Controls.Section; } interface tab_tab_4_Sections { tab_4_section_1: DevKit.Controls.Section; tab_4_section_3: DevKit.Controls.Section; tab_4_section_4: DevKit.Controls.Section; tab_6_section_1: DevKit.Controls.Section; } interface tab_tab_7_Sections { tab_7_section_1: DevKit.Controls.Section; } interface tab__0898DBC4_7C5F_4D66_963F_628E881B178B extends DevKit.Controls.ITab { Section: tab__0898DBC4_7C5F_4D66_963F_628E881B178B_Sections; } interface tab_Address extends DevKit.Controls.ITab { Section: tab_Address_Sections; } interface tab_tab_4 extends DevKit.Controls.ITab { Section: tab_tab_4_Sections; } interface tab_tab_7 extends DevKit.Controls.ITab { Section: tab_tab_7_Sections; } interface Tabs { _0898DBC4_7C5F_4D66_963F_628E881B178B: tab__0898DBC4_7C5F_4D66_963F_628E881B178B; Address: tab_Address; tab_4: tab_tab_4; tab_7: tab_tab_7; } interface Body { Tab: Tabs; msdyn_Address1: DevKit.Controls.String; msdyn_Address2: DevKit.Controls.String; msdyn_Address3: DevKit.Controls.String; /** Enter the location to ship the products of this PO to. */ msdyn_AddressName: DevKit.Controls.String; msdyn_AmountBilled: DevKit.Controls.Money; /** Enter the current status of the approval. */ msdyn_ApprovalStatus: DevKit.Controls.OptionSet; /** The user who approved or rejected this PO */ msdyn_ApprovedRejectedBy: DevKit.Controls.Lookup; /** If purchase order is being ordered directly to a booking specify here. Note, when specified, by default all products will receive directly to booking. */ msdyn_Booking: DevKit.Controls.Lookup; msdyn_City: DevKit.Controls.String; msdyn_Country: DevKit.Controls.String; /** Enter the date you expect to receive your order. Note that products added once the date is specified here will automatically be set to this date. */ msdyn_DateExpected: DevKit.Controls.Date; msdyn_Latitude: DevKit.Controls.Double; msdyn_Longitude: DevKit.Controls.Double; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Unique identifier for User associated with Purchase Order. */ msdyn_OrderedBy: DevKit.Controls.Lookup; /** The payment terms for this PO */ msdyn_PaymentTerm: DevKit.Controls.Lookup; msdyn_PostalCode: DevKit.Controls.String; /** Shows the date you submitted your order to the vendor. Note this field is for information only. */ msdyn_PODate: DevKit.Controls.Date; /** Warehouse where products of this PO will be received to */ msdyn_ReceivetoWarehouse: DevKit.Controls.Lookup; /** Resource that requested the purchase */ msdyn_RequestedByResource: DevKit.Controls.Lookup; /** Enter the location to ship to. If the PO has been associated to a work order or a schedule, you can ship directly to the service account address. */ msdyn_ShipTo: DevKit.Controls.OptionSet; /** Method of shipment by vendor */ msdyn_ShipVia: DevKit.Controls.Lookup; msdyn_StateOrProvince: DevKit.Controls.String; /** Purchase Order Substatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Enter the current status of the purchase order. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Total Amount (used by Field Service only) */ msdyn_TotalAmount: DevKit.Controls.Money; /** Vendor you wish to purchase from */ msdyn_Vendor: DevKit.Controls.Lookup; /** If you wish to display a note for the vendor on this PO specify it here */ msdyn_VendorNote: DevKit.Controls.String; /** If purchase order is being ordered directly to a work order specify here. Note, when specified, by default all products will receive directly to work order. */ msdyn_WorkOrder: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_purchaseorder_msdyn_bpf_2c5fe86acc8b414b8322ae571000c799: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_purchaseorder_msdyn_purchaseorderbill_PurchaseOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_purchaseorder_msdyn_purchaseorderproduct_PurchaseOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_purchaseorder_msdyn_purchaseorderreceipt_PurchaseOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_purchaseorder_msdyn_purchaseorderreceiptproduct_PurchaseOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface ProcessPurchase_Order_Business_Process { /** Enter the current status of the approval. */ msdyn_ApprovalStatus: DevKit.Controls.OptionSet; /** The user who approved or rejected this PO */ msdyn_ApprovedRejectedBy: DevKit.Controls.Lookup; /** Shows the date you submitted your order to the vendor. Note this field is for information only. */ msdyn_PODate: DevKit.Controls.Date; /** Warehouse where products of this PO will be received to */ msdyn_ReceivetoWarehouse: DevKit.Controls.Lookup; /** Method of shipment by vendor */ msdyn_ShipVia: DevKit.Controls.Lookup; /** Enter the current status of the purchase order. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Enter the current status of the purchase order. */ msdyn_SystemStatus_1: DevKit.Controls.OptionSet; /** Vendor you wish to purchase from */ msdyn_Vendor: DevKit.Controls.Lookup; /** If purchase order is being ordered directly to a work order specify here. Note, when specified, by default all products will receive directly to work order. */ msdyn_WorkOrder: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Purchase_Order_Business_Process: ProcessPurchase_Order_Business_Process; } interface Grid { PurchaseOrderProductsGrid: DevKit.Controls.Grid; } } class FormPurchase_Order extends DevKit.IForm { /** * DynamicsCrm.DevKit form Purchase_Order * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Purchase_Order */ Body: DevKit.FormPurchase_Order.Body; /** The Navigation of form Purchase_Order */ Navigation: DevKit.FormPurchase_Order.Navigation; /** The Process of form Purchase_Order */ Process: DevKit.FormPurchase_Order.Process; /** The Grid of form Purchase_Order */ Grid: DevKit.FormPurchase_Order.Grid; } namespace FormPurchase_Order_Mobile { interface tab_Address_Sections { fstab_address_section_address: DevKit.Controls.Section; } interface tab_fstab_details_Sections { fstab_details_column_5_section_1: DevKit.Controls.Section; fstab_details_column_6_section_1: DevKit.Controls.Section; fstab_details_section_amount: DevKit.Controls.Section; fstab_details_section_general: DevKit.Controls.Section; fstab_details_section_user_information: DevKit.Controls.Section; fstab_details_section_work_order: DevKit.Controls.Section; } interface tab_fstab_general_Sections { fstab_general_column_2_section_1: DevKit.Controls.Section; fstab_general_section_3: DevKit.Controls.Section; fstab_general_section_summary: DevKit.Controls.Section; fstab_general_section_vendor: DevKit.Controls.Section; } interface tab_fstab_other_Sections { tab_5_section_2: DevKit.Controls.Section; tab_5_section_3: DevKit.Controls.Section; tab_5_section_4: DevKit.Controls.Section; } interface tab_fstab_sub_grids_Sections { fstab_sub_grids_section_2: DevKit.Controls.Section; fstab_sub_grids_section_3: DevKit.Controls.Section; tab_7_section_1: DevKit.Controls.Section; } interface tab_Address extends DevKit.Controls.ITab { Section: tab_Address_Sections; } interface tab_fstab_details extends DevKit.Controls.ITab { Section: tab_fstab_details_Sections; } interface tab_fstab_general extends DevKit.Controls.ITab { Section: tab_fstab_general_Sections; } interface tab_fstab_other extends DevKit.Controls.ITab { Section: tab_fstab_other_Sections; } interface tab_fstab_sub_grids extends DevKit.Controls.ITab { Section: tab_fstab_sub_grids_Sections; } interface Tabs { Address: tab_Address; fstab_details: tab_fstab_details; fstab_general: tab_fstab_general; fstab_other: tab_fstab_other; fstab_sub_grids: tab_fstab_sub_grids; } interface Body { Tab: Tabs; msdyn_Address1: DevKit.Controls.String; msdyn_Address2: DevKit.Controls.String; msdyn_Address3: DevKit.Controls.String; msdyn_AmountBilled: DevKit.Controls.Money; /** Enter the current status of the approval. */ msdyn_ApprovalStatus: DevKit.Controls.OptionSet; /** The user who approved or rejected this PO */ msdyn_ApprovedRejectedBy: DevKit.Controls.Lookup; /** If purchase order is being ordered directly to a booking specify here. Note, when specified, by default all products will receive directly to booking. */ msdyn_Booking: DevKit.Controls.Lookup; msdyn_City: DevKit.Controls.String; msdyn_Country: DevKit.Controls.String; /** Enter the date you expect to receive your order. Note that products added once the date is specified here will automatically be set to this date. */ msdyn_DateExpected: DevKit.Controls.Date; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Unique identifier for User associated with Purchase Order. */ msdyn_OrderedBy: DevKit.Controls.Lookup; /** The payment terms for this PO */ msdyn_PaymentTerm: DevKit.Controls.Lookup; msdyn_PostalCode: DevKit.Controls.String; /** Shows the date you submitted your order to the vendor. Note this field is for information only. */ msdyn_PODate: DevKit.Controls.Date; /** Warehouse where products of this PO will be received to */ msdyn_ReceivetoWarehouse: DevKit.Controls.Lookup; /** Resource that requested the purchase */ msdyn_RequestedByResource: DevKit.Controls.Lookup; /** Enter the location to ship to. If the PO has been associated to a work order or a schedule, you can ship directly to the service account address. */ msdyn_ShipTo: DevKit.Controls.OptionSet; /** Method of shipment by vendor */ msdyn_ShipVia: DevKit.Controls.Lookup; msdyn_StateOrProvince: DevKit.Controls.String; /** Purchase Order Substatus */ msdyn_SubStatus: DevKit.Controls.Lookup; /** Enter the current status of the purchase order. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Total Amount (used by Field Service only) */ msdyn_TotalAmount: DevKit.Controls.Money; /** Vendor you wish to purchase from */ msdyn_Vendor: DevKit.Controls.Lookup; /** If you wish to display a note for the vendor on this PO specify it here */ msdyn_VendorNote: DevKit.Controls.String; /** If purchase order is being ordered directly to a work order specify here. Note, when specified, by default all products will receive directly to work order. */ msdyn_WorkOrder: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_purchaseorder_msdyn_bpf_2c5fe86acc8b414b8322ae571000c799: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_purchaseorder_msdyn_purchaseorderbill_PurchaseOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_purchaseorder_msdyn_purchaseorderproduct_PurchaseOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_purchaseorder_msdyn_purchaseorderreceipt_PurchaseOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_purchaseorder_msdyn_purchaseorderreceiptproduct_PurchaseOrder: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_purchaseorder_msdyn_rtv_OriginalPO: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface ProcessPurchase_Order_Business_Process { /** Enter the current status of the approval. */ msdyn_ApprovalStatus: DevKit.Controls.OptionSet; /** The user who approved or rejected this PO */ msdyn_ApprovedRejectedBy: DevKit.Controls.Lookup; /** Shows the date you submitted your order to the vendor. Note this field is for information only. */ msdyn_PODate: DevKit.Controls.Date; /** Warehouse where products of this PO will be received to */ msdyn_ReceivetoWarehouse: DevKit.Controls.Lookup; /** Method of shipment by vendor */ msdyn_ShipVia: DevKit.Controls.Lookup; /** Enter the current status of the purchase order. */ msdyn_SystemStatus: DevKit.Controls.OptionSet; /** Enter the current status of the purchase order. */ msdyn_SystemStatus_1: DevKit.Controls.OptionSet; /** Vendor you wish to purchase from */ msdyn_Vendor: DevKit.Controls.Lookup; /** If purchase order is being ordered directly to a work order specify here. Note, when specified, by default all products will receive directly to work order. */ msdyn_WorkOrder: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Purchase_Order_Business_Process: ProcessPurchase_Order_Business_Process; } interface Grid { PurchaseOrderProductsGrid: DevKit.Controls.Grid; RECEIPTS: DevKit.Controls.Grid; RECEIPT_PRODUCTS: DevKit.Controls.Grid; BILLS: DevKit.Controls.Grid; } } class FormPurchase_Order_Mobile extends DevKit.IForm { /** * DynamicsCrm.DevKit form Purchase_Order_Mobile * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Purchase_Order_Mobile */ Body: DevKit.FormPurchase_Order_Mobile.Body; /** The Navigation of form Purchase_Order_Mobile */ Navigation: DevKit.FormPurchase_Order_Mobile.Navigation; /** The Process of form Purchase_Order_Mobile */ Process: DevKit.FormPurchase_Order_Mobile.Process; /** The Grid of form Purchase_Order_Mobile */ Grid: DevKit.FormPurchase_Order_Mobile.Grid; } class msdyn_purchaseorderApi { /** * DynamicsCrm.DevKit msdyn_purchaseorderApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows the exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; msdyn_Address1: DevKit.WebApi.StringValue; msdyn_Address2: DevKit.WebApi.StringValue; msdyn_Address3: DevKit.WebApi.StringValue; /** Enter the location to ship the products of this PO to. */ msdyn_AddressName: DevKit.WebApi.StringValue; msdyn_AmountBilled: DevKit.WebApi.MoneyValue; /** Shows the value of the amount billed in the base currency. */ msdyn_amountbilled_Base: DevKit.WebApi.MoneyValueReadonly; /** Enter the current status of the approval. */ msdyn_ApprovalStatus: DevKit.WebApi.OptionSetValue; /** The user who approved or rejected this PO */ msdyn_ApprovedRejectedBy: DevKit.WebApi.LookupValue; /** Internal field used to generate the next name upon entity creation. It is optionally copied to the msdyn_name field. */ msdyn_AutoNumbering: DevKit.WebApi.StringValue; /** If purchase order is being ordered directly to a booking specify here. Note, when specified, by default all products will receive directly to booking. */ msdyn_Booking: DevKit.WebApi.LookupValue; msdyn_City: DevKit.WebApi.StringValue; msdyn_Country: DevKit.WebApi.StringValue; /** Enter the date you expect to receive your order. Note that products added once the date is specified here will automatically be set to this date. */ msdyn_DateExpected_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** For internal use only. */ msdyn_InternalFlags: DevKit.WebApi.StringValue; msdyn_Latitude: DevKit.WebApi.DoubleValue; msdyn_Longitude: DevKit.WebApi.DoubleValue; /** Enter the name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; /** Unique identifier for User associated with Purchase Order. */ msdyn_OrderedBy: DevKit.WebApi.LookupValue; /** The payment terms for this PO */ msdyn_PaymentTerm: DevKit.WebApi.LookupValue; /** Shows the date you submitted your order to the vendor. Note this field is for information only. */ msdyn_PODate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; msdyn_PostalCode: DevKit.WebApi.StringValue; /** Shows the entity instances. */ msdyn_purchaseorderId: DevKit.WebApi.GuidValue; /** Warehouse where products of this PO will be received to */ msdyn_ReceivetoWarehouse: DevKit.WebApi.LookupValue; /** Resource that requested the purchase */ msdyn_RequestedByResource: DevKit.WebApi.LookupValue; /** Enter the location to ship to. If the PO has been associated to a work order or a schedule, you can ship directly to the service account address. */ msdyn_ShipTo: DevKit.WebApi.OptionSetValue; /** Method of shipment by vendor */ msdyn_ShipVia: DevKit.WebApi.LookupValue; msdyn_StateOrProvince: DevKit.WebApi.StringValue; /** Purchase Order Substatus */ msdyn_SubStatus: DevKit.WebApi.LookupValue; /** Enter the current status of the purchase order. */ msdyn_SystemStatus: DevKit.WebApi.OptionSetValue; /** Total Amount (used by Field Service only) */ msdyn_TotalAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the total amount in the base currency. */ msdyn_totalamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Vendor you wish to purchase from */ msdyn_Vendor: DevKit.WebApi.LookupValue; /** If you wish to display a note for the vendor on this PO specify it here */ msdyn_VendorNote: DevKit.WebApi.StringValue; /** If purchase order is being ordered directly to a work order specify here. Note, when specified, by default all products will receive directly to work order. */ msdyn_WorkOrder: DevKit.WebApi.LookupValue; /** Shows the date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Contains the id of the process associated with the entity. */ processid: DevKit.WebApi.GuidValue; /** Contains the id of the stage where the entity is located. */ stageid: DevKit.WebApi.GuidValue; /** Status of the Purchase Order */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Purchase Order */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ traversedpath: DevKit.WebApi.StringValue; /** Shows the time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_purchaseorder { enum msdyn_ApprovalStatus { /** 690970000 */ Approved, /** 690970001 */ Rejected } enum msdyn_ShipTo { /** 690970001 */ Business_Unit, /** 690970003 */ Other, /** 690970002 */ Service_Account, /** 690970000 */ Site } enum msdyn_SystemStatus { /** 690970004 */ Billed, /** 690970002 */ Canceled, /** 690970000 */ Draft, /** 690970003 */ Products_Received, /** 690970001 */ Submitted } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Purchase Order','Purchase Order - Mobile'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import {ChangeDetectorRef, Component, Injector, OnDestroy, OnInit, Pipe, PipeTransform, TemplateRef, ViewChild, ViewContainerRef} from '@angular/core'; import * as angular from 'angular'; import * as _ from "underscore"; import {DomainType, DomainTypesService} from "../../../../services/DomainTypesService"; import {TableColumnDefinition} from "../../../../model/TableColumnDefinition"; import {TableFieldPartition} from "../../../../model/TableFieldPartition"; import {TableFieldPolicy} from "../../../../model/TableFieldPolicy"; import {HttpClient} from "@angular/common/http"; import {DefineFeedService, FeedEditStateChangeEvent} from "../../services/define-feed.service"; import {AbstractFeedStepComponent} from "../AbstractFeedStepComponent"; import {FeedTableColumnDefinitionValidation} from "../../../../model/feed/feed-table-column-definition-validation"; import {FormControl, FormGroup, ValidatorFn, Validators} from "@angular/forms"; import {AbstractControl} from "@angular/forms/src/model"; import {TdDialogService} from "@covalent/core/dialogs"; import {StateService} from "@uirouter/angular"; import {FeedService} from "../../../../services/FeedService"; import {ValidationErrors} from "@angular/forms/src/directives/validators"; import {TdVirtualScrollContainerComponent} from "@covalent/core/virtual-scroll"; import {FeedFieldPolicyRulesDialogService} from "../../../../shared/feed-field-policy-rules/feed-field-policy-rules-dialog.service"; import {SelectedColumn} from "./feed-table-selected-column.model"; import {Feed, SKIP_SOURCE_CATALOG_KEY} from "../../../../model/feed/feed.model"; import {FeedConstants} from "../../../../services/FeedConstants"; import {Observable} from "rxjs/Observable"; import { DomainTypeConflictDialogComponent, DomainTypeConflictDialogData, DomainTypeConflictDialogResponse } from "../../../../shared/domain-type/domain-type-conflict/domain-type-conflict-dialog.component"; import {ApplyDomainTypeDialogComponent, ApplyDomainTypeDialogData, ApplyDomainTypeDialogDataResponse} from "../../../../shared/domain-type/apply-domain-type/apply-domain-type-dialog.component"; import {CheckAll} from "../../../shared/checkAll"; import {MatDialog} from "@angular/material/dialog"; import { ApplyDomainTypesData, ApplyDomainTypesDialogComponent, ApplyDomainTypesResponse, ApplyDomainTypesResponseStatus, ApplyDomainTypesRow } from "../../../../shared/domain-type/apply-domain-types/apply-domain-types-dialog.component"; import {FeedStepConstants} from "../../../../model/feed/feed-step-constants"; import {FeedLoadingService} from "../../services/feed-loading-service"; import {FeedSideNavService} from "../../services/feed-side-nav.service"; import {FeedServiceTypes} from "../../../../services/FeedServiceTypes"; import {PreviewDataSet} from "../../../../catalog/datasource/preview-schema/model/preview-data-set"; import {ShowCatalogCanceledEvent} from "./source-sample/define-feed-step-source-sample.component"; import {PreviewFileDataSet} from "../../../../catalog/datasource/preview-schema/model/preview-file-data-set"; import {DatasetPreviewStepperSavedEvent} from "../../../../catalog-dataset-preview/preview-stepper/dataset-preview-stepper.component"; import {DefineFeedSourceSampleService} from "./source-sample/define-feed-source-sample.service"; import {CatalogService} from "../../../../catalog/api/services/catalog.service"; import {Common} from '../../../../../../lib/common/CommonTypes'; import {SaveFeedResponse} from "../../model/save-feed-response.model"; import {SchemaField} from "../../../../model/schema-field"; const moduleName = require('../../../define-feed/module-name'); class TablePermissions { tableLocked: boolean; partitionsLocked:boolean; dataTypeLocked: boolean; canRemoveFields: boolean; canAddFields:boolean; constructor() { this.canRemoveFields = true; } } @Component({ selector: "define-feed-step-table", styleUrls: ["./define-feed-table.component.css"], templateUrl: "./define-feed-table.component.html" }) export class DefineFeedTableComponent extends AbstractFeedStepComponent implements OnInit,OnDestroy{ @ViewChild("toolbarActionTemplate") private toolbarActionTemplate:TemplateRef<any>; /** * flag to check if the form is valid or not */ isValid: boolean = false; /** * Data Types in the drop down * @type {any[]} */ availableDefinitionDataTypes: string[] = []; /** * the selected field */ selectedColumn: SelectedColumn = null; /** * Array of partition formulas */ partitionFormulas: string[] = []; /** * The feed format */ feedFormat: string; /** * Metadata for the selected column tag. * @type {{searchText: null, selectedItem: null}} */ tagChips: any = {searchText: null, selectedItem: null}; /** * List of available domain types. * @type {DomainType[]} */ availableDomainTypes: DomainType[] = []; tablePermissions:TablePermissions =new TablePermissions(); feedTableColumnDefinitionValidation: FeedTableColumnDefinitionValidation; parentForm:FormGroup; /** * The table form with the fields and virtual repeate */ defineTableForm : FormGroup; /** * The possible Merge Strategies */ mergeStrategies: FeedServiceTypes.MergeStrategy[]; /** * The selected strategy defined for this feed. * This will be used when rendering the read only view */ mergeStrategy:FeedServiceTypes.MergeStrategy; /** * The possible target options */ targetFormatOptions: Common.LabelValue[]; /** * The compression Options */ compressionOptions: any[]; /** * The partition form */ definePartitionForm : FormGroup; private feedService: FeedService; private domainTypesService: DomainTypesService; private tableFormControls:TableFormControls; /** * the filter for the partition list */ private filterPartitionFormulaPipe:FilterPartitionFormulaPipe; /** * Toggle Check All/None on Profile column * Default it to true * @type {CheckAll} */ profileCheckAll: CheckAll; skippedSourceSample:boolean = false; /** * * @type {CheckAll} */ indexCheckAll: CheckAll; mergeStrategiesForm : FormGroup; targetFormatOptionsForm : FormGroup; sourceSampleForm:FormGroup; showSourceSampleCatalog:boolean; showSourceSample:boolean = true; catalogBrowserOpen:boolean = false; schemaPanelExpanded:boolean = true; targetFields:any[]; @ViewChild('virtualScroll') virtualScroll: TdVirtualScrollContainerComponent getStepName() { return FeedStepConstants.STEP_FEED_TARGET; } getToolbarTemplateRef(): TemplateRef<any> { return this.toolbarActionTemplate; } constructor(private http:HttpClient,stateService:StateService, defineFeedService:DefineFeedService,private $$angularInjector: Injector, dialogService: TdDialogService, private _viewContainerRef: ViewContainerRef, public dialog:MatDialog, private feedFieldPolicyRulesDialogService:FeedFieldPolicyRulesDialogService, feedLoadingService:FeedLoadingService, feedSideNavService:FeedSideNavService, private defineFeedSourceSampleService: DefineFeedSourceSampleService, private catalogService: CatalogService, private cd:ChangeDetectorRef) { super(defineFeedService,stateService, feedLoadingService,dialogService, feedSideNavService); this.domainTypesService = $$angularInjector.get("DomainTypesService"); this.feedService = $$angularInjector.get("FeedService"); this.mergeStrategies = angular.copy(this.feedService.mergeStrategies); this.targetFormatOptions = angular.copy(this.feedService.targetFormatOptions); this.compressionOptions = this.feedService.allCompressionOptions(); this.filterPartitionFormulaPipe = new FilterPartitionFormulaPipe(); this.profileCheckAll = new CheckAll('profile', true); this.indexCheckAll = new CheckAll( 'index', false); this.parentForm = new FormGroup({}) this.defineTableForm = new FormGroup({}); this.definePartitionForm = new FormGroup({}); this.mergeStrategiesForm = new FormGroup({}); this.targetFormatOptionsForm = new FormGroup({}); this.sourceSampleForm = new FormGroup({}) this.parentForm.addControl("defineTableForm",this.defineTableForm) this.parentForm.addControl("definePartitionForm",this.definePartitionForm) this.parentForm.addControl("mergeStrategiesForm",this.mergeStrategiesForm) this.parentForm.addControl("targetFormatOptionsForm",this.targetFormatOptionsForm) this.mergeStrategiesForm.registerControl("targetMergeStrategy", new FormControl()); this.defineTableForm.registerControl("indexCheckAll",new FormControl(this.indexCheckAll.isChecked)) this.defineTableForm.registerControl("profileCheckAll",new FormControl(this.profileCheckAll.isChecked)) } init() { this.profileCheckAll.setup(this.feed.table); this.indexCheckAll.setup(this.feed.table); let locked = this.feed.hasBeenDeployed(); // || this.feed.isDataTransformation(); this.tablePermissions.canRemoveFields = !locked this.tablePermissions.dataTypeLocked = locked this.tablePermissions.tableLocked = locked this.tablePermissions.canAddFields = !locked && !this.feed.isDataTransformation() && this.feed.table.method != "EXISTING_TABLE"; this.tablePermissions.partitionsLocked = this.feed.hasBeenDeployed(); if(this.feed.hasBeenDeployed()){ this.targetFields = this.feed.table.tableSchema.fields; } else { this.targetFields = this.feed.table.feedDefinitionTableSchema.fields; } this.feedTableColumnDefinitionValidation = new FeedTableColumnDefinitionValidation(this.definePartitionForm, this.feed); this.tableFormControls = new TableFormControls(this.defineTableForm,this.definePartitionForm, this.feedTableColumnDefinitionValidation,this.tablePermissions) //fetch the domain types this.domainTypesService.findAll().then((domainTypes: DomainType[]) => { this.availableDomainTypes = _.sortBy(domainTypes, "title"); //apply domain types when the schema has changed if(this.feed.table.schemaChanged) { this.applyDomainTypes(); this.feed.table.schemaChanged = false; } }); this.availableDefinitionDataTypes = FeedConstants.columnDefinitionDataTypes.slice(); //ensure the table field datatypes exist this.ensureTableFields(); //ensure the partition datatypes exist with proper form controls this.ensurePartitionData(); // Retrieve partition formulas this.feedService.getPartitionFunctions() .then((functions: any) => { this.partitionFormulas = functions; }); if(this.feed.table.targetMergeStrategy) { this.mergeStrategy = this.mergeStrategies.find((strategy: FeedServiceTypes.MergeStrategy) => strategy.type == this.feed.table.targetMergeStrategy) } this.targetFormatOptionsForm.registerControl("targetFormat", new FormControl({value:'',disabled:this.feed.readonly || this.feed.hasBeenDeployed()})); this.targetFormatOptionsForm.registerControl("compressionFormat", new FormControl({value:'',disabled:this.feed.readonly || this.feed.hasBeenDeployed()})); //listen when the form is valid or invalid this.subscribeToFormChanges(this.parentForm); this.subscribeToFormDirtyCheck(this.defineTableForm); this.subscribeToFormDirtyCheck(this.definePartitionForm); this.subscribeToFormDirtyCheck(this.mergeStrategiesForm); this.subscribeToFormDirtyCheck(this.targetFormatOptionsForm); if(this.feed.isDataTransformation() || (this.feed.hasBeenDeployed() && this.feed.sampleDataSet == undefined)){ this.showSourceSample = false; } if (this.feed.sampleDataSet == undefined && !this.skippedSourceSample && this.feed.table.feedDefinitionTableSchema.fields.length ==0) { this.showSourceSampleCatalog = true; } } feedStateChange(event: FeedEditStateChangeEvent) { super.feedStateChange(event); if (this.feed.readonly || this.tablePermissions.tableLocked) { this.targetFormatOptionsForm.get("targetFormat").disable(); this.targetFormatOptionsForm.get("compressionFormat").disable(); } else { this.targetFormatOptionsForm.get("targetFormat").enable(); this.targetFormatOptionsForm.get("compressionFormat").enable(); } } protected feedEdit(feed:Feed){ this.ensureTableFields(); } /** * Helper method called from the html to see if the field control has an error * @param {string} prefix * @param {TableColumnDefinition} field * @param {string} validationKey * @return {boolean} */ hasTableFormError(prefix:string,field:TableColumnDefinition, validationKey:string){ return this.tableFormControls.hasTableFormError(prefix,field,validationKey) } /** * Helper method called from the html to see if the field control has an error * @param {string} prefix * @param {TableFieldPartition} field * @param {string} validationKey * @return {boolean} */ hasPartitionFormError(prefix:string,field:TableFieldPartition, validationKey:string){ return this.tableFormControls.hasPartitionFormError(prefix,field,validationKey); } /** * Adding a new Column to the schema * This is called both when the user clicks the "Add Field" * If adding from the UI the {@code columnDef} will be null, otherwise it will be the parsed ColumnDef from the sample file * @param columnDef */ addColumn(columnDef?: TableColumnDefinition, syncFieldPolicies?: boolean) { let newColumn = this.feed.table.addColumn(columnDef, syncFieldPolicies); if(this.targetFields.find((col:any) => col._id != undefined && col._id == newColumn._id) == undefined) { this.targetFields.push(newColumn); } this.tableFormControls.addTableFieldFormControl(newColumn) this.feedTableColumnDefinitionValidation.validateColumn(newColumn); if(this.virtualScroll) { this.virtualScroll.refresh(); } this.defineTableForm.markAsDirty(); if(this.virtualScroll){ setTimeout(()=>{this.virtualScroll.scrollToEnd()}, 50); } } /** * Remove a column from the schema * @param index */ removeColumn(index: number) { let columnDef = this.feed.table.removeColumn(index) this.feed.table.getPartitionsOnColumn(columnDef.name).forEach(partition => { let index = this.feed.table.partitions.indexOf(partition); this.removePartitionField(index); }); this.tableFormControls.updateFieldState(columnDef); //ensure the field names on the columns are unique again as removing a column might fix a "notUnique" error this.feedTableColumnDefinitionValidation.validateColumn(columnDef); this.feedTableColumnDefinitionValidation.partitionNamesUnique(); this.isValid = this.feedTableColumnDefinitionValidation.validate(); } undoColumn(index: number) { let columnDef = this.feed.table.undoColumn(index); this.feedTableColumnDefinitionValidation.validateColumn(columnDef); this.feedTableColumnDefinitionValidation.partitionNamesUnique(); this.feed.table.syncTableFieldPolicyNames(); this.isValid = this.feedTableColumnDefinitionValidation.validate(); this.tableFormControls.updateFieldState(columnDef); } /** * Add a partition to the schema * This is called from the UI when the user clicks "Add Partition" */ addPartitionField() { var partitionLength = this.feed.table.partitions.length; var partition = TableFieldPartition.atPosition(partitionLength); this.tableFormControls.addPartitionFieldFormControl(partition) this.feed.table.partitions.push(partition); }; /** * Remove the partition from the schecma * @param index */ removePartitionField(index: number) { let partitions = this.feed.table.partitions.splice(index, 1); this.feedTableColumnDefinitionValidation.partitionNamesUnique(); this.tableFormControls.removePartitionFieldFormControls(partitions[0]); }; onIndexCheckAllChange() : boolean { this.indexCheckAll.toggleAll(); let checked = this.indexCheckAll.isChecked; //update the form values this.feed.table.feedDefinitionFieldPolicies.forEach(fieldPolicy => { let ctrl = this.tableFormControls.getFormControl(this.defineTableForm,"index",fieldPolicy.field); ctrl.setValue(checked); fieldPolicy.index = checked; }); return false; } onProfileCheckAllChange() : boolean{ this.profileCheckAll.toggleAll(); let checked = this.profileCheckAll.isChecked; //update the form values this.feed.table.feedDefinitionFieldPolicies.forEach(fieldPolicy => { let ctrl = this.tableFormControls.getFormControl(this.defineTableForm,"profile",fieldPolicy.field); ctrl.setValue(checked); fieldPolicy.profile = checked; }); return false; } onIndexChange(columnDef:TableColumnDefinition){ this._selectColumn(columnDef); this.selectedColumn.fieldPolicy.index = !this.selectedColumn.fieldPolicy.index this.indexCheckAll.clicked(!this.selectedColumn.fieldPolicy.index); } onProfileChange(columnDef:TableColumnDefinition){ this._selectColumn(columnDef); this.selectedColumn.fieldPolicy.profile = !this.selectedColumn.fieldPolicy.profile this.profileCheckAll.clicked(!this.selectedColumn.fieldPolicy.profile); } /** * * @param {TableColumnDefinition} selectedColumn */ onSelectedColumn(columnDef: TableColumnDefinition) { this._selectColumn(columnDef); }; onPrecisionChange(columnDef: TableColumnDefinition) { this.feedTableColumnDefinitionValidation.validateColumn(columnDef); this.onFieldChange(columnDef); }; onDataTypeChange(columnDef :TableColumnDefinition){ if(columnDef.derivedDataType == "decimal"){ this.defineTableForm.get("precisionScale_" + columnDef._id).enable() } else { this.defineTableForm.get("precisionScale_" + columnDef._id).disable(); } this.onFieldChange(columnDef); if(!columnDef.isDate()) { if(columnDef.createdTracker){ columnDef.changeColumn() columnDef.createdTracker = false; } if(columnDef.updatedTracker){ columnDef.changeColumn() columnDef.updatedTracker = false; } } } onSchemaPanelExpanded() { this.schemaPanelExpanded = true; } onSchemaPanelCollapsed() { this.schemaPanelExpanded = false; // Set merge strategy state if primary key is available let pkSet = _.any(this.feed.table.feedDefinitionTableSchema.fields, (value, index) => { return (value.primaryKey); }); let pkMergeStrategy = _.find(this.mergeStrategies, (value,index) => { return (value.type == 'PK_MERGE'); }); if (pkMergeStrategy != undefined) { pkMergeStrategy.disabled = !pkSet; } } /** * When the schema field changes it needs to * - ensure the names are unique * - update the respective partition names if there is a partition on the field with the 'val' formula * - ensure that partition names are unique since the new field name could clash with an existing partition * @param columnDef */ onNameFieldChange(columnDef: TableColumnDefinition, index: number) { columnDef.replaceNameSpaces(); this.onFieldChange(columnDef); //update the partitions with "val" on this column so the name matches _.each(this.feed.table.partitions, (partition: TableFieldPartition) => { if (partition.columnDef == columnDef) { partition.syncSource(); partition.updateFieldName(); } }); this.feedTableColumnDefinitionValidation.validateColumn(columnDef); this.feedTableColumnDefinitionValidation.partitionNamesUnique(); this.feed.table.syncFieldPolicy(columnDef,index); // Check if column data type matches domain data type var policy = <TableFieldPolicy>this.feed.table.feedDefinitionFieldPolicies[index]; var domainType = policy.$currentDomainType; if (policy.domainTypeId && domainType.field && columnDef.$allowDomainTypeConflict !== true) { var nameChanged = (domainType.field.name && columnDef.name !== domainType.field.name); var dataTypeChanged = (domainType.field.derivedDataType && columnDef.derivedDataType !== domainType.field.derivedDataType); if (nameChanged || dataTypeChanged) { let domainTypeDialogData:DomainTypeConflictDialogData = {columnDef:columnDef,domainType:domainType, propertyName:'', propertyValue:''}; const dialogRef = this.dialog.open(DomainTypeConflictDialogComponent, { width: '600px', data: domainTypeDialogData }); dialogRef.afterClosed().subscribe((keep:DomainTypeConflictDialogResponse) => { if (keep == DomainTypeConflictDialogResponse.Keep) { columnDef.$allowDomainTypeConflict = true; } else if(keep == DomainTypeConflictDialogResponse.Remove) { delete policy.$currentDomainType; delete policy.domainTypeId; } else if(keep == DomainTypeConflictDialogResponse.Cancel){ this.undoColumn(index); } }); } } } /** * Open the standardizers and validators * @param {SelectedColumn} selectedColumn */ onFieldPoliciesClicked(selectedColumn:SelectedColumn){ let fieldPolicy: TableFieldPolicy = this.feed.table.feedDefinitionFieldPolicies.find(policy => policy.fieldName == selectedColumn.field.name ); if(fieldPolicy) { this.feedFieldPolicyRulesDialogService.openDialog(this.feed, fieldPolicy).subscribe((result:any) => { this.selectedColumn.update() }); } } /** * When a partition Source field changes it needs to * - auto select the formula if there is only 1 in the drop down (i.e. fields other than dates/timestamps will only have the 'val' formula * - ensure the partition data mapping to this source field is correct * - attempt to prefill in the name with some default name. if its a val formula it will default the partition name to the source field name and leave it disabled * @param partition */ onPartitionSourceFieldChange(partition: TableFieldPartition, feed:Feed) { //set the partition data to match the selected sourceField partition.syncSource(); //if there is only 1 option in the formula list then auto select it var formulas:string[] = this.filterPartitionFormulaPipe.transform(this.partitionFormulas, partition,feed); if (formulas.length == 1) { partition.formula = formulas[0]; } partition.updateFieldName(); this.updatePartitionNameState(partition); setTimeout(() => {this.feedTableColumnDefinitionValidation.partitionNamesUnique()}, 50); } filterFormula(partition: TableFieldPartition, feed: Feed){ return this.filterPartitionFormulaPipe.transform(this.partitionFormulas, partition,feed); } /** * When a partition formula changes it needs to * - attempt to prefill in the name with some default name. if its a val formula it will default the partition name to the source field name and leave it disabled * @param partition */ onPartitionFormulaChange(partition: TableFieldPartition) { partition.updateFieldName(); this.feedTableColumnDefinitionValidation.partitionNamesUnique(); this.updatePartitionNameState(partition); } updatePartitionNameState(partition: TableFieldPartition) : void { let nameField = this.definePartitionForm.get('partitionName_'+partition._id); if (partition.allowPartitionNameChanges()) { nameField.enable({onlySelf:true}); } else { nameField.disable({onlySelf:true}); } } /** * when the partition name changes it needs to * - ensure the names are unique * - ensure no dups (cannot have more than 1 partitoin on the same col/formula * @param partition */ onPartitionNameChange(partition: any) { partition.replaceSpaces(); this.feedTableColumnDefinitionValidation.partitionNamesUnique(); }; private onFieldChange(columnDef: TableColumnDefinition) { this._selectColumn(columnDef); columnDef.changeColumn(); this.feedTableColumnDefinitionValidation.validateColumn(columnDef); } private _selectColumn(columnDef:TableColumnDefinition){ let fieldPolicy = columnDef.fieldPolicy; if(fieldPolicy == undefined) { fieldPolicy = this.feed.table.feedDefinitionFieldPolicies.find(policy => policy.fieldName == columnDef.name); } this.selectedColumn = new SelectedColumn(columnDef, fieldPolicy); this.selectedColumn.setDomainType(this.availableDomainTypes); } /** * Ensure that for the partitions the sourceField and sourceDataTypes match the respective schema field data */ private ensurePartitionData() { _.each(this.feed.table.partitions, (partition: TableFieldPartition) => { if (partition.columnDef == undefined) { let columnDef = this.feed.table.getColumnDefinitionByName(partition.sourceField) if (columnDef != null) { partition.columnDef = columnDef; } } partition.syncSource(); this.tableFormControls.addPartitionFieldFormControl(partition); }); } /** * Detects and applies domain types to all columns. */ private applyDomainTypes() { // Detect domain types var data: ApplyDomainTypesData = {domainTypes: [], fields: []}; this.feed.table.feedDefinitionTableSchema.fields.forEach((field: TableColumnDefinition, index: number) => { var domainType = this.domainTypesService.detectDomainType(field, this.availableDomainTypes); if (domainType !== null) { if (this.domainTypesService.matchesField(domainType, field)) { // Domain type can be applied immediately field.applyDomainType(domainType); field.history = []; field.addHistoryItem(); } else { // Domain type needs user confirmation data.domainTypes.push(domainType); data.fields.push(field); } } }); if(data.fields.length >0) { this.confirmDomainTypes(data); } } private confirmDomainTypes(applyDomainTypesData:ApplyDomainTypesData){ const dialogRef = this.dialog.open(ApplyDomainTypesDialogComponent, { width: '600px', data: applyDomainTypesData }); dialogRef.afterClosed().subscribe((response:ApplyDomainTypesResponse) => { if(response.status == ApplyDomainTypesResponseStatus.APPLY) { response.appliedRows.forEach((selection:ApplyDomainTypesRow) => { var fieldIndex = applyDomainTypesData.fields.findIndex((element: any) => { return element.name === selection.name; }); let columnDef = <TableColumnDefinition> applyDomainTypesData.fields[fieldIndex]; let domainType = applyDomainTypesData.domainTypes[fieldIndex]; columnDef.applyDomainType(domainType); columnDef.history = []; columnDef.addHistoryItem(); }); } }); } /** * Display a confirmation when the domain type of a field is changed and there are existing standardizers and validators. * * @param {SelectedColumn} the selected column */ onDomainTypeChange(selectedColumn:SelectedColumn) { // Check if removing domain type if (selectedColumn.fieldPolicy.domainTypeId == undefined) { delete selectedColumn.fieldPolicy.$currentDomainType; return; } // Find domain type from id let domainType = _.find(this.availableDomainTypes, (domainType: DomainType) => { return (domainType.id === selectedColumn.fieldPolicy.domainTypeId); }); if (domainType && selectedColumn.showDomainTypeDialog()) { let dialogData: ApplyDomainTypeDialogData = {column: selectedColumn, domainType: domainType}; const dialogRef = this.dialog.open(ApplyDomainTypeDialogComponent, { width: '600px', data: dialogData }); dialogRef.afterClosed().subscribe((response: ApplyDomainTypeDialogDataResponse) => { if (response == ApplyDomainTypeDialogDataResponse.Apply) { selectedColumn.applyDomainType(domainType); } else { //revert it selectedColumn.fieldPolicy.domainTypeId = selectedColumn.fieldPolicy.$currentDomainType ? selectedColumn.fieldPolicy.$currentDomainType.id : null; } }); } else if(domainType){ //apply it selectedColumn.applyDomainType(domainType); } } /** * Called when a user transitions from the Wrangler to this step */ private onDataTransformSchemaLoaded() { this.ensureTableFields(); if (angular.isDefined(this.feed.schemaChanged) && this.feed.schemaChanged == true) { this.isValid = false; /* this.$mdDialog.show( this.$mdDialog.alert() .parent(angular.element(document.body)) .clickOutsideToClose(true) .title('Table Schema Changed') .htmlContent('The table schema no longer matches the schema previously defined. <br/><br/> This is invalid. If you wish to modify the underlying schema <br/> (i.e. change some column names and/or types) please clone<br/> the feed as a new feed instead.') .ariaLabel('Table Schema Changed ') .ok('Got it!') ); */ } } private ensureTableFields(){ if (this.feed.table.feedDefinitionTableSchema.fields && this.feed.table.feedDefinitionTableSchema.fields.length > 0) { //ensure data types let targetFormFields = []; this.feed.table.feedDefinitionTableSchema.fields.forEach((columnDef: TableColumnDefinition) => { // add exotic data type to available columns if needed if ($.inArray(columnDef.derivedDataType, this.availableDefinitionDataTypes) == -1) { this.availableDefinitionDataTypes.push(columnDef.derivedDataType); } columnDef.replaceNameSpaces(); columnDef.initFeedColumn() //add the form control this.tableFormControls.addTableFieldFormControl(columnDef,false); if(this.feed.hasBeenDeployed()) { if(!columnDef.deleted) { targetFormFields.push(columnDef); } } else { targetFormFields.push(columnDef); } }); this.targetFields = targetFormFields; this.defineTableForm.get("indexCheckAll").setValue(this.indexCheckAll.isChecked) this.defineTableForm.get("profileCheckAll").setValue(this.profileCheckAll.isChecked) } this.calcTableState(); this.isValid = this.feedTableColumnDefinitionValidation.validate(); } /** * Set the table states for locks */ private calcTableState() { this.tablePermissions.tableLocked = angular.isDefined(this.tablePermissions.tableLocked) && (this.tablePermissions.tableLocked == true ); this.tablePermissions.dataTypeLocked = angular.isDefined(this.tablePermissions.dataTypeLocked) && (this.tablePermissions.dataTypeLocked == true ); this.tablePermissions.canRemoveFields = angular.isUndefined(this.tablePermissions.canRemoveFields) || this.tablePermissions.canRemoveFields === true ; } /* Create columns for tracking changes between original source and the target table schema @deprecated */ private syncFeedsColumns() { _.each(this.feed.table.feedDefinitionTableSchema.fields, (columnDef: TableColumnDefinition) => { columnDef.initFeedColumn() }); } tableSchemaTrackByFn(index:number,field:TableColumnDefinition) { return field._id; } onShowCatalogChange($event:boolean){ this.catalogBrowserOpen = $event; } onCatalogCanceled($event:ShowCatalogCanceledEvent){ if($event.skip){ //mark it in the metadata this.step.addProperty(SKIP_SOURCE_CATALOG_KEY,true); this.skippedSourceSample = true; } } onSchemaPanelEdit($event:any) { //$event.preventDefault(); //this.schemaPanelExpanded = true; } onSchemaPanelCancel($event:any) { //$event.preventDefault(); //this.schemaPanelExpanded = false; } onSchemaPanelSave($event:any) { $event.preventDefault(); this.registerLoading(); this.defineFeedService.saveFeed(this.feed, false,this.step).subscribe((response: SaveFeedResponse) => { this.defineFeedService.openSnackBar("Saved", 1500); this.resolveLoading(); this.step.clearDirty(); this.schemaPanelExpanded = false; }, error1 => { this.resolveLoading() this.defineFeedService.openSnackBar("Error saving feed ", 3000); }) } onSampleSourceSaved(previewEvent: DatasetPreviewStepperSavedEvent) { let previews: PreviewDataSet[] = previewEvent.previews; if (previews && previews.length) { let feedDataSets = this.feed.sourceDataSets; //check to see if schema differs if (feedDataSets && feedDataSets.length > 0) { let feedDatasetKeys = feedDataSets.map(ds => ds.id).sort().toString(); let newDatasetKeys = previews.map(ds => ds.key).sort().toString(); if (feedDatasetKeys != "" && feedDatasetKeys != newDatasetKeys) { //WARN different datasets this.dialogService.openConfirm({ message: 'The dataset you have selected differs from the one existing on this feed. Switching the source will result in a new target schema. Are you sure you want to do this?', disableClose: true, title: 'Confirm source dataset change', }).afterClosed().subscribe((accept: boolean) => { if (accept) { this._setSourceAndTarget(previewEvent); } else { // no op } }); } else { this._setSourceAndTarget(previewEvent); } } else { this._setSourceAndTarget(previewEvent); } } else { this._setSourceAndTarget(previewEvent) } } private _setSourceAndTarget(event: DatasetPreviewStepperSavedEvent) { this.feedLoadingService.registerLoading(); //detach the change detector so we can make the updates without angular this.cd.detach() let _updateFormControls = () => { //apply the updates to this form this.ensureTableFields(); this.ensurePartitionData(); this.feed.table.syncTableFieldPolicyNames() this.showSourceSampleCatalog = false; this.catalogBrowserOpen = false; if(this.virtualScroll) { this.virtualScroll.refresh(); } this.feedLoadingService.resolveLoading(); this.cd.reattach(); this.cd.markForCheck(); this.cd.detectChanges(); } /** * Applies the Serde if necessary and then update the form controls */ let applySerdeAndUpdateFormControls = () => { if(event.previews[0] instanceof PreviewFileDataSet) { this.defineFeedSourceSampleService.parseTableSettings((<PreviewFileDataSet>event.previews[0])).subscribe( (response:any)=> { this.feed.table.feedFormat = response.hiveFormat; this.feed.structuredData(response.structured); this.feed.table.feedTblProperties = response.serdeTableProperties; _updateFormControls(); }, (error1:any) => this.cd.reattach()); } else { _updateFormControls(); } } // reset the feed fields this.selectedColumn = undefined; this.tableFormControls.resetFormFields(); let previews = event.previews; let singleSelection = event.singleSelection; let firstPreview = previews && previews.length >0 ? previews[0] : undefined; if (firstPreview && singleSelection) { const sampleDataSet = firstPreview.toSparkDataSet(); if (sampleDataSet.dataSource && sampleDataSet.dataSource.connector && sampleDataSet.dataSource.connector.pluginId) { this.catalogService.getConnectorPlugin(sampleDataSet.dataSource.connector.pluginId) .subscribe(plugin => { this.feed.setSampleDataSetAndUpdateTarget(sampleDataSet, firstPreview,undefined, plugin) applySerdeAndUpdateFormControls(); }, (error1:any) => this.cd.reattach()); } else { this.feed.setSampleDataSetAndUpdateTarget(sampleDataSet, firstPreview); applySerdeAndUpdateFormControls(); } } else { //set the source and target to empty this.feed.setSampleDataSetAndUpdateTarget(null, null); applySerdeAndUpdateFormControls(); } } protected applyUpdatesToFeed(): Observable<any> | boolean | null { if(this.catalogBrowserOpen){ return this.dialogService.openConfirm( {title:"Pending source sample changes", message:"There are pending changes in the source sample that have not been applied to the target. Are you sure you want to save without applying these changes? ", acceptButton: "Abandon changes", cancelButton: "Cancel and review" }).afterClosed(); } return this.parentForm.valid; } } @Pipe({name: 'filterPartitionFormula'}) export class FilterPartitionFormulaPipe implements PipeTransform{ constructor() {} transform(formulas:string[], partition?:TableFieldPartition, feed?:Feed){ let formulaList = formulas; if(partition && partition.sourceField && feed) { let columnDef :TableColumnDefinition = feed.table.getColumnDefinitionByName(partition.sourceField) if(columnDef != null && columnDef != undefined){ if (columnDef.derivedDataType !== "date" && columnDef.derivedDataType !== "timestamp") { formulaList = _.without(formulas, "to_date", "year", "month", "day", "hour", "minute"); } } } return formulaList; } } class TableFormControls { public constructor(public defineTableForm:FormGroup,public definePartitionForm:FormGroup, private feedTableColumnDefinitionValidation: FeedTableColumnDefinitionValidation, private tablePermissions:TablePermissions ){ } public static TABLE_COLUMN_DEF_NAME_PREFIX:string = "name"; public static TABLE_COLUMN_DEF_DATA_TYPE_PREFIX:string = "dataType"; public static TABLE_COLUMN_DEF_PRECISION_SCALE_PREFIX:string = "precisionScale"; public static TABLE_COLUMN_DEF_INDEX_PREFIX:string = "index"; public static TABLE_COLUMN_DEF_PROFILE_PREFIX:string = "profile"; public static TABLE_COLUMN_DEF_PREFIXES :string[] = [TableFormControls.TABLE_COLUMN_DEF_NAME_PREFIX, TableFormControls.TABLE_COLUMN_DEF_DATA_TYPE_PREFIX, TableFormControls.TABLE_COLUMN_DEF_PRECISION_SCALE_PREFIX, TableFormControls.TABLE_COLUMN_DEF_INDEX_PREFIX, TableFormControls.TABLE_COLUMN_DEF_PROFILE_PREFIX]; public static precisionScale(control: AbstractControl): ValidationErrors { let pattern = new RegExp("[0-9]+(,[0-9]+)"); return control.value ? (pattern.test(control.value) ? null : {'precisionScale': true}) : null; } feedNameValidator(form: FeedTableColumnDefinitionValidation, columnDef:TableColumnDefinition): ValidatorFn { return (control: AbstractControl): {[key: string]: any} | null => { form.validateFeedName(columnDef); if(columnDef.validationErrors.name.notUnique){ return {"notUnique":true}; } else if(columnDef.validationErrors.name.reserved){ return {"reserved":true}; } else if(columnDef.validationErrors.name.length){ return {"length":true}; } else { return null; } }; } private buildTableFieldFormControl(field: TableColumnDefinition ) :Common.Map<FormControl> { let controls :Common.Map<FormControl> = {} let nameControl = new FormControl({value:field.name,disabled:field.deleted|| this.tablePermissions.tableLocked },[Validators.required, this.feedNameValidator(this.feedTableColumnDefinitionValidation,field)]); // nameControl.valueChanges.subscribe() //(change)="onNameFieldChange(row,index)"> controls[TableFormControls.TABLE_COLUMN_DEF_NAME_PREFIX+"_"+field._id] = nameControl; controls[TableFormControls.TABLE_COLUMN_DEF_DATA_TYPE_PREFIX+"_"+field._id] = new FormControl({value:field.derivedDataType,disabled:field.deleted|| this.tablePermissions.dataTypeLocked|| this.tablePermissions.tableLocked },[Validators.required]); controls[TableFormControls.TABLE_COLUMN_DEF_PRECISION_SCALE_PREFIX+"_" + field._id] = new FormControl({value:field.precisionScale,disabled:this.tablePermissions.dataTypeLocked || field.deleted},[TableFormControls.precisionScale]); let index = field.fieldPolicy ? field.fieldPolicy.index : false; let profile = field.fieldPolicy ? field.fieldPolicy.profile: false; controls[TableFormControls.TABLE_COLUMN_DEF_INDEX_PREFIX+"_" + field._id] = new FormControl({value:index,disabled:field.isComplex() || field.deleted },[]); controls[TableFormControls.TABLE_COLUMN_DEF_PROFILE_PREFIX+"_" + field._id] = new FormControl({value:profile,disabled:field.isComplex() || field.deleted },[]); return controls; } getTableFieldFormControl(prefix:string,field:TableColumnDefinition){ return this.getFormControl(this.defineTableForm,prefix,field); } resetFormFields() { Object.keys(this.defineTableForm.controls).forEach((key: string) => { if(key != "indexCheckAll" && key != "profileCheckAll") { this.defineTableForm.removeControl(key) } }); Object.keys(this.definePartitionForm.controls).forEach((key: string) => { this.definePartitionForm.removeControl(key); }); } addTableFieldFormControl(columnDef:TableColumnDefinition,touch:boolean =false){ let formControls :{ [key: string]: AbstractControl; } = this.buildTableFieldFormControl(columnDef); let keys :string[] = Object.keys(formControls) keys.forEach(key => { const ctrl = formControls[key]; if(touch) { //mark it as touched to force validation ctrl.markAsTouched({onlySelf:true}); } this.defineTableForm.addControl(key,ctrl); }) } private buildPartitionFieldFormControl(partition: TableFieldPartition ) :Common.Map<FormControl> { let controls :Common.Map<FormControl> = {} controls["partitionColumnRef_"+partition._id] = new FormControl({value:'',disabled:this.tablePermissions.partitionsLocked},[Validators.required]); controls["partitionFormula_"+partition._id] = new FormControl({value:partition.formula,disabled:this.tablePermissions.partitionsLocked},[Validators.required]); controls["partitionName_"+partition._id] = new FormControl({value:partition.field,disabled:(!partition.allowPartitionNameChanges() || this.tablePermissions.partitionsLocked)},[Validators.required]); return controls; } getFormControl(form:FormGroup,prefix:string,field:TableColumnDefinition | TableFieldPartition){ return form.get(prefix+"_"+field._id); } hasTableFormError(prefix:string,field:TableColumnDefinition, validationKey:string){ let formControl = this.getFormControl(this.defineTableForm,prefix,field); return formControl ? formControl.hasError(validationKey) : false; } hasPartitionFormError(prefix:string,field:TableFieldPartition, validationKey:string){ let formControl = this.getFormControl(this.definePartitionForm,prefix,field); return formControl ? formControl.hasError(validationKey) : false; } addPartitionFieldFormControl(partition:TableFieldPartition){ let formControls :{ [key: string]: AbstractControl; } = this.buildPartitionFieldFormControl(partition); let keys :string[] = Object.keys(formControls) keys.forEach(key => { const ctrl = formControls[key]; //mark it as touched to force validation ctrl.markAsTouched({onlySelf:true}); this.definePartitionForm.addControl(key,ctrl); }) } removePartitionFieldFormControls(partition:TableFieldPartition){ this.definePartitionForm.removeControl("partitionColumnRef_"+partition._id); this.definePartitionForm.removeControl("partitionFormula_"+partition._id); this.definePartitionForm.removeControl("partitionName_"+partition._id); } updateFieldState(field:TableColumnDefinition){ TableFormControls.TABLE_COLUMN_DEF_PREFIXES.forEach(prefix => { let formControl = this.getFormControl(this.defineTableForm,prefix,field); if(field.deleted){ formControl.disable(); } else { formControl.enable() } }) } }
the_stack
import * as Sequelize from 'sequelize'; import { IDatabaseDiffs, IRelation, IApplyOptions, IActionData } from '@materia/interfaces'; import { App } from './app'; import { MigrationType } from './history'; import { DBEntity } from './entities/db-entity'; import { Entity } from './entities/entity'; export class Synchronizer { constructor(private app: App) {} diff(): Promise<IDatabaseDiffs> { return this.app.database.interface.showTables().then((dbTables) => { const entities = this.app.entities.findAll().filter((entity: Entity): entity is DBEntity => entity instanceof DBEntity); const diffs = this._diffMap(entities, dbTables); return Promise.resolve(diffs); }); } entitiesToDatabase(diffs: IDatabaseDiffs, options?: IApplyOptions): Promise<IActionData[]> { options = Object.assign({}, options || {}); options.history = false; options.apply = false; options.save = false; const actions = []; for (const type of ['relations', 'fields', 'entities']) { for (const action of diffs[type]) { actions.push(action); } } return this.app.history.revert(actions, options); } databaseToEntities(diffs: IDatabaseDiffs, options?: IApplyOptions): Promise<IActionData[]> { options = Object.assign({}, options || {}); options.history = false; options.db = false; const actions = this._constructEntitiesDiffs(diffs.entities); diffs.entities.forEach(diff => { const findAction = actions.find(a => { return a.redo.type == diff.redo.type && a.redo.table == diff.redo.table; }); if ( ! findAction ) { actions.push(diff); } }); for (const type of ['fields', 'relations']) { for (const action of diffs[type]) { actions.push(action); } } return this.app.history.apply(actions, options) .then(() => this.app.entities.sync()) .then(() => actions); } private _compareField(dbfield, field, entity): any { const props = ['name', 'type', 'primary', 'required', 'autoIncrement', 'default', 'defaultValue', 'onUpdate', 'onDelete']; const diff = [{}, {}] as any; let found = false; if (field.defaultValue === Sequelize.NOW) { field.defaultValue = 'now()'; } if ( this.app.database && this.app.database.type === 'sqlite' && field.isRelation && field.isRelation.type === 'belongsTo' && dbfield.default ) { if ( ! field.onDelete || field.onDelete && field.onDelete.toUpperCase() === 'CASCADE') { field.default = true; field.defaultValue = dbfield.number ? parseInt(dbfield.defaultValue, 10) : dbfield.defaultValue; } } for (const k of props) { if (Array.isArray(dbfield[k])) { if (dbfield[k].indexOf(field[k]) == -1) { diff[0][k] = dbfield[k][0]; diff[1][k] = field[k]; found = true; } } else if ( dbfield[k] != field[k] && (k != 'defaultValue' || (new Date(dbfield[k])).getTime() != (new Date(field[k])).getTime()) ) { diff[0][k] = dbfield[k]; diff[1][k] = field[k]; found = true; } } if ( dbfield.unique !== field.unique && ! dbfield.primary && ! field.primary && ! (dbfield.unique === true && (typeof field.unique == 'string') && entity.getUniqueFields(field.unique).length == 1) ) { diff[0].unique = dbfield.unique; diff[1].unique = field.unique; found = true; } else if (dbfield.primary && dbfield.number && dbfield.autoIncrement) { diff[0].unique = true; } if ( ! found) { return false; } return diff; } private _constructEntitiesDiffs(entitiesDiffs: IDatabaseDiffs['entities']) { let result = []; if (entitiesDiffs && entitiesDiffs.length) { const entitiesWithoutRelationsDiffs = entitiesDiffs.filter(diff => diff.redo && diff.redo.type === MigrationType.CREATE_ENTITY && diff.redo.value && (! diff.redo.value.relations || (diff.redo.value.relations && diff.redo.value.relations.length === 0)) ); const entitiesWithRelationsDiffs = entitiesDiffs.filter(diff => diff.redo && diff.redo.type === MigrationType.CREATE_ENTITY && diff.redo.value && diff.redo.value.relations && diff.redo.value.relations.length > 0 ); result = this._sortCreateEntitiesDiffsWithRelations(entitiesWithRelationsDiffs, entitiesWithoutRelationsDiffs); const otherEntitiesDiffs = entitiesDiffs.filter(diff => ! diff.redo || ( diff.redo && diff.redo.type !== MigrationType.CREATE_ENTITY ) ); result = [...result, ...otherEntitiesDiffs]; } return result; } private _sortCreateEntitiesDiffsWithRelations( entitiesWithRelationsDiffs: IDatabaseDiffs['entities'], loadedDiffs: IDatabaseDiffs['entities'] ) { // const totalEntities = loadedDiffs.length + entitiesWithRelationsDiffs.length; let finish = true; entitiesWithRelationsDiffs.forEach(diff => { const relatedEntities = diff.redo.value.relations.map((relation: IRelation) => relation.reference.entity); const alreadyLoadedEntitiesInDiffs = loadedDiffs.map(d => d.redo.value.name); const alreadyLoadedEntities = [...this.app.entities.findAll().map(e => e.name), ...alreadyLoadedEntitiesInDiffs]; let missing = false; relatedEntities.forEach(entityName => { if (alreadyLoadedEntities.indexOf(entityName) === -1 && entityName !== diff.redo.table) { missing = true; } }); if ( ! missing && alreadyLoadedEntities.indexOf(diff.redo.value.name) === -1) { finish = false; loadedDiffs.push(diff); } }); if (finish) { return loadedDiffs; } else { return this._sortCreateEntitiesDiffsWithRelations(entitiesWithRelationsDiffs, loadedDiffs); } } private _compareRelation(rel1, rel2) { return rel1.entity != rel2.entity || rel2.field != rel2.field; } private _diffRelation(entity, dbField, field, diffs) { if (dbField.fk) { if (dbField.unique && entity.isRelation) { return true; } const relations = entity.getRelations(); let found = false; for (const relation of relations) { if (relation.field != dbField.name) { continue; } found = true; if (this._compareRelation(relation.reference, dbField.fk)) { // delete and create relation field.fk diffs.relations.push({ redo: { type: MigrationType.DELETE_RELATION, table: entity.name, value: relation, }, undo: { type: MigrationType.ADD_RELATION, table: entity.name, value: relation } }); diffs.relations.push({ redo: { type: MigrationType.ADD_RELATION, table: entity.name, value: { field: dbField.name, reference: dbField.fk }, }, undo: { type: MigrationType.DELETE_RELATION, table: entity.name, value: { field: dbField.name, reference: dbField.fk } } }); } else if (field) { const fieldDiff = this._compareField(dbField, field, entity); if ( fieldDiff ) { // the field has custom properties so add to fields or revert on db. dbField.read = field.read; dbField.write = field.write; diffs.fields.push({ redo: { type: MigrationType.CHANGE_FIELD, table: entity.name, name: dbField.name, value: this.app.database.interface.flattenField(dbField) }, undo: { type: MigrationType.CHANGE_FIELD, table: entity.name, name: field.name, value: fieldDiff[1] } }); } } } if ( ! found) { diffs.relations.push({ redo: { type: MigrationType.ADD_RELATION, table: entity.name, value: { field: dbField.name, reference: dbField.fk }, }, undo: { type: MigrationType.DELETE_RELATION, table: entity.name, value: { field: dbField.name, reference: dbField.fk } } }); } return true; } else if (field) { // if a field is a relation and a simple field in db if (field.isRelation) { diffs.relations.push({ redo: { type: MigrationType.DELETE_RELATION, table: entity.name, value: field.isRelation }, undo: { type: MigrationType.ADD_RELATION, table: entity.name, value: field.isRelation } }); diffs.fields.push({ redo: { type: MigrationType.ADD_FIELD, table: entity.name, value: field.toJson() }, undo: { type: MigrationType.DELETE_FIELD, table: entity.name, value: field.name } }); return true; } } return false; } private _diffEntity(entity, dbTable, diffs) { const dbFields = {}; const isRelationTable = []; for (const _dbField of dbTable) { if ( _dbField.fk && _dbField.unique) { isRelationTable.push({ as: _dbField.name, entity: _dbField.fk.entity }); } } if (isRelationTable.length == 2 && ( ! entity.isRelation || entity.getFields().length < 2)) { // add relations belongsToMany diffs.relations.push({ redo: { type: MigrationType.ADD_RELATION, table: isRelationTable[0].entity, value: { type: 'belongsToMany', through: entity.name, as: isRelationTable[0].as, reference: isRelationTable[1] } }, undo: { type: MigrationType.DELETE_RELATION, table: isRelationTable[0].entity, value: { type: 'belongsToMany', through: entity.name, as: isRelationTable[0].as, reference: isRelationTable[1] } } }); diffs.relations.push({ redo: { type: MigrationType.ADD_RELATION, table: isRelationTable[1].entity, value: { type: 'belongsToMany', through: entity.name, as: isRelationTable[1].as, reference: isRelationTable[0] } }, undo: { type: MigrationType.DELETE_RELATION, table: isRelationTable[1].entity, value: { type: 'belongsToMany', through: entity.name, as: isRelationTable[1].as, reference: isRelationTable[0] } } }); } for (const _dbField of dbTable) { const dbField = this.app.database.interface.columnToField(_dbField); dbField.fk = _dbField.fk; dbFields[dbField.name] = dbField; const field = entity.getField(dbField.name); if (isRelationTable.length != 2 && this._diffRelation(entity, dbField, field, diffs)) { continue; } if (field) { const fieldDiff = this._compareField(dbField, field, entity); if (fieldDiff[0] && ! fieldDiff[0].fk) { // update field to db properties dbField.read = field.read; dbField.write = field.write; diffs.fields.push({ redo: { type: MigrationType.CHANGE_FIELD, table: entity.name, name: dbField.name, value: fieldDiff[0] }, undo: { type: MigrationType.CHANGE_FIELD, table: entity.name, name: field.name, value: fieldDiff[1] } }); } } else if ( ! dbField.fk) { // add field that are in db diffs.fields.push({ redo: { type: MigrationType.ADD_FIELD, table: entity.name, value: this.app.database.interface.flattenField(dbField) }, undo: { type: MigrationType.DELETE_FIELD, table: entity.name, value: dbField.name } }); } } // delete fields that are not in db for (const field of entity.getFields()) { if ( ! dbFields[field.name] && ! field.isRelation) { diffs.fields.push({ redo: { type: MigrationType.DELETE_FIELD, table: entity.name, value: field.name }, undo: { type: MigrationType.ADD_FIELD, table: entity.name, value: field.toJson() } }); } } // delete relations that are not in db for (const relation of entity.getRelations()) { if ( ! dbFields[relation.field] && relation.type == 'belongsTo' && ! relation.implicit) { // delete relation diffs.relations.push({ redo: { type: MigrationType.DELETE_RELATION, table: entity.name, value: relation, }, undo: { type: MigrationType.ADD_RELATION, table: entity.name, value: relation } }); } } } private _diffEntities(entities, dbTables, diffs) { const tableCompared = []; for (const entity of entities) { tableCompared[entity.name] = entity; if (dbTables[entity.name]) { // compare fields this._diffEntity(entity, dbTables[entity.name], diffs); } else if (entity.isRelation) { let relation = { type: 'belongsToMany', through: entity.name, as: entity.isRelation[0].as, reference: { entity: entity.isRelation[1].entity, as: entity.isRelation[1].as } }; diffs.relations.push({ redo: { type: MigrationType.DELETE_RELATION, table: entity.isRelation[0].entity, value: relation }, undo: { type: MigrationType.ADD_RELATION, table: entity.isRelation[0].entity, value: relation } }); relation = { type: 'belongsToMany', through: entity.name, as: entity.isRelation[1].as, reference: { entity: entity.isRelation[0].entity, as: entity.isRelation[0].as } }; diffs.relations.push({ redo: { type: MigrationType.DELETE_RELATION, table: entity.isRelation[1].entity, value: relation }, undo: { type: MigrationType.ADD_RELATION, table: entity.isRelation[1].entity, value: relation } }); } else { diffs.entities.push({ redo: { type: MigrationType.DELETE_ENTITY, table: entity.name }, undo: { type: MigrationType.CREATE_ENTITY, table: entity.name, value: entity.toJson() } }); } } for (const table in dbTables) { // if table exists in db but not in entities if ( ! tableCompared[table]) { const fields = []; let relations = []; let isRelation = []; for (const field of dbTables[table]) { if ( field.fk ) { const relation: IRelation = { field: field.name, reference: field.fk }; if (field.unique) { if (field.unique === true) { relation.unique = true; } isRelation.push({ field: field.name, entity: field.fk.entity }); } relations.push(relation); if ((field.onDelete !== 'CASCADE') || (field.onUpdate !== 'CASCADE')) { if ( ! field.onDelete) { field.onDelete = 'NO ACTION'; } if ( ! field.onUpdate) { field.onUpdate = 'NO ACTION'; } fields.push(this.app.database.interface.flattenField(this.app.database.interface.columnToField(field))); } } else { fields.push(this.app.database.interface.flattenField(this.app.database.interface.columnToField(field))); } } if (isRelation.length != 2) { isRelation = undefined; } else { relations = undefined; let relation = { type: 'belongsToMany', through: table, as: isRelation[0].field, reference: { entity: isRelation[1].entity, as: isRelation[1].field } }; diffs.relations.push({ redo: { type: MigrationType.ADD_RELATION, table: isRelation[0].entity, value: relation }, undo: { type: MigrationType.DELETE_RELATION, table: isRelation[0].entity, value: relation } }); relation = { type: 'belongsToMany', through: table, as: isRelation[1].field, reference: { entity: isRelation[0].entity, as: isRelation[0].field } }; diffs.relations.push({ redo: { type: MigrationType.ADD_RELATION, table: isRelation[1].entity, value: relation }, undo: { type: MigrationType.DELETE_RELATION, table: isRelation[1].entity, value: relation } }); } const tableDesc = { name: table, fields: fields, queries: [], isRelation: isRelation, relations: relations }; diffs.entities.push({ redo: { type: MigrationType.CREATE_ENTITY, table: table, value: tableDesc }, undo: { type: MigrationType.DELETE_ENTITY, table: table } }); } } } private _diffMap(entities, dbTables) { const diffs = { entities: [], fields: [], relations: [], length: 0 }; this._diffEntities(entities, dbTables, diffs); diffs.length = diffs.entities.length + diffs.fields.length + diffs.relations.length; return diffs; } }
the_stack
import { getSynopsis } from 'parsing'; const LANGUAGE_ID = 'typescript'; describe('TypeScript Functions', () => { test('Function expression with no parameters', async () => { const code = `function hello(): void { console.log('Hello, world!'); }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [], returns: false }); }); test('Function expression with required parameters', async () => { const code = `function printKeyValue(key: string, value: string): void { console.log(key + ' : ' + value); }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); const params = [ { name: 'key', required: true, type: 'string', }, { name: 'value', required: true, type: 'string', }, ]; expect(synopsis).toEqual({ kind: 'function', params, returns: false }); }); test('Function expression with required parameters and custom types', async () => { const code = ` function nodeValues(a: Node, b: Node): void { console.log(a.value + ' ' + b.value); }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); const params = [ { name: 'a', required: true, type: 'Node', }, { name: 'b', required: true, type: 'Node', }, ]; expect(synopsis).toEqual({ kind: 'function', params, returns: false }); }); test('Function expression with optional parameters', async () => { const code = ` function multiply(a: number, b: number, c?: number): number { if (typeof c !== 'undefined') { return a * b * c; } return a * b; }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); const params = [ { name: 'a', required: true, type: 'number', }, { name: 'b', required: true, type: 'number', }, { name: 'c', required: false, type: 'number', }, ]; expect(synopsis).toEqual({ kind: 'function', params, returns: true }); }); test('Function expression with optional parameters and default value', async () => { const code = ` function multiply(a: number, b: number, c = 8): number { if (typeof c !== 'undefined') { return a * b * c; } return a * b; }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); const params = [ { name: 'a', required: true, type: 'number', }, { name: 'b', required: true, type: 'number', }, { name: 'c', required: false, defaultValue: '8', }, ]; expect(synopsis).toEqual({ kind: 'function', params, returns: true }); }); test('Function expression with export statement', async () => { const code = ` export function hello(): void { console.log('Hello, world!'); }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [], returns: false }); }); test('Function expression with return in another function statement', async () => { const code = ` function parentFunc(): void { function bar(): string { return 'hello'; } console.log('yo'); } `; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [], returns: false }); }); test('Arrow function with no return', async () => { const code = `const hello = (): void => { console.log('hello world'); }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [], returns: false }); }); test('Arrow function with no parameters', async () => { const code = `const hello = () => { console.log('hello world'); }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [], returns: false }); }); test('Arrow function with parameters', async () => { const code = `const printKeyValue = (key: string, value: string) => { console.log(key + ' : ' + value); }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); const params = [ { name: 'key', required: true, type: 'string' }, { name: 'value', required: true, type: 'string' }, ]; expect(synopsis).toEqual({ kind: 'function', params, returns: false }); }); test('Arrow function with return', async () => { const code = `const hello = () => { return false; }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [], returns: true }); }); test('Variable declared function', async () => { const code = `export const school = function(id: string) { return schools.doc(id); }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [{ name: 'id', required: true, type: 'string', }], returns: true }); }); test('Variable declared function with optional params and no return', async () => { const code = `export const school = function(id?: string) { let b = 'a'; }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [{ name: 'id', required: false, type: 'string', }], returns: false }); }); test('Function with rest params', async () => { const code = `function printKeyValue(key: string, ...values?: string[]): void { console.log(key + ' : ' + values); }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [ { name: 'key', required: true, type: 'string' }, { name: 'values', required: false, type: 'string[]' }, ], returns: false }); }); test('Function with array type param', async () => { const code = `function printKeyValue(key: string, values: string[]): void { console.log(key + ' : ' + values); }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [ { name: 'key', required: true, type: 'string' }, { name: 'values', required: true, type: 'string[]' }, ], returns: false }); }) // Remember to pass through the entire class/file to identify method test('Method with no parameters', async () => { const classCode = ` class Rectangle { constructor(height: number, width: number) { this.height = height; this.width = width; } // Getter get area() : number { return this.calcArea(); } // Method calcArea() : number { return this.height * this.width; } } `; const funcInClass = ` calcArea() : number { return this.height * this.width; }`; const synopsis = getSynopsis(funcInClass, LANGUAGE_ID, classCode); expect(synopsis).toEqual({ kind: 'function', params: [], returns: true }); }); test('Method with parameters', async () => { const classCode = ` class Rectangle { constructor(height: number, width: number) { this.height = height; this.width = width; } // Getter get area() : number { return this.calcArea(); } // Method calcArea() : number { return this.height * this.width; } areaMultiplied(multipliedBy : number) : number { return multipliedBy * calcArea(); } } `; const funcInClass = ` areaMultiplied(multipliedBy : number) : number { return multipliedBy * calcArea(); }`; const synopsis = getSynopsis(funcInClass, LANGUAGE_ID, classCode); const params = [ { name: 'multipliedBy', required: true, type: 'number' } ]; expect(synopsis).toEqual({ kind: 'function', params, returns: true }); }); test('Method with no return', async () => { const classCode = ` class Rectangle { constructor(height: number, width: number) { this.height = height; this.width = width; } // Getter get area() : number { return this.calcArea(); } // Method hello() { console.log('hello world'); } } `; const funcInClass = ` hello() { console.log('hello world'); }`; const synopsis = getSynopsis(funcInClass, LANGUAGE_ID, classCode); expect(synopsis).toEqual({ kind: 'function', params: [], returns: false }); }); test('Async method', async () => { const code = ` const mintlifyFiles = async (): Promise<MintedResults> => { const errors = []; const mints = []; return { mints, errors }; }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'function', params: [], returns: true }); }); }); describe('TypeScript Typedefs', () => { test('Properties with primative types', async () => { const code = ` type UndefinedElement = { name: string; line: number; character: number; }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); const properties = [ { name: 'name', type: 'string' }, { name: 'line', type: 'number' }, { name: 'character', type: 'number' } ]; expect(synopsis).toEqual({ kind: 'typedef', properties }); }); // e.g. name: NameType; test('Properties with complex types', async () => { const code = ` type LinkedListNode = { value: Node; next: LinkedListNode; }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); const properties = [ { name: 'value', type: 'Node' }, { name: 'next', type: 'LinkedListNode' } ]; expect(synopsis).toEqual({ kind: 'typedef', properties }); }); // TODO: add support for optional properties }); describe('TypeScript Classes', () => { test('Class with no extends', async () => { const code = ` class Rectangle { constructor(height: number, width: number) { this.height = height; this.width = width; } // Getter get area() : number { return this.calcArea(); } // Method hello() { console.log('hello world'); } }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'class' }); }); test('Class that extends another Class', async () => { const code = ` class Square extends Rectangle { constructor(height: number, width: number) { this.height = height; this.width = width; } // Getter get area() : number { return this.calcArea(); } // Method hello() { console.log('hello world'); } }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'class', extends: 'Rectangle' }); }); test('Class that implements another Class', async () => { const code = ` export default class JavaScript implements PL { async getSynopsis(tree: TreeNode, fileTree: TreeNode): Promise<Synopsis> { const functionSynopsis = getFunction(tree); if (functionSynopsis) return functionSynopsis; const methodSynopsis = getMethod(tree, fileTree); if (methodSynopsis) return methodSynopsis; const classSynopsis = getClass(tree); if (classSynopsis) return classSynopsis; return { kind: 'unspecified', } } }`; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'class', extends: 'PL' }); }); }); describe('TypeScript Unspecified', () => { test('One line of variable declaration', async () => { const code = "const a : string = 'a'"; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'unspecified' }); }); test('Two lines of code', async () => { const code = ` const a : string = 'a'; const b : string = 'b'; `; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'unspecified' }); }); test('One line of calling a function', async () => { const code = 'fun();'; const synopsis = getSynopsis(code, LANGUAGE_ID, code); expect(synopsis).toEqual({ kind: 'unspecified' }); }); });
the_stack
import {expect} from 'chai'; import {spawnSync} from 'child_process'; import fs from 'fs-extra'; import {after, before, describe, it} from 'mocha'; import path, {dirname} from 'path'; import {readPackageUpSync} from 'read-pkg-up'; import {fileURLToPath} from 'url'; import {getAppsScriptFileName, getLocalFileType} from '../src/files.js'; import {ERROR, LOG} from '../src/messages.js'; import {extractScriptId, URL} from '../src/urls.js'; import {getApiFileType, getDefaultProjectName, getWebApplicationURL, saveProject} from '../src/utils.js'; import {CLASP, CLASP_PATHS, CLASP_USAGE, IS_PR, SCRIPT_ID} from './constants.js'; import {backupSettings, cleanup, restoreSettings, setup} from './functions.js'; const __dirname = dirname(fileURLToPath(import.meta.url)); const manifest = readPackageUpSync({cwd: __dirname}); describe.skip('Test --help for each function', () => { const expectHelp = (command: string, expected: string) => { const result = spawnSync(CLASP, [command, '--help'], {encoding: 'utf8'}); expect(result.status).to.equal(0); expect(result.stdout).to.include(expected); }; it('should run --help', () => expectHelp('run', 'Run a function in your Apps Scripts project')); it('should logs --help', () => expectHelp('logs', 'Shows the StackDriver logs')); it('should login --help', () => expectHelp('login', 'Log in to script.google.com')); it('should logout --help', () => expectHelp('logout', 'Log out')); it('should create --help', () => expectHelp('create', 'Create a script')); it('should clone --help', () => expectHelp('clone', 'Clone a project')); it('should pull --help', () => expectHelp('pull', 'Fetch a remote project')); it('should push --help', () => expectHelp('push', 'Update the remote project')); it('should status --help', () => expectHelp('status', 'Lists files that will be pushed by clasp')); it('should open --help', () => expectHelp('open', 'Open a script')); it('should deployments --help', () => expectHelp('deployments', 'List deployment ids of a script')); it('should undeploy --help', () => expectHelp('undeploy', 'Undeploy a deployment of a project')); it('should versions --help', () => expectHelp('versions', 'List versions of a script')); it('should version --help', () => expectHelp('version', 'Creates an immutable version of the script')); it('should list --help', () => expectHelp('list', 'List App Scripts projects')); it('should apis --help', () => expectHelp('apis', 'List, enable, or disable APIs')); it('should help --help', () => expectHelp('help', 'Display help')); }); describe('Test extractScriptId function', () => { it('should return scriptId correctly', () => { expect(extractScriptId(SCRIPT_ID)).to.equal(SCRIPT_ID); expect(extractScriptId(URL.SCRIPT(SCRIPT_ID))).to.equal(SCRIPT_ID); }); }); describe('Test clasp pull function', () => { before(function () { if (IS_PR) { this.skip(); } setup(); }); it('should pull an existing project correctly', () => { const result = spawnSync(CLASP, ['pull'], {encoding: 'utf8'}); expect(result.stdout).to.contain('Cloned'); expect(result.stdout).to.contain('files.'); expect(result.status).to.equal(0); }); after(cleanup); }); describe('Test URL utils function', () => { it('should create Script URL correctly', () => { const expectedUrl = `https://script.google.com/d/${SCRIPT_ID}/edit`; expect(URL.SCRIPT(SCRIPT_ID)).to.equal(expectedUrl); }); it('should create Creds URL correctly', () => { const expectedURL = `https://console.developers.google.com/apis/credentials?project=${SCRIPT_ID}`; expect(URL.CREDS(SCRIPT_ID)).to.equal(expectedURL); }); }); describe('Test clasp version and versions function', () => { before(function () { if (IS_PR) { this.skip(); } setup(); }); let versionNumber = 0; it('should prompt for version description', () => { const result = spawnSync(CLASP, ['version'], {encoding: 'utf8'}); expect(result.stderr).to.equal(''); expect(result.stdout).to.contain(LOG.GIVE_DESCRIPTION); expect(result.status).to.equal(0); }); it('should create a new version correctly', () => { const result = spawnSync(CLASP, ['version', 'xxx'], {encoding: 'utf8'}); versionNumber = Number(result.stdout.slice(result.stdout.lastIndexOf(' '), -2)); expect(versionNumber).to.be.greaterThan(0); }); // TODO: this test needs to be updated it.skip('should list versions correctly', () => { const result = spawnSync(CLASP, ['versions'], {encoding: 'utf8'}); expect(result.stdout).to.contain('Versions'); if (versionNumber) expect(result.stdout).to.contain(`${versionNumber} - `); expect(result.status).to.equal(0); }); after(cleanup); }); describe('Test setting function', () => { before(function () { if (IS_PR) { this.skip(); } setup(); }); it('should return current setting value', () => { const result = spawnSync(CLASP, ['setting', 'scriptId'], {encoding: 'utf8'}); expect(result.stdout).to.equal(process.env.SCRIPT_ID); }); it('should update .clasp.json with provided value', () => { const result = spawnSync(CLASP, ['setting', 'scriptId', 'test'], {encoding: 'utf8'}); const fileContents = fs.readFileSync('.clasp.json', 'utf8'); expect(result.stdout).to.contain('Updated "scriptId":'); expect(result.stdout).to.contain('→ "test"'); expect(fileContents).to.contain('"test"'); }); it('should error on unknown keys', () => { // Test getting let result = spawnSync(CLASP, ['setting', 'foo'], {encoding: 'utf8'}); expect(result.status).to.equal(1); expect(result.stderr).to.contain(ERROR.UNKNOWN_KEY('foo')); // Test setting result = spawnSync(CLASP, ['setting', 'bar', 'foo'], {encoding: 'utf8'}); expect(result.status).to.equal(1); expect(result.stderr).to.contain(ERROR.UNKNOWN_KEY('bar')); }); after(cleanup); }); describe('Test getAppsScriptFileName function from files', () => { it('should return the basename correctly', () => { expect(getAppsScriptFileName('./', 'appsscript.json')).to.equal('appsscript'); expect(getAppsScriptFileName('', 'appsscript.json')).to.equal('appsscript'); expect(getAppsScriptFileName('./dist', './dist/appsscript.json')).to.equal('appsscript'); expect(getAppsScriptFileName('./dist', './dist/foo/Code.js')).to.equal('foo/Code'); }); }); describe('Test URL helper from utils', () => { it('should return the scriptURL correctly', () => { const url = URL.SCRIPT('abcdefghijklmnopqrstuvwxyz'); expect(url).to.equal('https://script.google.com/d/abcdefghijklmnopqrstuvwxyz/edit'); }); }); describe('Test getWebApplicationURL function from utils', () => { it('should return the scriptURL correctly', () => { const url = getWebApplicationURL({ entryPoints: [ { entryPointType: 'WEB_APP', webApp: { url: 'https://script.google.com/macros/s/abcdefghijklmnopqrstuvwxyz/exec', }, }, ], }); expect(url).to.equal('https://script.google.com/macros/s/abcdefghijklmnopqrstuvwxyz/exec'); }); }); describe('Test getDefaultProjectName function from utils', () => { it('should return the current directory name correctly', () => { expect(getDefaultProjectName()).to.equal('Clasp'); }); }); describe('Test getLocalFileType function from utils', () => { it('should return the lowercase file type correctly', () => { expect(getLocalFileType('SERVER_JS')).to.equal('js'); expect(getLocalFileType('GS')).to.equal('gs'); expect(getLocalFileType('JS')).to.equal('js'); expect(getLocalFileType('HTML')).to.equal('html'); }); it('should return the specified file extention if the file type is SERVER_JS', () => { expect(getLocalFileType('SERVER_JS', 'gs')).to.equal('gs'); expect(getLocalFileType('GS', 'js')).to.equal('gs'); expect(getLocalFileType('JS', 'gs')).to.equal('js'); expect(getLocalFileType('HTML', 'js')).to.equal('html'); }); }); describe('Test getAPIFileType function from utils', () => { it('should return the uppercase file type correctly', () => { expect(getApiFileType('file.GS')).to.equal('SERVER_JS'); expect(getApiFileType('file.JS')).to.equal('SERVER_JS'); expect(getApiFileType('file.js')).to.equal('SERVER_JS'); expect(getApiFileType('file.jsx')).to.equal('JSX'); expect(getApiFileType('file.js.html')).to.equal('HTML'); }); }); describe('Test saveProject function from utils', () => { it('should save the scriptId correctly', () => { spawnSync('rm', ['.clasp.json']); const isSaved = async () => { await saveProject({scriptId: '12345'}); const id = fs.readFileSync(path.join(__dirname, '/../.clasp.json'), 'utf8'); expect(id).to.equal('{"scriptId":"12345"}'); }; expect(isSaved).to.not.equal(null); }); it('should save the scriptId, rootDir correctly', () => { spawnSync('rm', ['.clasp.json']); const isSaved = async () => { await saveProject({scriptId: '12345', rootDir: './dist'}); const id = fs.readFileSync(path.join(__dirname, '/../.clasp.json'), 'utf8'); expect(id).to.equal('{"scriptId":"12345","rootDir":"./dist"}'); }; expect(isSaved).to.not.equal(null); }); }); describe('Test variations of clasp help', () => { const expectHelp = (variation: string) => { const result = spawnSync(CLASP, [variation], {encoding: 'utf8'}); expect(result.status).to.equal(0); expect(result.stdout).to.include(CLASP_USAGE); }; it('should show help for clasp help', () => expectHelp('help')); it('should show help for clasp --help', () => expectHelp('--help')); it('should show help for clasp -h', () => expectHelp('-h')); }); describe('Test variations of clasp --version', () => { const expectVersion = (variation: string) => { const result = spawnSync(CLASP, [variation], {encoding: 'utf8'}); expect(result.status).to.equal(0); expect(result.stdout).to.include(manifest ? manifest.packageJson.version : 'unknown'); }; it('should show version for clasp --version', () => expectVersion('--version')); it('should show version for clasp -v', () => expectVersion('-v')); }); describe('Test unknown functions', () => { it('should show version correctly', () => { const result = spawnSync(CLASP, ['unknown'], {encoding: 'utf8'}); expect(result.stderr).to.contain('Unknown command'); expect(result.status).to.equal(1); }); }); describe('Test all functions while logged out', () => { before(() => { backupSettings(); if (fs.existsSync(CLASP_PATHS.rcGlobal)) fs.removeSync(CLASP_PATHS.rcGlobal); if (fs.existsSync(CLASP_PATHS.rcLocal)) fs.removeSync(CLASP_PATHS.rcLocal); }); after(restoreSettings); const expectNoCredentials = (command: string) => { const result = spawnSync(CLASP, [command], {encoding: 'utf8'}); expect(result.status).to.equal(1); // expect(result.stderr).to.include(ERROR.NO_CREDENTIALS); }; it('should fail to list (no credentials)', () => expectNoCredentials('list')); it('should fail to clone (no credentials)', () => expectNoCredentials('clone')); it('should fail to push (no credentials)', () => expectNoCredentials('push')); it('should fail to deployments (no credentials)', () => expectNoCredentials('deployments')); it('should fail to deploy (no credentials)', () => expectNoCredentials('deploy')); it('should fail to version (no credentials)', () => expectNoCredentials('version')); it('should fail to versions (no credentials)', () => expectNoCredentials('versions')); // TODO: all test should have same order of checks // and should all return ERROR.NO_CREDENTIALS it('should fail to pull (no .clasp.json file)', () => { const result = spawnSync(CLASP, ['pull'], {encoding: 'utf8'}); expect(result.status).to.equal(1); // Should be ERROR.NO_CREDENTIALS // see: https://github.com/google/clasp/issues/278 expect(result.stderr).to.contain(ERROR.SETTINGS_DNE()); }); it('should fail to open (no .clasp.json file)', () => { const result = spawnSync(CLASP, ['open'], {encoding: 'utf8'}); expect(result.status).to.equal(1); // Should be ERROR.NO_CREDENTIALS // see: https://github.com/google/clasp/issues/278 expect(result.stderr).to.contain(ERROR.SETTINGS_DNE()); }); it('should fail to show logs (no .clasp.json file)', () => { const result = spawnSync(CLASP, ['logs'], {encoding: 'utf8'}); expect(result.status).to.equal(1); // Should be ERROR.NO_CREDENTIALS // see: https://github.com/google/clasp/issues/278 expect(result.stderr).to.contain(ERROR.SETTINGS_DNE()); }); });
the_stack
import * as React from 'react'; import * as d3 from 'd3'; import * as ReactDom from 'react-dom'; import * as Raven from 'raven-js'; import { Utils, PathRegion } from './widgets/Utils'; import LazyLoad from 'react-lazy-load'; import * as QueryString from 'query-string'; import DashboardInner from './DashboardInner'; Raven.config( 'https://7d69f10d11104fa9a644cff495db7d6f@sentry.io/197647' ).install(); const chroms = require('./samples/GRCh37.json'); // TODO(): Should be removed. export interface ContainerProps { uuid: string; posText: string[]; keyId: number; reference: string; subPathAnnotation: boolean; } export interface ContainerState { features?: any; featureId?: number; featureThreshold: number[]; filteredFeatures?: any; featureSelection: boolean[]; // Inter-chromosomal / Intra-chromosomal chroms?: any; chromsAll?: any; posInner: PathRegion[]; nodes: number[]; annotations: any[]; uuid: string; keyId: number; sequentialId: number; arrayMode: boolean; reference?: string; name?: string; staticFiles: any[]; subPathAnnotation: boolean; bigbedAnnotation: boolean; steps: number; } class DashBoard extends React.Component<ContainerProps, ContainerState> { constructor(props: ContainerProps) { super(props); this._posUpdate = this._posUpdate.bind(this); this._posUpdateWithFeature = this._posUpdateWithFeature.bind(this); this._posConcat = this._posConcat.bind(this); this._posConcatWithFeature = this._posConcatWithFeature.bind(this); this._posReplaceWithFeature = this._posReplaceWithFeature.bind(this); this._posReplace = this._posReplace.bind(this); this._nodesUpdate = this._nodesUpdate.bind(this); this._annotationsUpdate = this._annotationsUpdate.bind(this); this._annotationsClean = this._annotationsClean.bind(this); this._uuidUpdate = this._uuidUpdate.bind(this); this._keyIdUpdate = this._keyIdUpdate.bind(this); this._handleThreshold = this._handleThreshold.bind(this); this._handleSelection = this._handleSelection.bind(this); this._changeReference = this._changeReference.bind(this); this._arrayMode = this._arrayMode.bind(this); this._nameUpdate = this._nameUpdate.bind(this); this._stepsUpdate = this._stepsUpdate.bind(this); this._toggleSubPathAnnotation = this._toggleSubPathAnnotation.bind(this); this.state = { chroms: chroms, chromsAll: null, nodes: [], annotations: [], featureThreshold: [0, 100], featureSelection: [true, true], posInner: Utils.strsToRegion(props.posText), uuid: props.uuid === undefined ? '' : props.uuid, keyId: props.keyId, sequentialId: 0, reference: props.reference, // default is hg19. name: null, arrayMode: false, staticFiles: [], subPathAnnotation: props.subPathAnnotation, bigbedAnnotation: true, steps: 3 }; } componentDidMount() { this.fetchOverview(); } _arrayMode() { this.setState({ arrayMode: true }); } _changeReference(newReference: string) { this.setState({ reference: newReference }); if (this.state.chromsAll !== null && newReference !== null) { this.setState({ chroms: this.state.chromsAll[newReference] }); this._dumpPosition({ path: this.state.posInner, uuid: this.state.uuid, reference: newReference, layout: this.state.keyId, subPath: this.state.subPathAnnotation }); } } fetchOverview() { const _this = this; const uuidQuery = this.state.uuid !== '' ? '&uuid=' + this.state.uuid : ''; d3.csv('/api/v2/overview?source=features' + uuidQuery, function( error: any, data: any ) { if (error) { d3.csv('./samples/fusion-genes.csv', function(sampleData: any) { _this.setState({ features: sampleData, filteredFeatures: sampleData }); }); } else { const sortedData = data.sort(function(a: any, b: any) { return d3.descending(+a.priority, +b.priority); }); _this.setState({ features: sortedData, filteredFeatures: sortedData }); } }); fetch('/api/v2/overview?source=chromosomes') .then(function(response: Response) { return response.json(); }) .then(function(json2: any) { _this.setState({ chromsAll: json2, chroms: json2[_this.state.reference] }); }) .catch(function(err: any) { // handle error console.error(err); _this.setState({ chroms: chroms }); }); if (this.props.uuid === undefined || this.props.uuid.length === 0) { fetch('/api/v2/overview?source=metadata') .then(function(response: Response) { return response.json(); }) .then(function(json: any) { _this.setState({ reference: json.ref_id, name: json.name, staticFiles: json.static_files }); }) .catch(function(err: any) { // handle error console.error(err); _this.setState({ name: 'demo' }); }); } } _posUpdate(path: PathRegion[], updatedIndex: number = 0) { this._dumpPosition({ path: path, reference: this.state.reference, uuid: this.state.uuid, layout: this.state.keyId, subPath: this.state.subPathAnnotation }); if (updatedIndex === 0) { this.setState({ sequentialId: this.state.sequentialId + 1 }); } this.setState({ posInner: path }); } _posUpdateWithFeature( path: PathRegion[], featureId: number, updatedIndex?: number ) { this.setState({ featureId: featureId }); this._posUpdate(path, updatedIndex); } _posConcat(path: PathRegion[]) { if (!this.state.arrayMode) { this._posUpdate(path); } if (path.length !== 1 || !path[0].compare(this.state.posInner[0])) { var result = path.concat(this.state.posInner); this._posUpdate(result); } } _posConcatWithFeature(path: PathRegion[], featureId: number) { this.setState({ featureId: featureId }); this._posConcat(path); } _posReplace(path: PathRegion[]) { if (!this.state.arrayMode) { this._posUpdate(path); } var result = this.state.posInner; if (!result[0].isLocked) { result[0] = path[0]; this._posUpdate(result); } } _posReplaceWithFeature(path: PathRegion[], featureId: number) { this.setState({ featureId: featureId }); this._posReplace(path); } _nodesUpdate(nodes: number[]) { this.setState({ nodes: nodes }); } _annotationsUpdate(annotations: any[]) { this.setState({ annotations: this.state.annotations.concat(annotations) }); } _annotationsClean() { this.setState({ annotations: [] }); } _nameUpdate(name: string) { this.setState({ name: name }); } _stepsUpdate(steps: number) { this.setState({ steps: steps }); } _dumpPosition(item: { path: PathRegion[]; uuid: string; reference: string; layout: number; subPath: boolean; }) { window.parent.location.hash = '#' + QueryString.stringify({ path: item.path.map(a => a.toStringWithNames()), uuid: item.uuid, reference: item.reference, layout: item.layout, annotations: item.subPath }); } _keyIdUpdate(keyId: number) { // console.log(keyId); this._dumpPosition({ path: this.state.posInner, uuid: this.state.uuid, reference: this.state.reference, layout: keyId, subPath: this.state.subPathAnnotation }); this.setState({ keyId: keyId }); } _uuidUpdate(uuid: string) { this.setState({ uuid: uuid }); this._dumpPosition({ path: this.state.posInner, uuid: uuid, reference: this.state.reference, layout: this.state.keyId, subPath: this.state.subPathAnnotation }); this.fetchOverview(); } _handleThreshold(event: any) { const featureSelection = this.state.featureSelection; const currentFeatures = this.state.features .filter(function(d2: any) { return d2.source_id === d2.target_id || featureSelection[0]; }) .filter(function(d2: any) { return d2.source_id !== d2.target_id || featureSelection[1]; }); this.setState({ featureThreshold: event, filteredFeatures: currentFeatures.slice( (1 - event[1] / 100) * currentFeatures.length, (1 - event[0] / 100) * currentFeatures.length ) }); } _handleSelection(selectId: number) { var select = this.state.featureSelection; select[selectId] = !select[selectId]; const currentFeatures = this.state.features .filter(function(d2: any) { return select[0] || d2.source_id === d2.target_id; }) .filter(function(d2: any) { return select[1] || d2.source_id !== d2.target_id; }); this.setState({ featureSelection: select, filteredFeatures: currentFeatures.slice( (1 - this.state.featureThreshold[1] / 100) * currentFeatures.length, (1 - this.state.featureThreshold[0] / 100) * currentFeatures.length ) }); } _toggleSubPathAnnotation() { this.setState({ subPathAnnotation: !this.state.subPathAnnotation }); this._dumpPosition({ path: this.state.posInner, uuid: this.state.uuid, reference: this.state.reference, layout: this.state.keyId, subPath: !this.state.subPathAnnotation }); } render() { return ( <DashboardInner {...this.state} width={window.innerWidth} margin={{ top: 20, right: 20, bottom: 20, left: 10 }} _uuidUpdate={this._uuidUpdate} _posUpdate={this._posUpdate} _posUpdateWithFeature={this._posUpdateWithFeature} _posReplace={this._posReplace} _posReplaceWithFeature={this._posReplaceWithFeature} _posConcatWithFeature={this._posConcatWithFeature} _handleThreshold={this._handleThreshold} _nodesUpdate={this._nodesUpdate} _annotationsUpdate={this._annotationsUpdate} _annotationsClean={this._annotationsClean} _keyIdUpdate={this._keyIdUpdate} _handleSelection={this._handleSelection} _arrayMode={this._arrayMode} _changeReference={this._changeReference} _nameUpdate={this._nameUpdate} _toggleSubPathAnnotation={this._toggleSubPathAnnotation} /> ); } } export default DashBoard;
the_stack
import { Injectable, Logger } from '@nestjs/common'; import { Order } from 'common/constants'; import { PageMetaDto } from 'common/dtos'; import { CreateFailedException, TransactionNotFoundException, } from 'exceptions'; import { BillEntity } from 'modules/bill/entities'; import { BillRepository } from 'modules/bill/repositories'; import { BillService } from 'modules/bill/services'; import { ConfirmTransactionDto, CreateTransactionDto, TransactionsPageDto, TransactionsPageOptionsDto, } from 'modules/transaction/dtos'; import { TransactionEntity } from 'modules/transaction/entities'; import { TransactionRepository } from 'modules/transaction/repositories'; import { UserEntity } from 'modules/user/entities'; import { UtilsService, ValidatorService } from 'utils/services'; import { UpdateResult } from 'typeorm'; import { MailerService } from '@nestjs-modules/mailer'; import { ConfigService } from '@nestjs/config'; import { UserConfigService } from 'modules/user/services'; import { Transactional } from 'typeorm-transactional-cls-hooked'; import { Readable } from 'stream'; import * as pdf from 'html-pdf'; import { LanguageService } from 'modules/language/services'; import * as fs from 'fs'; import handlebars from 'handlebars'; import { format } from 'date-fns'; @Injectable() export class TransactionService { private readonly _logger = new Logger(TransactionService.name); private readonly _configService = new ConfigService(); private readonly _emailSubject = { en: 'Payment authorization', de: 'Zahlungsermächtigung', pl: 'Autoryzacja płatności', }; constructor( private readonly _transactionRepository: TransactionRepository, private readonly _billRepository: BillRepository, private readonly _billService: BillService, private readonly _validatorService: ValidatorService, private readonly _mailerService: MailerService, private readonly _userConfigService: UserConfigService, private readonly _languageService: LanguageService, ) {} public async getTransactions( user: UserEntity, pageOptionsDto: TransactionsPageOptionsDto, ): Promise<TransactionsPageDto | undefined> { const queryBuilder = this._transactionRepository.createQueryBuilder( 'transactions', ); const [transactions, transactionsCount] = await queryBuilder .addSelect([ 'recipientUser.uuid', 'recipientUser.firstName', 'recipientUser.lastName', 'recipientUser.avatar', 'senderUser.uuid', 'senderUser.firstName', 'senderUser.lastName', 'senderUser.avatar', ]) .leftJoinAndSelect('transactions.senderBill', 'senderBill') .leftJoinAndSelect('transactions.recipientBill', 'recipientBill') .leftJoin('recipientBill.user', 'recipientUser') .leftJoinAndSelect('recipientBill.currency', 'recipientBillCurrency') .leftJoin('senderBill.user', 'senderUser') .leftJoinAndSelect('senderBill.currency', 'senderBillCurrency') .where(':user IN ("senderUser"."id", "recipientUser"."id")') .andWhere('transactions.authorizationStatus = true') .orderBy('transactions.updatedAt', pageOptionsDto.order) .addOrderBy('transactions.id', pageOptionsDto.order) .setParameter('user', user.id) .skip(pageOptionsDto.skip) .take(pageOptionsDto.take) .getManyAndCount(); const pageMetaDto = new PageMetaDto({ pageOptionsDto, itemCount: transactionsCount, }); return new TransactionsPageDto(transactions.toDtos(), pageMetaDto); } public async getTransaction( options: Partial<{ uuid: string; authorizationKey: string; recipient: UserEntity; sender: UserEntity; user: UserEntity; authorizationStatus: boolean; }>, ): Promise<TransactionEntity | undefined> { const queryBuilder = this._transactionRepository.createQueryBuilder( 'transaction', ); queryBuilder.orderBy('transaction.id', Order.DESC); if (options.recipient) { queryBuilder .leftJoin('transaction.recipientBill', 'recipientBill') .leftJoin('recipientBill.user', 'recipientUser') .andWhere('recipientUser.id = :user', { user: options.recipient.id }); } if (options.sender) { queryBuilder .leftJoin('transaction.senderBill', 'senderBill') .leftJoin('senderBill.user', 'senderUser') .andWhere('senderUser.id = :user', { user: options.sender.id }); } if (options.uuid) { queryBuilder.andWhere('transaction.uuid = :uuid', { uuid: options.uuid, }); } if (options.authorizationStatus) { queryBuilder.andWhere( 'transaction.authorizationStatus = :authorizationStatus', { authorizationStatus: options.authorizationStatus }, ); } if (options.authorizationKey) { queryBuilder.andWhere( 'transaction.authorizationKey = :authorizationKey', { authorizationKey: options.authorizationKey }, ); } if (options.user) { queryBuilder .leftJoinAndSelect('transaction.senderBill', 'senderBill') .leftJoinAndSelect('senderBill.user', 'senderUser') .leftJoinAndSelect('transaction.recipientBill', 'recipientBill') .leftJoinAndSelect('recipientBill.user', 'recipientUser') .leftJoinAndSelect('senderBill.currency', 'senderBillCurrency') .andWhere('(senderUser.id = :user OR recipientUser.id = :user)', { user: options.user.id, }); } return queryBuilder.getOne(); } public async createTransaction( user: UserEntity, createTransactionDto: CreateTransactionDto, authorizationKey?: string, ): Promise<TransactionEntity> { const [recipientBill, senderBill] = await Promise.all([ this._billService.findBill(createTransactionDto.recipientBill), this._billService.findBill(createTransactionDto.senderBill, user), ]); this._validatorService.isCorrectRecipient( senderBill?.id, recipientBill?.id, ); this._validatorService.isCorrectAmountMoney( user.userAuth.role, senderBill.amountMoney, createTransactionDto.amountMoney, ); const createdTransaction = { recipientBill, senderBill, authorizationKey: authorizationKey ?? this._generateAuthrorizationKey(), amountMoney: createTransactionDto.amountMoney, transferTitle: createTransactionDto.transferTitle, }; const transaction = this._transactionRepository.create(createdTransaction); const isHigherRole = this._validatorService.isHigherRole( user.userAuth.role, ); if (!isHigherRole) { await this.sendEmailWithAuthorizationKey( createdTransaction, createTransactionDto, senderBill, recipientBill, ); } try { return this._transactionRepository.save(transaction); } catch (error) { throw new CreateFailedException(error); } } private async sendEmailWithAuthorizationKey( createdTransaction, createTransactionDto: CreateTransactionDto, senderBill: BillEntity, recipientBill: BillEntity, ): Promise<void> { try { const email = await this._mailerService.sendMail({ to: senderBill.user.email, from: this._configService.get('EMAIL_ADDRESS'), subject: this._emailSubject[createTransactionDto.locale], template: __dirname + `/../templates/transaction.template.${createTransactionDto.locale}.hbs`, context: { amountMoney: createTransactionDto.amountMoney.toLocaleString( undefined, { minimumFractionDigits: 2 }, ), currencyName: senderBill.currency.name, recipient: `${recipientBill.user.firstName} ${recipientBill.user.lastName}`, authorizationKey: createdTransaction.authorizationKey, }, }); this._logger.log( `An email with the authorization code has been sent to: ${email.accepted}`, ); } catch (error) { this._logger.error( `An email with a confirmation code has not been sent. Theoretical recipient: ${senderBill.user.email}`, ); } } @Transactional() public async confirmTransaction( user: UserEntity, confirmTransactionDto: ConfirmTransactionDto, ): Promise<void> { const createdTransaction = await this._findTransactionByAuthorizationKey( confirmTransactionDto.authorizationKey, user, ); if (!createdTransaction) { throw new TransactionNotFoundException(); } const { amountMoney: senderAmountMoney, senderBill: [{ amountMoney: transactionAmountMoney }], senderBill: [transaction], } = createdTransaction; this._validatorService.isCorrectAmountMoney( user.userAuth.role, senderAmountMoney, transactionAmountMoney, ); try { await this._updateTransactionAuthorizationStatus(transaction); await this._userConfigService.setNotification( transaction.recipientBill.user.userConfig, ); } catch (error) { throw new CreateFailedException(error); } } /** * NOTE: This query is created by the bill repository because it must include the current amount of the sender's money as well. * This method is called when the user confirms the transfer. * Attaching the current balance of the sender's account is necessary to validation before confirming the transfer. */ private async _findTransactionByAuthorizationKey( authorizationKey: string, sender: UserEntity, ): Promise<BillEntity | undefined> { const queryBuilder = this._billRepository.createQueryBuilder('bill'); queryBuilder .addSelect( (subQuery) => subQuery .select( `COALESCE( TRUNC( SUM( CASE WHEN "transactions"."recipient_bill_id" = "bill"."id" THEN 1 / CASE WHEN "senderBillCurrency"."id" = "recipientBillCurrency"."id" THEN 1 ELSE CASE WHEN "recipientBillCurrency"."base" THEN "senderBillCurrency"."current_exchange_rate" :: decimal ELSE "senderBillCurrency"."current_exchange_rate" :: decimal * "recipientBillCurrency"."current_exchange_rate" :: decimal END END ELSE -1 END * "transactions"."amount_money"), 2), '0.00') :: numeric`, ) .from(TransactionEntity, 'transactions') .leftJoin('transactions.recipientBill', 'recipientBill') .leftJoin('transactions.senderBill', 'senderBill') .leftJoin('recipientBill.currency', 'recipientBillCurrency') .leftJoin('senderBill.currency', 'senderBillCurrency') .where( `"bill"."id" IN ("transactions"."sender_bill_id", "transactions"."recipient_bill_id")`, ) .andWhere('transactions.authorization_status = true'), 'bill_amount_money', ) .leftJoinAndSelect('bill.senderBill', 'transaction') .leftJoinAndSelect('transaction.recipientBill', 'recipientBill') .leftJoinAndSelect('recipientBill.user', 'recipientUser') .leftJoinAndSelect('recipientUser.userConfig', 'userConfig') .leftJoinAndSelect('bill.currency', 'currency') .where('transaction.authorizationKey = :authorizationKey', { authorizationKey, }) .andWhere('bill.user = :user', { user: sender.id, }) .andWhere('transaction.authorizationStatus = false') .orderBy('transaction.id', Order.DESC); return queryBuilder.getOne(); } private async _updateTransactionAuthorizationStatus( transaction: TransactionEntity, ): Promise<UpdateResult> { const queryBuilder = this._transactionRepository.createQueryBuilder( 'transaction', ); return queryBuilder .update() .set({ authorizationStatus: true }) .where('id = :id', { id: transaction.id }) .execute(); } private _generateAuthrorizationKey() { return UtilsService.generateRandomString(5); } public async getConfirmationDocumentFile( user: UserEntity, uuid: string, locale: string, ): Promise<string> { const transaction = await this.getTransaction({ user, uuid, authorizationStatus: true, }); if (!transaction) { throw new TransactionNotFoundException(); } const variables = { date: format(transaction.updatedAt, 'dd.MM.yyyy, HH:mm'), senderName: `${transaction.senderBill.user.firstName} ${transaction.senderBill.user.lastName}`, recipientName: `${transaction.recipientBill.user.firstName} ${transaction.recipientBill.user.lastName}`, amountMoney: transaction.amountMoney, currencyName: transaction.senderBill.currency.name, }; const content = await this._getConfirmationFileContent(locale); return this._getCompiledContent(content, variables); } public getReadableStream(buffer: Buffer): Readable { const stream = new Readable(); stream.push(buffer); stream.push(null); return stream; } public async htmlToPdfBuffer(html: string): Promise<Buffer> { return new Promise((resolve, reject) => { pdf.create(html).toBuffer((err, buffer) => { if (err) { reject(err); } else { resolve(buffer); } }); }); } private async _getConfirmationFileContent(locale: string): Promise<string> { try { const data = await fs.promises.readFile( __dirname + `/../templates/confirmation.template.${locale}.hbs`, 'utf8', ); return data; } catch (error) { throw new Error(error); } } /** * TODO: This method is re-declared somewhere and fails the DRY principle. * Transfer it to a separate service */ private _getCompiledContent(content: string, variables): any { const template = handlebars.compile(content.toString()); return template(variables); } }
the_stack
import { Transaction } from '@/js/Transaction' import Big from 'big.js' export interface TransactionsState { tx: Transaction | null txRes: TransactionQuery recentTxRes: TransactionQuery assetTxRes: TransactionQuery addressTxRes: TransactionQuery blockchainTxRes: TransactionQuery evmTx: EVMTransactionResponse | null } /* ========================================== UTXO Transactions (API) ========================================== */ export interface TransactionQueryResponse { startTime: string endTime: string next: string transactions: TransactionResponse[] } export interface TransactionQuery { startTime: string endTime: string next: string transactions: Transaction[] } export interface TransactionResponse { id: string chainID: string type: string inputs: InputResponse[] outputs: OutputResponse[] memo: string // base64 inputTotals: InputTotal outputTotals: OutputTotal reusedAddressTotals: string | null timestamp: string // https://docs.avax.network/learn/platform-overview/transaction-fees#fee-schedule /* Multi-sig txFee scenarios A. 1-of-2 ms UTXO => UTXO (equal) both parties paid the fee. UTXO (equal) B. 1-of-2 ms UTXO => UTXO (equal) person that owned the non-multisig output paid more of a % of the fee. non-ms UTXO UTXO (equal) C. 1-of-2 ms UTXO => UTXO person that ended up w/ out output paid the fee because the other person was reimbursed. non-ms UTXO */ txFee: number genesis: boolean /* REWARD PATTERNS - tx type: delgator/validator only 0. KEYPAIR controls UTXOs 1. KEYPAIR issues ADD_VALIDATOR/ADD_DELEGATOR TX - validator = adds node to validator (nodeId, start, end, stakeAmount, addressID (rewards destination), fee they charge delegators) - delegator = delegates to validator - once the tx is put into block and accepted: - Input UTXOs - UTXOs for staking transfer custody to the protocol (they disappear) - Output UTXOs - none for staking (output.stake boolean) - change UTXOs only - you will become a validator/delegator at the startTime 2. endTime arrives 3. PROTOCOL automatically issues REMOVE_VALIDATOR / REMOVE_DELEGATOR TX - removes the validator/delegator from validator set - once the tx is put into block and accepted: - Input UTXOs - none - Output UTXO - UTXOs mirroring the ADD_VALIDATOR/ADD_DELGATOR Input UTXOs are created - get your stake back - no UTXO appears in tx for reward... - no inputs or outputs for this tx. the output UTXOs are created out of thin air 4. PROTOCOL creates a commit or abort block - if uptime is good, then you receive the reward P-chain blocks contain 1 tx or 0 tx - 1 tx = commit block - contains reward UTXO - 0 tx = abort block - no reward 5. KEYPAIR spends reward UTXO (it appears in Ortelius) - confirm the reward tx (points at the ADD_* tx) is issued on the x-chain - possibly issued on p-chain and pvm_export to x-chain to be spent rewarded | rewardedTime false | null = default, someone staked false | number = reward tx was rejected for some reason (double decision block = 2tx in one block) true | number = locktime up and reward submitted */ rewarded: boolean // false by default, true when a reward is committed. rewardedTime: string | null epoch: number vertexId: string validatorNodeID: string validatorStart: number validatorEnd: number // p-chain event. you can tie transactions together (double decision block) txBlockId: string // p-chain hash (might be useful to lookup) /* TODOS: exception booleans - genesis - rewarded - frozen - stakable - stakeLockTime - stakableLockedOutput (wraps transfer) - stakeLockTime - vesting avax. we needed a way for ppl to stake but otherwise not spend it for any other purpose - lockTime */ } /* ========================================== EVM Transactions ========================================== */ export interface EVMTransactionQueryResponse { Transactions: EVMTransactionResponse[] startTime: string // N/A - internal query logic for Ortelius DB endTime: string // N/A } /* All definitions from https://consensys.github.io/EthOn/EthOn_spec.html ValueTx - Just moves Ether from one account to another. CallTx - A type of transaction that is directed towards a contract account and calls a method in the contract's code. CreateTx - A type of transaction that results in creation of a new contract account. */ export interface EVMTransactionResponse { hash: string // The Keccak 256-bit hash of the transaction createdAt: string // time of ingestion by Ortelius, 99& of the time this value should be the same as blockHeader.timestamp (sec granularity). different by ms // SENDER fromAddr: string /* A tx always originates from an external account that is controlled by an external actor by means of a private key */ nonce: number // A scalar value equal to the number of transactions sent by the sender. // PAYLOAD value: string /* A scalar value equal to the number of Wei to be transferred to the Message call's recipient. In the case of contract creation it is the initial balance of the contract account, paid by the sending account. */ input: string // An unlimited size byte array specifying the input data of the call. gasPrice: string /* A scalar value equal to the number of Wei to be paid per unit of gas for all computation costs incurred as a result of the execution of this transaction. */ gasLimit: number /* A scalar value equal to the maximum amount of gas that should be used in executing this transaction. This is paid up-front, before any computation is done and may not be increased later. If used with contract messages it represents the fraction of the original transaction gas limit still available for execution of the contract message. After all resulting computations are done, excess gas is returned to the sender of the original transaction. */ // RECIPIENT toAddr: string // Relates a message with the account it is sent to. recipient: string // duplicate to above // THE BLOCK CONTAINING THIS TX block: string // A scalar value equal to the number of ancestor blocks. The genesis block has a number of zero. blockGasUsed: number // A scalar value equal to the total gas used by all transactions in this block. blockGasLimit: number /* Will stay constant for foreseeable future A scalar value equal to the current limit of gas expenditure per block. Its purpose is to keep block propagation and processing time low, thereby allowing for a sufficiently decentralized network. */ blockHash: string // The Keccak 256-bit hash of the block's header, in its entierty. blockNonce: number /* Not Applicable In PoW, this 64 bit hash, when combined with the mix-hash, proves that a sufficient amount of computation has been carried out on this block. */ /* EXECUTION TRACES The downside of contract execution is that it is very hard to say what a transaction actually did. A transaction receipt does contain a status code to check whether execution succeeded or not, but there’s no way to see what data was modified, nor what external contracts were invoked. In order to introspect a transaction, we need to trace its execution. Example: https://explorerapi.avax.network/v2/ctransactions?hash=0xbe5960deded935d9cbea94ea9e944699db668646dba9d20bcfda921f979bfd87 */ traces: TraceResponse[] /* TX SIGNATURE - used to determine the sender of the transaction - V, R and S correspond to the signature of the transaction */ r: string // byte array of length 32 s: string // byte array of length 32 v: string /* specifies the sign and finiteness of the curve point. Since EIP-155 it is used to realize a replay attack protection. It is calculated in the following way: txV = CHAIN_ID * 2 + 36 */ } /* EXECUTION TRACES This response is based on the Blockscout tracer: It allows Geth's "debug_traceTransaction" to mimic the output of Parity's "trace_replayTransaction". Objects represent ContractMsg - A contract message is passed between a contract account and any other account (external or contract). It is the result of an execution chain originally triggered by an external eccount. curl -X POST --data '{ "jsonrpc": "2.0", "method": "debug_traceTransaction","params": ["0x00000217bc17e7e3187efae9248523f4fe2bc90e029e3ba13ddd8ff69607c705", {"disableStack": true, "disableMemory": true, "disableStorage": true}],"id": 1}' -H 'content-type:application/json;' https://api.avax.network/ext/bc/C/rpc */ export interface TraceResponse { callType: string /* execution context "" - when it's a CREATE CALL - executes in scope of contract DELEGATECALL - executes in scope of caller contract. value inherited from scope during call sequencing STATICCALL - by definition static calls transfer no value */ type: string /* one of the two values CALL and CREATE CREATE - a subtype of a contract message that results in creation of a new contract account CALL - CallContractMsg - a contract message that calls a function in another contract. ??? SelfdestructContractMsg - a contract message that deletes the originating contract and refunds its balance to the receiver of the message.*/ // SENDER from: string // Relates a message to the account it originates from. // PAYLOAD input: string // An unlimited size byte array specifying the input data of the call. output?: string // return value value: string // amount to be transferred in wei // RECEIVER to: string /* Relates a message with the account it is sent to. refunds - Relates a selfdestruct contract message to the contract account it sends its refund balance to. creates - Relates a create transaction to the contract account it creates. */ gasUsed: string /* The amount of gas that was used for processing a single message regardless of which type of message it may be. */ gas: string // ??? could be msgGasLimit - A scalar value equal to the maximum amount of gas that should be used in executing this transaction. This is paid up-front, before any computation is done and may not be increased later. If used with contract messages it represents the fraction of the original transaction gas limit still available for execution of the contract message. After all resulting computations are done, excess gas is returned to the sender of the original transaction. traceAddress?: number[] createdContractAddressHash?: string createdContractCode?: string // ERROR EXAMPLE: https://explorerapi.avax-test.network/v2/ctransactions?hash=0x638a35c57a7a1545a8a6eb4ea6a3355c2d4e64657f8921fd3ff922aff86436b1 error?: string // "execution reverted", revertReason?: string // keccak-256 encoding "0x08c379a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000009542d4f4145582d30310000000000000000000000000000000000000000000000", revertReasonUnpacked?: string // "T-OAEX-01" children?: TraceResponse[] } /* ========================================== Transactions (JS) ========================================== */ export interface ITransaction extends Omit<TransactionResponse, 'inputs' | 'outputs'> { inputs: Input[] outputs: Output[] } /* ========================================== UTXOs (API) ========================================== */ export interface InputResponse { credentials: CredentialResponse output: OutputResponse } export interface OutputResponse { id: string transactionID: string // INPUTS - the prev tx that generated this input UTXO. OUTPUTS - this tx redeemingTransactionID: string // INPUTS - this tx. OUTPUTS - "" if unspent, or the txID that spent this UTXO outputIndex: number // INPUTS - reference the UTXO index from the prev tx that generated this UTXO. chainID: string assetID: string timestamp: string // time of ingestion by Ortelius amount: string // 0 in the case of NFTs outputType: number groupID: number // RELEVANT TO P-CHAIN stake: boolean // if true, UTXO was in the staking output set (ins/outs/staking) stakeableout: boolean // if true, UTXO is/was subject to vesting. connected to stakeLocktime stakeLocktime: number // if before stakeLockTime, UTXO is vesting (locked), and can only used as input UTXO to stake in addValidator/addDelegator tx rewardUtxo: boolean // if true, this UTXO is the validation/delegation reward // RELEVANT TO X-CHAIN genesisutxo: boolean frozen: boolean // TODO: Apricot locktime: number threshold: number payload: string | null // NFTs // RELEVANT TO P-CHAIN & X-CHAIN addresses: string[] // notice the output UTXO address is blank. an exception for c-chain is handled in the transaction class // RELEVANT TO C-CHAIN caddresses: string[] block: string // https://cchain.explorer.avax.network/blocks/33726/transactions - broken block/tx nonce: number /* X > SHARED DB > P/C 1. EXPORT = move UTXO from X to SHARED DB (https://explorerapi.avax.network/v2/transactions/wQwXqfXKyoHSMCP4QVrfZgU9V7cBShJGgkZmGvkLQbHTRjhAS) 2. ATOMIC_IMPORT = move UTXO from SHARED DB to P/C (https://explorerapi.avax.network/v2/transactions/9TMCg4ZRfa91NHJE7LgMFK6UHKP83uopHBFL3zyDc55acfMUF) - normally, we'd see an output UTXO, but in lieu of output UTXO, we see a C-address - inputs.addresses = [avax...] - outputs.address = null - outputs.caddress = [0x..] - if you have hex C-addresses, then the output represented as atomic import address, you will see the actual block that wrapped that atomic import/export tx P/C > SHARED DB > X 1. ATOMIC_EXPORT = move UTXO from P/C to SHARED DB 2. IMPORT = move UTXO from SHARED DB to X note: "chainID": "2q9e4r6Mu3U68nU1fYjgbR6JvwrRx36CohpAX5UQxse55x1Q5", is messed up */ } export interface CredentialResponse { signature: string public_key: string address: string } /* ========================================== UTXOs (JS) ========================================== */ export interface Input { credentials: CredentialResponse output: Output } export interface Output extends Omit<OutputResponse, 'timestamp' | 'amount'> { timestamp: Date amount: Big } export interface InputTotal { [key: string]: number } export interface OutputTotal { [key: string]: number } export interface OutputValuesDict { [key: string]: { symbol: string amount: Big denomination: number isNFT: boolean } } export interface OutValuesDenominated { [assetId: string]: { amount: string symbol: string assetID: string isNFT: boolean } } export enum OutputType { TRANSFERABLE = '', NFT_TRANSFERABLE = 'NFT', MINT = 'Mint', NFT_MINT = 'NFT Minting Rights', ATOMIC_EXPORT_TX = 'Atomic Export', ATOMIC_IMPORT_TX = 'Atomic Import', } export enum BlockType { PROPOSAL = 'Proposal', ABORT = 'Abort', COMMIT = 'Commit', STANDARD = 'Standard', ATOMIC = 'Atomic', }
the_stack
import http = require("http"); import https = require("https"); import assert = require("assert"); import path = require("path") import os = require("os") import fs = require('fs'); import sinon = require("sinon"); import events = require("events"); import child_process = require("child_process"); import nock = require("nock"); import AppInsights = require("../applicationinsights"); import Sender = require("../Library/Sender"); import Traceparent = require("../Library/Traceparent"); import { EventEmitter } from "events"; import { CorrelationContextManager } from "../AutoCollection/CorrelationContextManager"; import Constants = require("../Declarations/Constants"); import Contracts = require("../Declarations/Contracts"); import HeartBeat = require("../AutoCollection/HeartBeat"); import TelemetryClient = require("../Library/TelemetryClient"); import Context = require("../Library/Context"); import Util = require("../Library/Util"); /** * A fake response class that passes by default */ class fakeResponse { private callbacks: { [event: string]: (data?: any) => void } = Object.create(null); public setEncoding(): void { }; public statusCode: number = 200; private _responseData: any; constructor(private passImmediately: boolean = true, responseData?: any) { this._responseData = responseData ? responseData : "data"; } public on(event: string, callback: () => void) { if (!this.callbacks[event]) { this.callbacks[event] = callback; } else { var lastCallback = this.callbacks[event]; this.callbacks[event] = () => { callback(); lastCallback(); }; } if (event == "end" && this.passImmediately) { this.pass(true); } } public emit(eventName: string, ...args: any[]): boolean { return true; } public addListener(eventName: string, listener: () => void): void { this.on(eventName, listener); } public removeListener(eventName: string, listener: () => void) { } public pass(test = false): void { this.callbacks["data"] ? this.callbacks["data"](this._responseData) : null; this.callbacks["end"] ? this.callbacks["end"]() : null; this.callbacks["finish"] ? this.callbacks["finish"]() : null; } public end = this.pass; public once = this.on; } /** * A fake request class that fails by default */ class fakeRequest { private callbacks: { [event: string]: Function } = Object.create(null); public write(): void { } public headers: { [id: string]: string } = {}; public agent = { protocol: 'http' }; private _responseData: any; constructor(private failImmediatly: boolean = true, public url: string = undefined, responseData?: any) { this._responseData = responseData; } public on(event: string, callback: Function) { this.callbacks[event] = callback; if (event === "error" && this.failImmediatly) { setImmediate(() => this.fail()); } } public emit(eventName: string, ...args: any[]): boolean { return true; } public addListener(eventName: string, listener: Function): void { this.on(eventName, listener); } public removeListener(eventName: string, listener?: Function) { } public fail(): void { this.callbacks["error"] ? this.callbacks["error"]() : null; } public end(): void { this.callbacks["end"] ? this.callbacks["end"](new fakeResponse(true, this._responseData)) : null; } } /** * A fake http server */ class fakeHttpServer extends events.EventEmitter { public setCallback(callback: any) { this.on("request", callback); } public listen(port: any, host?: any, backlog?: any, callback?: any) { this.emit("listening"); } public emitRequest(url: string) { var request = new fakeRequest(false, url); var response = new fakeResponse(false); this.emit("request", request, response); request.end(); } } /** * A fake https server class that doesn't require ssl certs */ class fakeHttpsServer extends events.EventEmitter { public setCallback(callback: any) { this.on("request", callback); } public listen(port: any, host?: any, backlog?: any, callback?: any) { this.emit("listening"); } public emitRequest(url: string) { var request = new fakeRequest(false, url); var response = new fakeResponse(false); this.emit("request", request, response); request.end(); response.pass(); } } describe("EndToEnd", () => { var sandbox: sinon.SinonSandbox; var originalEnv = {}; let interceptor: nock.Interceptor; var breezeResponse: Contracts.BreezeResponse = { itemsAccepted: 1, itemsReceived: 1, errors: [] }; before(() => { sandbox = sinon.sandbox.create(); var newEnv = <{ [id: string]: string }>{}; Util.tlsRestrictedAgent = new https.Agent(); newEnv["APPLICATION_INSIGHTS_NO_STATSBEAT"] = "true"; originalEnv = process.env; process.env = newEnv; interceptor = nock(Constants.DEFAULT_BREEZE_ENDPOINT) .post("/v2.1/track", (body: string) => { return true; }); nock.disableNetConnect(); }); after(() => { process.env = originalEnv; nock.cleanAll(); nock.enableNetConnect(); }); describe("Basic usage", () => { let nockScope: nock.Scope; before(() => { nockScope = interceptor.reply(200, breezeResponse).persist(); }); afterEach(() => { // Dispose the default app insights client and auto collectors so that they can be reconfigured // cleanly for each test sandbox.restore(); CorrelationContextManager.reset(); AppInsights.dispose(); }); it("should send telemetry", (done) => { const expectedTelemetryData: AppInsights.Contracts.AvailabilityTelemetry = { duration: 100, id: "id1", message: "message1", success: true, name: "name1", runLocation: "east us" }; var client = new AppInsights.TelemetryClient("iKey"); client.trackEvent({ name: "test event" }); client.trackException({ exception: new Error("test error") }); client.trackMetric({ name: "test metric", value: 3 }); client.trackTrace({ message: "test trace" }); client.trackAvailability(expectedTelemetryData); client.flush({ callback: (response) => { assert.ok(response, "response should not be empty"); assert.ok(response !== "no data to send", "response should have data"); done(); } }); }); it("should collect http request telemetry", (done) => { var fakeHttpSrv = new fakeHttpServer(); sandbox.stub(http, 'createServer', (callback: (req: http.ServerRequest, res: http.ServerResponse) => void) => { fakeHttpSrv.setCallback(callback); return fakeHttpSrv; }); AppInsights .setup("ikey") .setAutoCollectRequests(true) .start(); var track = sandbox.stub(AppInsights.defaultClient, 'track'); http.createServer((req, res) => { assert.equal(track.callCount, 0); res.end(); assert.equal(track.callCount, 1); done(); }); fakeHttpSrv.emitRequest("http://localhost:0/test"); }); it("should collect https request telemetry", (done) => { var fakeHttpSrv = new fakeHttpServer(); sandbox.stub(https, 'createServer', (options: any, callback: (req: http.ServerRequest, res: http.ServerResponse) => void) => { fakeHttpSrv.setCallback(callback); return fakeHttpSrv; }); AppInsights .setup("ikey") .setAutoCollectRequests(true) .start(); var track = sandbox.stub(AppInsights.defaultClient, 'track'); https.createServer(null, (req: http.ServerRequest, res: http.ServerResponse) => { assert.equal(track.callCount, 0); res.end(); assert.equal(track.callCount, 1); done(); }); fakeHttpSrv.emitRequest("http://localhost:0/test"); }); it("should collect http dependency telemetry", (done) => { var eventEmitter = new EventEmitter(); (<any>eventEmitter).method = "GET"; sandbox.stub(http, 'request', (url: string, c: Function) => { process.nextTick(c); return eventEmitter; }); AppInsights .setup("ikey") .setAutoCollectDependencies(true) .start(); var track = sandbox.stub(AppInsights.defaultClient, 'track'); http.request(<any>'http://test.com', (c) => { assert.equal(track.callCount, 0); eventEmitter.emit("response", {}); assert.equal(track.callCount, 1); done(); }); }); it("should collect https dependency telemetry", (done) => { sandbox.restore(); var eventEmitter = new EventEmitter(); (<any>eventEmitter).method = "GET"; sandbox.stub(https, 'request', (url: string, c: Function) => { process.nextTick(c); return eventEmitter; }); AppInsights .setup("ikey") .setAutoCollectDependencies(true) .start(); var track = sandbox.stub(AppInsights.defaultClient, 'track'); https.request(<any>'https://test.com', (c) => { assert.equal(track.callCount, 0); eventEmitter.emit("response", {}); assert.equal(track.callCount, 1); done(); }); }); }); describe("W3C mode", () => { let nockScope: nock.Scope; before(() => { nockScope = interceptor.reply(200, breezeResponse).persist(); }); afterEach(() => { // Dispose the default app insights client and auto collectors so that they can be reconfigured // cleanly for each test sandbox.restore(); CorrelationContextManager.reset(); AppInsights.dispose(); }); it("should pass along traceparent/tracestate header if present in current operation", (done) => { var eventEmitter = new EventEmitter(); (eventEmitter as any).headers = {}; (eventEmitter as any)["getHeader"] = function (name: string) { return this.headers[name]; }; (eventEmitter as any)["setHeader"] = function (name: string, value: string) { this.headers[name] = value; }; (<any>eventEmitter).method = "GET"; sandbox.stub(https, 'request', (url: string, c: Function) => { process.nextTick(c); return eventEmitter; }); AppInsights .setup("ikey") .setAutoCollectDependencies(true) .start(); sandbox.stub(CorrelationContextManager, "getCurrentContext", () => ({ operation: { traceparent: new Traceparent("00-5e84aff3af474588a42dcbf3bd1db95f-1fc066fb77fa43a3-00"), tracestate: "sometracestate" }, customProperties: { serializeToHeader: (): null => null } })); https.request(<any>'https://test.com', (c) => { eventEmitter.emit("response", {}); assert.ok((eventEmitter as any).headers["request-id"].match(/^\|[0-z]{32}\.[0-z]{16}\./g)); assert.ok((eventEmitter as any).headers.traceparent.match(/^00-5e84aff3af474588a42dcbf3bd1db95f-[0-z]{16}-00$/)); assert.notEqual((eventEmitter as any).headers.traceparent, "00-5e84aff3af474588a42dcbf3bd1db95f-1fc066fb77fa43a3-00"); assert.equal((eventEmitter as any).headers.tracestate, "sometracestate"); AppInsights.defaultClient.flush(); done(); }); }); it("should create and pass a traceparent header if w3c is enabled", (done) => { var eventEmitter = new EventEmitter(); (eventEmitter as any).headers = {}; (eventEmitter as any)["getHeader"] = function (name: string) { return this.headers[name]; }; (eventEmitter as any)["setHeader"] = function (name: string, value: string) { this.headers[name] = value; }; (<any>eventEmitter).method = "GET"; sandbox.stub(https, 'request', (url: string, c: Function) => { process.nextTick(c); return eventEmitter; }); var CorrelationIdManager = require("../Library/CorrelationIdManager"); AppInsights .setup("ikey") .setAutoCollectDependencies(true) .start(); CorrelationIdManager.w3cEnabled = true; sandbox.stub(CorrelationContextManager, "getCurrentContext", () => ({ operation: { }, customProperties: { serializeToHeader: (): null => null } })); https.request(<any>'https://test.com', (c) => { eventEmitter.emit("response", {}); assert.ok((eventEmitter as any).headers.traceparent.match(/^00-[0-z]{32}-[0-z]{16}-[0-9a-f]{2}/g), "traceparent header is passed, 00-W3C-W3C-00"); assert.ok((eventEmitter as any).headers["request-id"].match(/^\|[0-z]{32}\.[0-z]{16}\./g), "back compat header is also passed, |W3C.W3C." + (eventEmitter as any).headers["request-id"]); CorrelationIdManager.w3cEnabled = false; AppInsights.defaultClient.flush(); done(); }); }); }); describe("Disk retry mode", () => { var CorrelationIdManager = require("../Library/CorrelationIdManager"); var writeFile: sinon.SinonStub; var writeFileSync: sinon.SinonStub; var readFile: sinon.SinonStub; var lstat: sinon.SinonStub; var mkdir: sinon.SinonStub; var exists: sinon.SinonStub; var existsSync: sinon.SinonStub; var readdir: sinon.SinonStub; var readdirSync: sinon.SinonStub; var stat: sinon.SinonStub; var statSync: sinon.SinonStub; var mkdirSync: sinon.SinonStub; var spawn: sinon.SinonStub; var spawnSync: sinon.SinonStub; let nockScope: nock.Scope; beforeEach(() => { nockScope = interceptor.reply(503, {}); AppInsights.defaultClient = undefined; sandbox.stub(CorrelationIdManager, 'queryCorrelationId'); // TODO: Fix method of stubbing requests to allow CID to be part of E2E tests writeFile = sandbox.stub(fs, 'writeFile'); writeFileSync = sandbox.stub(fs, 'writeFileSync'); exists = sandbox.stub(fs, 'exists').yields(true); existsSync = sandbox.stub(fs, 'existsSync').returns(true); readdir = sandbox.stub(fs, 'readdir').yields(null, ['1.ai.json']); readdirSync = sandbox.stub(fs, 'readdirSync').returns(['1.ai.json']); stat = sandbox.stub(fs, 'stat').yields(null, { isFile: () => true, size: 8000 }); statSync = sandbox.stub(fs, 'statSync').returns({ isFile: () => true, size: 8000 }); lstat = sandbox.stub(fs, 'lstat').yields(null, { isDirectory: () => true }); mkdir = sandbox.stub(fs, 'mkdir').yields(null); mkdirSync = sandbox.stub(fs, 'mkdirSync').returns(null); readFile = sandbox.stub(fs, 'readFile').yields(null, ''); spawn = sandbox.stub(child_process, 'spawn').returns({ on: (type: string, cb: any) => { if (type === 'close') { cb(0); } }, stdout: { on: (type: string, cb: any) => { if (type === 'data') { cb('stdoutmock'); } } } }); if (child_process.spawnSync) { spawnSync = sandbox.stub(child_process, 'spawnSync').returns({ status: 0, stdout: 'stdoutmock' }); } }); afterEach(() => { sandbox.restore(); AppInsights.dispose(); }); it("disabled by default for new clients", (done) => { var client = new AppInsights.TelemetryClient("key"); client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { assert(writeFile.callCount === 0); done(); }); } }); }); it("enabled by default for default client", (done) => { AppInsights.setup("key").start(); var client = AppInsights.defaultClient; client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { assert.equal(writeFile.callCount, 1); assert.equal(spawn.callCount, os.type() === "Windows_NT" ? 2 : 0); done(); }); } }); }); it("stores data to disk when enabled", (done) => { var client = new AppInsights.TelemetryClient("key"); client.channel.setUseDiskRetryCaching(true); client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { assert(writeFile.callCount === 1); assert.equal( path.dirname(writeFile.firstCall.args[0]), path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + "key")); assert.equal(writeFile.firstCall.args[2].mode, 0o600, "File must not have weak permissions"); assert.equal(spawn.callCount, 0); // Should always be 0 because of caching after first call to ICACLS done(); }); } }); }); it("uses WindowsIdentity to get the identity for ICACLS", (done) => { var client = new AppInsights.TelemetryClient("uniquekey"); client.channel.setUseDiskRetryCaching(true); var origICACLS = (<any>client.channel._sender.constructor).USE_ICACLS; (<any>client.channel._sender.constructor).USE_ICACLS = true; // Simulate ICACLS environment even on *nix // Clear ICACLS caches for test purposes (<any>client.channel._sender.constructor).ACL_IDENTITY = null; (<any>client.channel._sender.constructor).ACLED_DIRECTORIES = {}; client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { assert.equal(writeFile.callCount, 1); assert.equal(spawn.callCount, 2); // First external call should be to powershell to query WindowsIdentity assert(spawn.firstCall.args[0].indexOf('powershell.exe')); assert.equal(spawn.firstCall.args[1][0], "-Command"); assert.equal(spawn.firstCall.args[1][1], "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"); assert.equal((<any>client.channel._sender.constructor).ACL_IDENTITY, 'stdoutmock'); // Next call should be to ICACLS (with the acquired identity) assert(spawn.lastCall.args[0].indexOf('icacls.exe')); assert.equal(spawn.lastCall.args[1][3], "/grant"); assert.equal(spawn.lastCall.args[1][4], "stdoutmock:(OI)(CI)F"); (<any>client.channel._sender.constructor).USE_ICACLS = origICACLS; done(); }); } }); }); it("refuses to store data if ACL identity fails", (done) => { spawn.restore(); var tempSpawn = sandbox.stub(child_process, 'spawn').returns({ on: (type: string, cb: any) => { if (type == 'close') { cb(2000); // return non-zero status code } }, stdout: { on: (type: string, cb: any) => { return; // do nothing } } }); var client = new AppInsights.TelemetryClient("uniquekey"); client.channel.setUseDiskRetryCaching(true); var origICACLS = (<any>client.channel._sender.constructor).USE_ICACLS; (<any>client.channel._sender.constructor).USE_ICACLS = true; // Simulate ICACLS environment even on *nix // Set ICACLS caches for test purposes (<any>client.channel._sender.constructor).ACL_IDENTITY = null; (<any>client.channel._sender.constructor).ACLED_DIRECTORIES = {}; client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { assert(writeFile.callCount === 0); assert.equal(tempSpawn.callCount, 1); (<any>client.channel._sender.constructor).USE_ICACLS = origICACLS; done(); }); } }); }); it("refuses to query for ACL identity twice", (done) => { spawn.restore(); var tempSpawn = sandbox.stub(child_process, 'spawn').returns({ on: (type: string, cb: any) => { if (type == 'close') { cb(2000); // return non-zero status code } }, stdout: { on: (type: string, cb: any) => { return; // do nothing } } }); var client = new AppInsights.TelemetryClient("uniquekey"); client.channel.setUseDiskRetryCaching(true); var origICACLS = (<any>client.channel._sender.constructor).USE_ICACLS; (<any>client.channel._sender.constructor).USE_ICACLS = true; // Simulate ICACLS environment even on *nix // Set ICACLS caches for test purposes (<any>client.channel._sender.constructor).ACL_IDENTITY = null; (<any>client.channel._sender.constructor).ACLED_DIRECTORIES = {}; client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setTimeout(() => { assert(writeFile.callCount === 0); assert.equal(tempSpawn.callCount, 1); client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { // The call counts shouldnt have changed assert(writeFile.callCount === 0); assert.equal(tempSpawn.callCount, 1); (<any>client.channel._sender.constructor).USE_ICACLS = origICACLS; done(); }); } }); }, 100); } }); }); it("refuses to query for ACL identity twice (process never returned)", (done) => { spawn.restore(); var tempSpawn = sandbox.stub(child_process, 'spawn').returns({ on: (type: string, cb: any) => { return; // do nothing }, stdout: { on: (type: string, cb: any) => { return; // do nothing } } }); var client = new AppInsights.TelemetryClient("uniquekey"); client.channel.setUseDiskRetryCaching(true); var origICACLS = (<any>client.channel._sender.constructor).USE_ICACLS; (<any>client.channel._sender.constructor).USE_ICACLS = true; // Simulate ICACLS environment even on *nix // Set ICACLS caches for test purposes (<any>client.channel._sender.constructor).ACL_IDENTITY = null; (<any>client.channel._sender.constructor).ACLED_DIRECTORIES = {}; client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { assert(writeFile.callCount === 0); assert.equal(tempSpawn.callCount, 1); client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { // The call counts shouldnt have changed assert(writeFile.callCount === 0); assert.equal(tempSpawn.callCount, 1); (<any>client.channel._sender.constructor).USE_ICACLS = origICACLS; done(); }); } }); }); } }); }); it("refuses to store data if ICACLS fails", (done) => { spawn.restore(); var tempSpawn = sandbox.stub(child_process, 'spawn').returns({ on: (type: string, cb: any) => { if (type == 'close') { cb(2000); // return non-zero status code } } }); var client = new AppInsights.TelemetryClient("uniquekey"); client.channel.setUseDiskRetryCaching(true); var origICACLS = (<any>client.channel._sender.constructor).USE_ICACLS; (<any>client.channel._sender.constructor).USE_ICACLS = true; // Simulate ICACLS environment even on *nix // Set ICACLS caches for test purposes (<any>client.channel._sender.constructor).ACL_IDENTITY = 'testidentity'; // Don't use spawn for identity (<any>client.channel._sender.constructor).ACLED_DIRECTORIES = {}; client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { assert(writeFile.callCount === 0); assert.equal(tempSpawn.callCount, 1); (<any>client.channel._sender.constructor).USE_ICACLS = origICACLS; done(); }); } }); }); it("creates directory when nonexistent", (done) => { lstat.restore(); sandbox.stub(fs, 'lstat').yields({ code: "ENOENT" }, null); var client = new AppInsights.TelemetryClient("key"); client.channel.setUseDiskRetryCaching(true); client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { setTimeout(() => { assert.equal(mkdir.callCount, 1); assert.equal(mkdir.firstCall.args[0], path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + "key")); assert.equal(writeFile.callCount, 1); assert.equal( path.dirname(writeFile.firstCall.args[0]), path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + "key")); assert.equal(writeFile.firstCall.args[2].mode, 0o600, "File must not have weak permissions"); done(); }, 100); } }); }); it("does not store data when limit is below directory size", (done) => { var client = new AppInsights.TelemetryClient("key"); client.channel.setUseDiskRetryCaching(true, null, 10); // 10 bytes is less than synthetic directory size (see file size in stat mock) client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { assert(writeFile.callCount === 0); done(); }); } }); }); it("checks for files when connection is back online", (done) => { var client = new AppInsights.TelemetryClient("key"); client.channel.setUseDiskRetryCaching(true, 0); client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // yield for the caching behavior setImmediate(() => { assert.equal(writeFile.callCount, 1); interceptor.reply(200, breezeResponse); client.trackEvent({ name: "test event" }); client.flush({ callback: (response: any) => { // wait until sdk looks for offline files setTimeout(() => { assert.equal(readdir.callCount, 2); assert.equal(readFile.callCount, 1); assert.equal( path.dirname(readFile.firstCall.args[0]), path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + "key")); done(); }, 100); } }); }); } }); }); it("cache payload synchronously when process crashes", () => { var client = new AppInsights.TelemetryClient("key2"); client.channel.setUseDiskRetryCaching(true); client.trackEvent({ name: "test event" }); client.channel.triggerSend(true); assert(existsSync.callCount === 1); assert(writeFileSync.callCount === 1); assert.equal(spawnSync.callCount, os.type() === "Windows_NT" ? 1 : 0); // This is implicitly testing caching of ACL identity (otherwise call count would be 2 like it is the non-sync time) assert.equal( path.dirname(writeFileSync.firstCall.args[0]), path.join(os.tmpdir(), Sender.TEMPDIR_PREFIX + "key2")); assert.equal(writeFileSync.firstCall.args[2].mode, 0o600, "File must not have weak permissions"); }); it("use WindowsIdentity to get ACL identity when process crashes (ICACLS)", () => { var client = new AppInsights.TelemetryClient("key22"); client.channel.setUseDiskRetryCaching(true); var origICACLS = (<any>client.channel._sender.constructor).USE_ICACLS; (<any>client.channel._sender.constructor).USE_ICACLS = true; // Simulate ICACLS environment even on *nix // Set ICACLS caches for test purposes (<any>client.channel._sender.constructor).ACL_IDENTITY = null; (<any>client.channel._sender.constructor).ACLED_DIRECTORIES = {}; client.trackEvent({ name: "test event" }); client.channel.triggerSend(true); // First external call should be to powershell to query WindowsIdentity assert(spawnSync.firstCall.args[0].indexOf('powershell.exe')); assert.equal(spawnSync.firstCall.args[1][0], "-Command"); assert.equal(spawnSync.firstCall.args[1][1], "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name"); assert.equal((<any>client.channel._sender.constructor).ACL_IDENTITY, 'stdoutmock'); // Next call should be to ICACLS (with the acquired identity) assert(spawnSync.lastCall.args[0].indexOf('icacls.exe')); assert.equal(spawnSync.lastCall.args[1][3], "/grant"); assert.equal(spawnSync.lastCall.args[1][4], "stdoutmock:(OI)(CI)F"); (<any>client.channel._sender.constructor).USE_ICACLS = origICACLS; }); it("refuses to cache payload when process crashes if ICACLS fails", () => { spawnSync.restore(); var tempSpawnSync = sandbox.stub(child_process, 'spawnSync').returns({ status: 2000 }); var client = new AppInsights.TelemetryClient("key3"); // avoid icacls cache by making key unique client.channel.setUseDiskRetryCaching(true); var origICACLS = (<any>client.channel._sender.constructor).USE_ICACLS; (<any>client.channel._sender.constructor).USE_ICACLS = true; // Simulate ICACLS environment even on *nix client.trackEvent({ name: "test event" }); client.channel.triggerSend(true); assert(existsSync.callCount === 1); assert(writeFileSync.callCount === 0); if (child_process.spawnSync) { assert.equal(tempSpawnSync.callCount, 1); (<any>client.channel._sender.constructor).USE_ICACLS = origICACLS; } }); }); describe("Heartbeat metrics for VM", () => { afterEach(() => { sandbox.restore(); }); it("should collect correct VM information from JSON response", (done) => { // set up stub const vmDataJSON = `{ "vmId": "1", "subscriptionId": "2", "osType": "Windows_NT" }`; var stub: sinon.SinonStub = sandbox.stub(http, "request", (options: any, callback: any) => { var req = new fakeRequest(false, "http://169.254.169.254", vmDataJSON); req.on("end", callback); return req; }); // set up sdk const client = new TelemetryClient("key"); const heartbeat: HeartBeat = new HeartBeat(client); heartbeat.enable(true, client.config); HeartBeat.INSTANCE.enable(true, client.config); const trackMetricStub = sandbox.stub(heartbeat["_client"], "trackMetric"); heartbeat["trackHeartBeat"](client.config, () => { assert.equal(trackMetricStub.callCount, 1, "should call trackMetric for the VM heartbeat metric"); assert.equal(trackMetricStub.args[0][0].name, "HeartBeat", "should use correct name for heartbeat metric"); assert.equal(trackMetricStub.args[0][0].value, 0, "value should be 0"); const keys = Object.keys(trackMetricStub.args[0][0].properties); assert.equal(keys.length, 5, "should have 4 kv pairs added when resource type is VM"); assert.equal(keys[0], "sdk", "sdk should be added as a key"); assert.equal(keys[1], "osType", "osType should be added as a key"); assert.equal(keys[2], "azInst_vmId", "azInst_vmId should be added as a key"); assert.equal(keys[3], "azInst_subscriptionId", "azInst_subscriptionId should be added as a key"); assert.equal(keys[4], "azInst_osType", "azInst_osType should be added as a key"); const properties = trackMetricStub.args[0][0].properties; assert.equal(properties["sdk"], Context.sdkVersion, "sdk version should be read from Context"); assert.equal(properties["osType"], os.type(), "osType should be read from os library"); assert.equal(properties["azInst_vmId"], "1", "azInst_vmId should be read from response"); assert.equal(properties["azInst_subscriptionId"], "2", "azInst_subscriptionId should be read from response"); assert.equal(properties["azInst_osType"], "Windows_NT", "azInst_osType should be read from response"); done(); }); }); it("should only send name and value properties for heartbeat metric when get VM request fails", (done) => { // set up stub var stub: sinon.SinonStub = sandbox.stub(http, "request", (options: any, callback: any) => { var req = new fakeRequest(true, "http://169.254.169.254"); return req; }); // set up sdk const client = new TelemetryClient("key"); const heartbeat: HeartBeat = new HeartBeat(client); heartbeat.enable(true, client.config); HeartBeat.INSTANCE.enable(true, client.config); const trackMetricStub = sandbox.stub(heartbeat["_client"], "trackMetric"); heartbeat["trackHeartBeat"](client.config, () => { assert.equal(trackMetricStub.callCount, 1, "should call trackMetric as heartbeat metric"); assert.equal(trackMetricStub.args[0][0].name, "HeartBeat", "should use correct name for heartbeat metric"); assert.equal(trackMetricStub.args[0][0].value, 0, "value should be 0"); const keys = Object.keys(trackMetricStub.args[0][0].properties); assert.equal(keys.length, 2, "should have 2 kv pairs added when resource type is not web app, not function app, not VM"); assert.equal(keys[0], "sdk", "sdk should be added as a key"); assert.equal(keys[1], "osType", "osType should be added as a key"); const properties = trackMetricStub.args[0][0].properties; assert.equal(properties["sdk"], Context.sdkVersion, "sdk version should be read from Context"); assert.equal(properties["osType"], os.type(), "osType should be read from os library"); done(); }); }); }); });
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class Kafka extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: Kafka.Types.ClientConfiguration) config: Config & Kafka.Types.ClientConfiguration; /** * Associates one or more Scram Secrets with an Amazon MSK cluster. */ batchAssociateScramSecret(params: Kafka.Types.BatchAssociateScramSecretRequest, callback?: (err: AWSError, data: Kafka.Types.BatchAssociateScramSecretResponse) => void): Request<Kafka.Types.BatchAssociateScramSecretResponse, AWSError>; /** * Associates one or more Scram Secrets with an Amazon MSK cluster. */ batchAssociateScramSecret(callback?: (err: AWSError, data: Kafka.Types.BatchAssociateScramSecretResponse) => void): Request<Kafka.Types.BatchAssociateScramSecretResponse, AWSError>; /** * Creates a new MSK cluster. */ createCluster(params: Kafka.Types.CreateClusterRequest, callback?: (err: AWSError, data: Kafka.Types.CreateClusterResponse) => void): Request<Kafka.Types.CreateClusterResponse, AWSError>; /** * Creates a new MSK cluster. */ createCluster(callback?: (err: AWSError, data: Kafka.Types.CreateClusterResponse) => void): Request<Kafka.Types.CreateClusterResponse, AWSError>; /** * Creates a new MSK configuration. */ createConfiguration(params: Kafka.Types.CreateConfigurationRequest, callback?: (err: AWSError, data: Kafka.Types.CreateConfigurationResponse) => void): Request<Kafka.Types.CreateConfigurationResponse, AWSError>; /** * Creates a new MSK configuration. */ createConfiguration(callback?: (err: AWSError, data: Kafka.Types.CreateConfigurationResponse) => void): Request<Kafka.Types.CreateConfigurationResponse, AWSError>; /** * Deletes the MSK cluster specified by the Amazon Resource Name (ARN) in the request. */ deleteCluster(params: Kafka.Types.DeleteClusterRequest, callback?: (err: AWSError, data: Kafka.Types.DeleteClusterResponse) => void): Request<Kafka.Types.DeleteClusterResponse, AWSError>; /** * Deletes the MSK cluster specified by the Amazon Resource Name (ARN) in the request. */ deleteCluster(callback?: (err: AWSError, data: Kafka.Types.DeleteClusterResponse) => void): Request<Kafka.Types.DeleteClusterResponse, AWSError>; /** * Deletes an MSK Configuration. */ deleteConfiguration(params: Kafka.Types.DeleteConfigurationRequest, callback?: (err: AWSError, data: Kafka.Types.DeleteConfigurationResponse) => void): Request<Kafka.Types.DeleteConfigurationResponse, AWSError>; /** * Deletes an MSK Configuration. */ deleteConfiguration(callback?: (err: AWSError, data: Kafka.Types.DeleteConfigurationResponse) => void): Request<Kafka.Types.DeleteConfigurationResponse, AWSError>; /** * Returns a description of the MSK cluster whose Amazon Resource Name (ARN) is specified in the request. */ describeCluster(params: Kafka.Types.DescribeClusterRequest, callback?: (err: AWSError, data: Kafka.Types.DescribeClusterResponse) => void): Request<Kafka.Types.DescribeClusterResponse, AWSError>; /** * Returns a description of the MSK cluster whose Amazon Resource Name (ARN) is specified in the request. */ describeCluster(callback?: (err: AWSError, data: Kafka.Types.DescribeClusterResponse) => void): Request<Kafka.Types.DescribeClusterResponse, AWSError>; /** * Returns a description of the cluster operation specified by the ARN. */ describeClusterOperation(params: Kafka.Types.DescribeClusterOperationRequest, callback?: (err: AWSError, data: Kafka.Types.DescribeClusterOperationResponse) => void): Request<Kafka.Types.DescribeClusterOperationResponse, AWSError>; /** * Returns a description of the cluster operation specified by the ARN. */ describeClusterOperation(callback?: (err: AWSError, data: Kafka.Types.DescribeClusterOperationResponse) => void): Request<Kafka.Types.DescribeClusterOperationResponse, AWSError>; /** * Returns a description of this MSK configuration. */ describeConfiguration(params: Kafka.Types.DescribeConfigurationRequest, callback?: (err: AWSError, data: Kafka.Types.DescribeConfigurationResponse) => void): Request<Kafka.Types.DescribeConfigurationResponse, AWSError>; /** * Returns a description of this MSK configuration. */ describeConfiguration(callback?: (err: AWSError, data: Kafka.Types.DescribeConfigurationResponse) => void): Request<Kafka.Types.DescribeConfigurationResponse, AWSError>; /** * Returns a description of this revision of the configuration. */ describeConfigurationRevision(params: Kafka.Types.DescribeConfigurationRevisionRequest, callback?: (err: AWSError, data: Kafka.Types.DescribeConfigurationRevisionResponse) => void): Request<Kafka.Types.DescribeConfigurationRevisionResponse, AWSError>; /** * Returns a description of this revision of the configuration. */ describeConfigurationRevision(callback?: (err: AWSError, data: Kafka.Types.DescribeConfigurationRevisionResponse) => void): Request<Kafka.Types.DescribeConfigurationRevisionResponse, AWSError>; /** * Disassociates one or more Scram Secrets from an Amazon MSK cluster. */ batchDisassociateScramSecret(params: Kafka.Types.BatchDisassociateScramSecretRequest, callback?: (err: AWSError, data: Kafka.Types.BatchDisassociateScramSecretResponse) => void): Request<Kafka.Types.BatchDisassociateScramSecretResponse, AWSError>; /** * Disassociates one or more Scram Secrets from an Amazon MSK cluster. */ batchDisassociateScramSecret(callback?: (err: AWSError, data: Kafka.Types.BatchDisassociateScramSecretResponse) => void): Request<Kafka.Types.BatchDisassociateScramSecretResponse, AWSError>; /** * A list of brokers that a client application can use to bootstrap. */ getBootstrapBrokers(params: Kafka.Types.GetBootstrapBrokersRequest, callback?: (err: AWSError, data: Kafka.Types.GetBootstrapBrokersResponse) => void): Request<Kafka.Types.GetBootstrapBrokersResponse, AWSError>; /** * A list of brokers that a client application can use to bootstrap. */ getBootstrapBrokers(callback?: (err: AWSError, data: Kafka.Types.GetBootstrapBrokersResponse) => void): Request<Kafka.Types.GetBootstrapBrokersResponse, AWSError>; /** * Gets the Apache Kafka versions to which you can update the MSK cluster. */ getCompatibleKafkaVersions(params: Kafka.Types.GetCompatibleKafkaVersionsRequest, callback?: (err: AWSError, data: Kafka.Types.GetCompatibleKafkaVersionsResponse) => void): Request<Kafka.Types.GetCompatibleKafkaVersionsResponse, AWSError>; /** * Gets the Apache Kafka versions to which you can update the MSK cluster. */ getCompatibleKafkaVersions(callback?: (err: AWSError, data: Kafka.Types.GetCompatibleKafkaVersionsResponse) => void): Request<Kafka.Types.GetCompatibleKafkaVersionsResponse, AWSError>; /** * Returns a list of all the operations that have been performed on the specified MSK cluster. */ listClusterOperations(params: Kafka.Types.ListClusterOperationsRequest, callback?: (err: AWSError, data: Kafka.Types.ListClusterOperationsResponse) => void): Request<Kafka.Types.ListClusterOperationsResponse, AWSError>; /** * Returns a list of all the operations that have been performed on the specified MSK cluster. */ listClusterOperations(callback?: (err: AWSError, data: Kafka.Types.ListClusterOperationsResponse) => void): Request<Kafka.Types.ListClusterOperationsResponse, AWSError>; /** * Returns a list of all the MSK clusters in the current Region. */ listClusters(params: Kafka.Types.ListClustersRequest, callback?: (err: AWSError, data: Kafka.Types.ListClustersResponse) => void): Request<Kafka.Types.ListClustersResponse, AWSError>; /** * Returns a list of all the MSK clusters in the current Region. */ listClusters(callback?: (err: AWSError, data: Kafka.Types.ListClustersResponse) => void): Request<Kafka.Types.ListClustersResponse, AWSError>; /** * Returns a list of all the MSK configurations in this Region. */ listConfigurationRevisions(params: Kafka.Types.ListConfigurationRevisionsRequest, callback?: (err: AWSError, data: Kafka.Types.ListConfigurationRevisionsResponse) => void): Request<Kafka.Types.ListConfigurationRevisionsResponse, AWSError>; /** * Returns a list of all the MSK configurations in this Region. */ listConfigurationRevisions(callback?: (err: AWSError, data: Kafka.Types.ListConfigurationRevisionsResponse) => void): Request<Kafka.Types.ListConfigurationRevisionsResponse, AWSError>; /** * Returns a list of all the MSK configurations in this Region. */ listConfigurations(params: Kafka.Types.ListConfigurationsRequest, callback?: (err: AWSError, data: Kafka.Types.ListConfigurationsResponse) => void): Request<Kafka.Types.ListConfigurationsResponse, AWSError>; /** * Returns a list of all the MSK configurations in this Region. */ listConfigurations(callback?: (err: AWSError, data: Kafka.Types.ListConfigurationsResponse) => void): Request<Kafka.Types.ListConfigurationsResponse, AWSError>; /** * Returns a list of Kafka versions. */ listKafkaVersions(params: Kafka.Types.ListKafkaVersionsRequest, callback?: (err: AWSError, data: Kafka.Types.ListKafkaVersionsResponse) => void): Request<Kafka.Types.ListKafkaVersionsResponse, AWSError>; /** * Returns a list of Kafka versions. */ listKafkaVersions(callback?: (err: AWSError, data: Kafka.Types.ListKafkaVersionsResponse) => void): Request<Kafka.Types.ListKafkaVersionsResponse, AWSError>; /** * Returns a list of the broker nodes in the cluster. */ listNodes(params: Kafka.Types.ListNodesRequest, callback?: (err: AWSError, data: Kafka.Types.ListNodesResponse) => void): Request<Kafka.Types.ListNodesResponse, AWSError>; /** * Returns a list of the broker nodes in the cluster. */ listNodes(callback?: (err: AWSError, data: Kafka.Types.ListNodesResponse) => void): Request<Kafka.Types.ListNodesResponse, AWSError>; /** * Returns a list of the Scram Secrets associated with an Amazon MSK cluster. */ listScramSecrets(params: Kafka.Types.ListScramSecretsRequest, callback?: (err: AWSError, data: Kafka.Types.ListScramSecretsResponse) => void): Request<Kafka.Types.ListScramSecretsResponse, AWSError>; /** * Returns a list of the Scram Secrets associated with an Amazon MSK cluster. */ listScramSecrets(callback?: (err: AWSError, data: Kafka.Types.ListScramSecretsResponse) => void): Request<Kafka.Types.ListScramSecretsResponse, AWSError>; /** * Returns a list of the tags associated with the specified resource. */ listTagsForResource(params: Kafka.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: Kafka.Types.ListTagsForResourceResponse) => void): Request<Kafka.Types.ListTagsForResourceResponse, AWSError>; /** * Returns a list of the tags associated with the specified resource. */ listTagsForResource(callback?: (err: AWSError, data: Kafka.Types.ListTagsForResourceResponse) => void): Request<Kafka.Types.ListTagsForResourceResponse, AWSError>; /** * Reboots brokers. */ rebootBroker(params: Kafka.Types.RebootBrokerRequest, callback?: (err: AWSError, data: Kafka.Types.RebootBrokerResponse) => void): Request<Kafka.Types.RebootBrokerResponse, AWSError>; /** * Reboots brokers. */ rebootBroker(callback?: (err: AWSError, data: Kafka.Types.RebootBrokerResponse) => void): Request<Kafka.Types.RebootBrokerResponse, AWSError>; /** * Adds tags to the specified MSK resource. */ tagResource(params: Kafka.Types.TagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Adds tags to the specified MSK resource. */ tagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes the tags associated with the keys that are provided in the query. */ untagResource(params: Kafka.Types.UntagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes the tags associated with the keys that are provided in the query. */ untagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates the number of broker nodes in the cluster. */ updateBrokerCount(params: Kafka.Types.UpdateBrokerCountRequest, callback?: (err: AWSError, data: Kafka.Types.UpdateBrokerCountResponse) => void): Request<Kafka.Types.UpdateBrokerCountResponse, AWSError>; /** * Updates the number of broker nodes in the cluster. */ updateBrokerCount(callback?: (err: AWSError, data: Kafka.Types.UpdateBrokerCountResponse) => void): Request<Kafka.Types.UpdateBrokerCountResponse, AWSError>; /** * Updates EC2 instance type. */ updateBrokerType(params: Kafka.Types.UpdateBrokerTypeRequest, callback?: (err: AWSError, data: Kafka.Types.UpdateBrokerTypeResponse) => void): Request<Kafka.Types.UpdateBrokerTypeResponse, AWSError>; /** * Updates EC2 instance type. */ updateBrokerType(callback?: (err: AWSError, data: Kafka.Types.UpdateBrokerTypeResponse) => void): Request<Kafka.Types.UpdateBrokerTypeResponse, AWSError>; /** * Updates the EBS storage associated with MSK brokers. */ updateBrokerStorage(params: Kafka.Types.UpdateBrokerStorageRequest, callback?: (err: AWSError, data: Kafka.Types.UpdateBrokerStorageResponse) => void): Request<Kafka.Types.UpdateBrokerStorageResponse, AWSError>; /** * Updates the EBS storage associated with MSK brokers. */ updateBrokerStorage(callback?: (err: AWSError, data: Kafka.Types.UpdateBrokerStorageResponse) => void): Request<Kafka.Types.UpdateBrokerStorageResponse, AWSError>; /** * Updates an MSK configuration. */ updateConfiguration(params: Kafka.Types.UpdateConfigurationRequest, callback?: (err: AWSError, data: Kafka.Types.UpdateConfigurationResponse) => void): Request<Kafka.Types.UpdateConfigurationResponse, AWSError>; /** * Updates an MSK configuration. */ updateConfiguration(callback?: (err: AWSError, data: Kafka.Types.UpdateConfigurationResponse) => void): Request<Kafka.Types.UpdateConfigurationResponse, AWSError>; /** * Updates the cluster with the configuration that is specified in the request body. */ updateClusterConfiguration(params: Kafka.Types.UpdateClusterConfigurationRequest, callback?: (err: AWSError, data: Kafka.Types.UpdateClusterConfigurationResponse) => void): Request<Kafka.Types.UpdateClusterConfigurationResponse, AWSError>; /** * Updates the cluster with the configuration that is specified in the request body. */ updateClusterConfiguration(callback?: (err: AWSError, data: Kafka.Types.UpdateClusterConfigurationResponse) => void): Request<Kafka.Types.UpdateClusterConfigurationResponse, AWSError>; /** * Updates the Apache Kafka version for the cluster. */ updateClusterKafkaVersion(params: Kafka.Types.UpdateClusterKafkaVersionRequest, callback?: (err: AWSError, data: Kafka.Types.UpdateClusterKafkaVersionResponse) => void): Request<Kafka.Types.UpdateClusterKafkaVersionResponse, AWSError>; /** * Updates the Apache Kafka version for the cluster. */ updateClusterKafkaVersion(callback?: (err: AWSError, data: Kafka.Types.UpdateClusterKafkaVersionResponse) => void): Request<Kafka.Types.UpdateClusterKafkaVersionResponse, AWSError>; /** * Updates the monitoring settings for the cluster. You can use this operation to specify which Apache Kafka metrics you want Amazon MSK to send to Amazon CloudWatch. You can also specify settings for open monitoring with Prometheus. */ updateMonitoring(params: Kafka.Types.UpdateMonitoringRequest, callback?: (err: AWSError, data: Kafka.Types.UpdateMonitoringResponse) => void): Request<Kafka.Types.UpdateMonitoringResponse, AWSError>; /** * Updates the monitoring settings for the cluster. You can use this operation to specify which Apache Kafka metrics you want Amazon MSK to send to Amazon CloudWatch. You can also specify settings for open monitoring with Prometheus. */ updateMonitoring(callback?: (err: AWSError, data: Kafka.Types.UpdateMonitoringResponse) => void): Request<Kafka.Types.UpdateMonitoringResponse, AWSError>; /** * Updates the security settings for the cluster. You can use this operation to specify encryption and authentication on existing clusters. */ updateSecurity(params: Kafka.Types.UpdateSecurityRequest, callback?: (err: AWSError, data: Kafka.Types.UpdateSecurityResponse) => void): Request<Kafka.Types.UpdateSecurityResponse, AWSError>; /** * Updates the security settings for the cluster. You can use this operation to specify encryption and authentication on existing clusters. */ updateSecurity(callback?: (err: AWSError, data: Kafka.Types.UpdateSecurityResponse) => void): Request<Kafka.Types.UpdateSecurityResponse, AWSError>; } declare namespace Kafka { export interface BatchAssociateScramSecretRequest { /** * The Amazon Resource Name (ARN) of the cluster to be updated. */ ClusterArn: __string; /** * List of AWS Secrets Manager secret ARNs. */ SecretArnList: __listOf__string; } export interface BatchAssociateScramSecretResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * List of errors when associating secrets to cluster. */ UnprocessedScramSecrets?: __listOfUnprocessedScramSecret; } export type BrokerAZDistribution = "DEFAULT"|string; export interface BrokerEBSVolumeInfo { /** * The ID of the broker to update. */ KafkaBrokerNodeId: __string; /** * Size of the EBS volume to update. */ VolumeSizeGB: __integer; } export interface BrokerLogs { CloudWatchLogs?: CloudWatchLogs; Firehose?: Firehose; S3?: S3; } export interface BrokerNodeGroupInfo { /** * The distribution of broker nodes across Availability Zones. This is an optional parameter. If you don't specify it, Amazon MSK gives it the value DEFAULT. You can also explicitly set this parameter to the value DEFAULT. No other values are currently allowed. Amazon MSK distributes the broker nodes evenly across the Availability Zones that correspond to the subnets you provide when you create the cluster. */ BrokerAZDistribution?: BrokerAZDistribution; /** * The list of subnets to connect to in the client virtual private cloud (VPC). AWS creates elastic network interfaces inside these subnets. Client applications use elastic network interfaces to produce and consume data. Client subnets can't be in Availability Zone us-east-1e. */ ClientSubnets: __listOf__string; /** * The type of Amazon EC2 instances to use for Kafka brokers. The following instance types are allowed: kafka.m5.large, kafka.m5.xlarge, kafka.m5.2xlarge, kafka.m5.4xlarge, kafka.m5.12xlarge, and kafka.m5.24xlarge. */ InstanceType: __stringMin5Max32; /** * The AWS security groups to associate with the elastic network interfaces in order to specify who can connect to and communicate with the Amazon MSK cluster. If you don't specify a security group, Amazon MSK uses the default security group associated with the VPC. */ SecurityGroups?: __listOf__string; /** * Contains information about storage volumes attached to MSK broker nodes. */ StorageInfo?: StorageInfo; } export interface BrokerNodeInfo { /** * The attached elastic network interface of the broker. */ AttachedENIId?: __string; /** * The ID of the broker. */ BrokerId?: __double; /** * The client subnet to which this broker node belongs. */ ClientSubnet?: __string; /** * The virtual private cloud (VPC) of the client. */ ClientVpcIpAddress?: __string; /** * Information about the version of software currently deployed on the Kafka brokers in the cluster. */ CurrentBrokerSoftwareInfo?: BrokerSoftwareInfo; /** * Endpoints for accessing the broker. */ Endpoints?: __listOf__string; } export interface BrokerSoftwareInfo { /** * The Amazon Resource Name (ARN) of the configuration used for the cluster. This field isn't visible in this preview release. */ ConfigurationArn?: __string; /** * The revision of the configuration to use. This field isn't visible in this preview release. */ ConfigurationRevision?: __long; /** * The version of Apache Kafka. */ KafkaVersion?: __string; } export interface ClientAuthentication { /** * Details for ClientAuthentication using SASL. */ Sasl?: Sasl; /** * Details for ClientAuthentication using TLS. */ Tls?: Tls; /** * Contains information about unauthenticated traffic to the cluster. */ Unauthenticated?: Unauthenticated; } export type ClientBroker = "TLS"|"TLS_PLAINTEXT"|"PLAINTEXT"|string; export interface CloudWatchLogs { Enabled: __boolean; LogGroup?: __string; } export interface ClusterInfo { /** * Arn of active cluster operation. */ ActiveOperationArn?: __string; /** * Information about the broker nodes. */ BrokerNodeGroupInfo?: BrokerNodeGroupInfo; /** * Includes all client authentication information. */ ClientAuthentication?: ClientAuthentication; /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn?: __string; /** * The name of the cluster. */ ClusterName?: __string; /** * The time when the cluster was created. */ CreationTime?: __timestampIso8601; /** * Information about the version of software currently deployed on the Kafka brokers in the cluster. */ CurrentBrokerSoftwareInfo?: BrokerSoftwareInfo; /** * The current version of the MSK cluster. */ CurrentVersion?: __string; /** * Includes all encryption-related information. */ EncryptionInfo?: EncryptionInfo; /** * Specifies which metrics are gathered for the MSK cluster. This property has the following possible values: DEFAULT, PER_BROKER, PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION. For a list of the metrics associated with each of these levels of monitoring, see Monitoring. */ EnhancedMonitoring?: EnhancedMonitoring; /** * Settings for open monitoring using Prometheus. */ OpenMonitoring?: OpenMonitoring; LoggingInfo?: LoggingInfo; /** * The number of broker nodes in the cluster. */ NumberOfBrokerNodes?: __integer; /** * The state of the cluster. The possible states are ACTIVE, CREATING, DELETING, FAILED, HEALING, MAINTENANCE, REBOOTING_BROKER, and UPDATING. */ State?: ClusterState; StateInfo?: StateInfo; /** * Tags attached to the cluster. */ Tags?: __mapOf__string; /** * The connection string to use to connect to the Apache ZooKeeper cluster. */ ZookeeperConnectString?: __string; /** * The connection string to use to connect to zookeeper cluster on Tls port. */ ZookeeperConnectStringTls?: __string; } export interface ClusterOperationInfo { /** * The ID of the API request that triggered this operation. */ ClientRequestId?: __string; /** * ARN of the cluster. */ ClusterArn?: __string; /** * The time that the operation was created. */ CreationTime?: __timestampIso8601; /** * The time at which the operation finished. */ EndTime?: __timestampIso8601; /** * Describes the error if the operation fails. */ ErrorInfo?: ErrorInfo; /** * ARN of the cluster operation. */ OperationArn?: __string; /** * State of the cluster operation. */ OperationState?: __string; /** * Steps completed during the operation. */ OperationSteps?: __listOfClusterOperationStep; /** * Type of the cluster operation. */ OperationType?: __string; /** * Information about cluster attributes before a cluster is updated. */ SourceClusterInfo?: MutableClusterInfo; /** * Information about cluster attributes after a cluster is updated. */ TargetClusterInfo?: MutableClusterInfo; } export interface ClusterOperationStep { /** * Information about the step and its status. */ StepInfo?: ClusterOperationStepInfo; /** * The name of the step. */ StepName?: __string; } export interface ClusterOperationStepInfo { /** * The steps current status. */ StepStatus?: __string; } export type ClusterState = "ACTIVE"|"CREATING"|"DELETING"|"FAILED"|"HEALING"|"MAINTENANCE"|"REBOOTING_BROKER"|"UPDATING"|string; export interface CompatibleKafkaVersion { /** * A Kafka version. */ SourceVersion?: __string; /** * A list of Kafka versions. */ TargetVersions?: __listOf__string; } export interface Configuration { /** * The Amazon Resource Name (ARN) of the configuration. */ Arn: __string; /** * The time when the configuration was created. */ CreationTime: __timestampIso8601; /** * The description of the configuration. */ Description: __string; /** * An array of the versions of Apache Kafka with which you can use this MSK configuration. You can use this configuration for an MSK cluster only if the Apache Kafka version specified for the cluster appears in this array. */ KafkaVersions: __listOf__string; /** * Latest revision of the configuration. */ LatestRevision: ConfigurationRevision; /** * The name of the configuration. */ Name: __string; /** * The state of the configuration. The possible states are ACTIVE, DELETING, and DELETE_FAILED. */ State: ConfigurationState; } export interface ConfigurationInfo { /** * ARN of the configuration to use. */ Arn: __string; /** * The revision of the configuration to use. */ Revision: __long; } export interface ConfigurationRevision { /** * The time when the configuration revision was created. */ CreationTime: __timestampIso8601; /** * The description of the configuration revision. */ Description?: __string; /** * The revision number. */ Revision: __long; } export type ConfigurationState = "ACTIVE"|"DELETING"|"DELETE_FAILED"|string; export interface CreateClusterRequest { /** * Information about the broker nodes in the cluster. */ BrokerNodeGroupInfo: BrokerNodeGroupInfo; /** * Includes all client authentication related information. */ ClientAuthentication?: ClientAuthentication; /** * The name of the cluster. */ ClusterName: __stringMin1Max64; /** * Represents the configuration that you want MSK to use for the brokers in a cluster. */ ConfigurationInfo?: ConfigurationInfo; /** * Includes all encryption-related information. */ EncryptionInfo?: EncryptionInfo; /** * Specifies the level of monitoring for the MSK cluster. The possible values are DEFAULT, PER_BROKER, PER_TOPIC_PER_BROKER, and PER_TOPIC_PER_PARTITION. */ EnhancedMonitoring?: EnhancedMonitoring; /** * The settings for open monitoring. */ OpenMonitoring?: OpenMonitoringInfo; /** * The version of Apache Kafka. */ KafkaVersion: __stringMin1Max128; LoggingInfo?: LoggingInfo; /** * The number of broker nodes in the cluster. */ NumberOfBrokerNodes: __integerMin1Max15; /** * Create tags when creating the cluster. */ Tags?: __mapOf__string; } export interface CreateClusterResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * The name of the MSK cluster. */ ClusterName?: __string; /** * The state of the cluster. The possible states are ACTIVE, CREATING, DELETING, FAILED, HEALING, MAINTENANCE, REBOOTING_BROKER, and UPDATING. */ State?: ClusterState; } export interface CreateConfigurationRequest { /** * The description of the configuration. */ Description?: __string; /** * The versions of Apache Kafka with which you can use this MSK configuration. */ KafkaVersions?: __listOf__string; /** * The name of the configuration. */ Name: __string; /** * Contents of the server.properties file. When using the API, you must ensure that the contents of the file are base64 encoded. When using the AWS Management Console, the SDK, or the AWS CLI, the contents of server.properties can be in plaintext. */ ServerProperties: __blob; } export interface CreateConfigurationResponse { /** * The Amazon Resource Name (ARN) of the configuration. */ Arn?: __string; /** * The time when the configuration was created. */ CreationTime?: __timestampIso8601; /** * Latest revision of the configuration. */ LatestRevision?: ConfigurationRevision; /** * The name of the configuration. */ Name?: __string; /** * The state of the configuration. The possible states are ACTIVE, DELETING, and DELETE_FAILED. */ State?: ConfigurationState; } export interface DeleteClusterRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; /** * The current version of the MSK cluster. */ CurrentVersion?: __string; } export interface DeleteClusterResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * The state of the cluster. The possible states are ACTIVE, CREATING, DELETING, FAILED, HEALING, MAINTENANCE, REBOOTING_BROKER, and UPDATING. */ State?: ClusterState; } export interface DeleteConfigurationRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies an MSK configuration. */ Arn: __string; } export interface DeleteConfigurationResponse { /** * The Amazon Resource Name (ARN) that uniquely identifies an MSK configuration. */ Arn?: __string; /** * The state of the configuration. The possible states are ACTIVE, DELETING, and DELETE_FAILED. */ State?: ConfigurationState; } export interface DescribeClusterOperationRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the MSK cluster operation. */ ClusterOperationArn: __string; } export interface DescribeClusterOperationResponse { /** * Cluster operation information */ ClusterOperationInfo?: ClusterOperationInfo; } export interface DescribeClusterRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; } export interface DescribeClusterResponse { /** * The cluster information. */ ClusterInfo?: ClusterInfo; } export interface DescribeConfigurationRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies an MSK configuration and all of its revisions. */ Arn: __string; } export interface DescribeConfigurationResponse { /** * The Amazon Resource Name (ARN) of the configuration. */ Arn?: __string; /** * The time when the configuration was created. */ CreationTime?: __timestampIso8601; /** * The description of the configuration. */ Description?: __string; /** * The versions of Apache Kafka with which you can use this MSK configuration. */ KafkaVersions?: __listOf__string; /** * Latest revision of the configuration. */ LatestRevision?: ConfigurationRevision; /** * The name of the configuration. */ Name?: __string; /** * The state of the configuration. The possible states are ACTIVE, DELETING, and DELETE_FAILED. */ State?: ConfigurationState; } export interface DescribeConfigurationRevisionRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies an MSK configuration and all of its revisions. */ Arn: __string; /** * A string that uniquely identifies a revision of an MSK configuration. */ Revision: __long; } export interface DescribeConfigurationRevisionResponse { /** * The Amazon Resource Name (ARN) of the configuration. */ Arn?: __string; /** * The time when the configuration was created. */ CreationTime?: __timestampIso8601; /** * The description of the configuration. */ Description?: __string; /** * The revision number. */ Revision?: __long; /** * Contents of the server.properties file. When using the API, you must ensure that the contents of the file are base64 encoded. When using the AWS Management Console, the SDK, or the AWS CLI, the contents of server.properties can be in plaintext. */ ServerProperties?: __blob; } export interface BatchDisassociateScramSecretRequest { /** * The Amazon Resource Name (ARN) of the cluster to be updated. */ ClusterArn: __string; /** * List of AWS Secrets Manager secret ARNs. */ SecretArnList: __listOf__string; } export interface BatchDisassociateScramSecretResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * List of errors when disassociating secrets to cluster. */ UnprocessedScramSecrets?: __listOfUnprocessedScramSecret; } export interface EBSStorageInfo { /** * The size in GiB of the EBS volume for the data drive on each broker node. */ VolumeSize?: __integerMin1Max16384; } export interface EncryptionAtRest { /** * The ARN of the AWS KMS key for encrypting data at rest. If you don't specify a KMS key, MSK creates one for you and uses it. */ DataVolumeKMSKeyId: __string; } export interface EncryptionInTransit { /** * Indicates the encryption setting for data in transit between clients and brokers. The following are the possible values. TLS means that client-broker communication is enabled with TLS only. TLS_PLAINTEXT means that client-broker communication is enabled for both TLS-encrypted, as well as plaintext data. PLAINTEXT means that client-broker communication is enabled in plaintext only. The default value is TLS_PLAINTEXT. */ ClientBroker?: ClientBroker; /** * When set to true, it indicates that data communication among the broker nodes of the cluster is encrypted. When set to false, the communication happens in plaintext. The default value is true. */ InCluster?: __boolean; } export interface EncryptionInfo { /** * The data-volume encryption details. */ EncryptionAtRest?: EncryptionAtRest; /** * The details for encryption in transit. */ EncryptionInTransit?: EncryptionInTransit; } export type EnhancedMonitoring = "DEFAULT"|"PER_BROKER"|"PER_TOPIC_PER_BROKER"|"PER_TOPIC_PER_PARTITION"|string; export interface ErrorInfo { /** * A number describing the error programmatically. */ ErrorCode?: __string; /** * An optional field to provide more details about the error. */ ErrorString?: __string; } export interface Firehose { DeliveryStream?: __string; Enabled: __boolean; } export interface GetBootstrapBrokersRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; } export interface GetBootstrapBrokersResponse { /** * A string containing one or more hostname:port pairs. */ BootstrapBrokerString?: __string; /** * A string containing one or more DNS names (or IP) and TLS port pairs. */ BootstrapBrokerStringTls?: __string; /** * A string containing one or more DNS names (or IP) and Sasl Scram port pairs. */ BootstrapBrokerStringSaslScram?: __string; /** * A string that contains one or more DNS names (or IP addresses) and SASL IAM port pairs. */ BootstrapBrokerStringSaslIam?: __string; } export interface GetCompatibleKafkaVersionsRequest { /** * The Amazon Resource Name (ARN) of the cluster check. */ ClusterArn?: __string; } export interface GetCompatibleKafkaVersionsResponse { /** * A list of CompatibleKafkaVersion objects. */ CompatibleKafkaVersions?: __listOfCompatibleKafkaVersion; } export interface KafkaVersion { Version?: __string; Status?: KafkaVersionStatus; } export type KafkaVersionStatus = "ACTIVE"|"DEPRECATED"|string; export interface ListClusterOperationsRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; /** * The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter. */ MaxResults?: MaxResults; /** * The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response. To get the next batch, provide this token in your next request. */ NextToken?: __string; } export interface ListClusterOperationsResponse { /** * An array of cluster operation information objects. */ ClusterOperationInfoList?: __listOfClusterOperationInfo; /** * If the response of ListClusterOperations is truncated, it returns a NextToken in the response. This Nexttoken should be sent in the subsequent request to ListClusterOperations. */ NextToken?: __string; } export interface ListClustersRequest { /** * Specify a prefix of the name of the clusters that you want to list. The service lists all the clusters whose names start with this prefix. */ ClusterNameFilter?: __string; /** * The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter. */ MaxResults?: MaxResults; /** * The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response. To get the next batch, provide this token in your next request. */ NextToken?: __string; } export interface ListClustersResponse { /** * Information on each of the MSK clusters in the response. */ ClusterInfoList?: __listOfClusterInfo; /** * The paginated results marker. When the result of a ListClusters operation is truncated, the call returns NextToken in the response. To get another batch of clusters, provide this token in your next request. */ NextToken?: __string; } export interface ListConfigurationRevisionsRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies an MSK configuration and all of its revisions. */ Arn: __string; /** * The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter. */ MaxResults?: MaxResults; /** * The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response. To get the next batch, provide this token in your next request. */ NextToken?: __string; } export interface ListConfigurationRevisionsResponse { /** * Paginated results marker. */ NextToken?: __string; /** * List of ConfigurationRevision objects. */ Revisions?: __listOfConfigurationRevision; } export interface ListConfigurationsRequest { /** * The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter. */ MaxResults?: MaxResults; /** * The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response. To get the next batch, provide this token in your next request. */ NextToken?: __string; } export interface ListConfigurationsResponse { /** * An array of MSK configurations. */ Configurations?: __listOfConfiguration; /** * The paginated results marker. When the result of a ListConfigurations operation is truncated, the call returns NextToken in the response. To get another batch of configurations, provide this token in your next request. */ NextToken?: __string; } export interface ListKafkaVersionsRequest { /** * The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter. */ MaxResults?: MaxResults; /** * The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response. To get the next batch, provide this token in your next request. */ NextToken?: __string; } export interface ListKafkaVersionsResponse { KafkaVersions?: __listOfKafkaVersion; NextToken?: __string; } export interface ListNodesRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; /** * The maximum number of results to return in the response. If there are more results, the response includes a NextToken parameter. */ MaxResults?: MaxResults; /** * The paginated results marker. When the result of the operation is truncated, the call returns NextToken in the response. To get the next batch, provide this token in your next request. */ NextToken?: __string; } export interface ListNodesResponse { /** * The paginated results marker. When the result of a ListNodes operation is truncated, the call returns NextToken in the response. To get another batch of nodes, provide this token in your next request. */ NextToken?: __string; /** * List containing a NodeInfo object. */ NodeInfoList?: __listOfNodeInfo; } export interface ListScramSecretsRequest { /** * The arn of the cluster. */ ClusterArn: __string; /** * The maxResults of the query. */ MaxResults?: MaxResults; /** * The nextToken of the query. */ NextToken?: __string; } export interface ListScramSecretsResponse { /** * Paginated results marker. */ NextToken?: __string; /** * The list of scram secrets associated with the cluster. */ SecretArnList?: __listOf__string; } export interface ListTagsForResourceRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the resource that's associated with the tags. */ ResourceArn: __string; } export interface ListTagsForResourceResponse { /** * The key-value pair for the resource tag. */ Tags?: __mapOf__string; } export type MaxResults = number; export interface LoggingInfo { BrokerLogs: BrokerLogs; } export interface MutableClusterInfo { /** * Specifies the size of the EBS volume and the ID of the associated broker. */ BrokerEBSVolumeInfo?: __listOfBrokerEBSVolumeInfo; /** * Information about the changes in the configuration of the brokers. */ ConfigurationInfo?: ConfigurationInfo; /** * The number of broker nodes in the cluster. */ NumberOfBrokerNodes?: __integer; /** * Specifies which Apache Kafka metrics Amazon MSK gathers and sends to Amazon CloudWatch for this cluster. */ EnhancedMonitoring?: EnhancedMonitoring; /** * The settings for open monitoring. */ OpenMonitoring?: OpenMonitoring; /** * The Kafka version. */ KafkaVersion?: __string; /** * You can configure your MSK cluster to send broker logs to different destination types. This is a container for the configuration details related to broker logs. */ LoggingInfo?: LoggingInfo; /** * Information about the Amazon MSK broker type. */ InstanceType?: __stringMin5Max32; /** * Includes all client authentication information. */ ClientAuthentication?: ClientAuthentication; /** * Includes all encryption-related information. */ EncryptionInfo?: EncryptionInfo; } export interface NodeExporter { /** * Indicates whether you want to enable or disable the Node Exporter. */ EnabledInBroker: __boolean; } export interface NodeExporterInfo { /** * Indicates whether you want to enable or disable the Node Exporter. */ EnabledInBroker: __boolean; } export interface JmxExporter { /** * Indicates whether you want to enable or disable the JMX Exporter. */ EnabledInBroker: __boolean; } export interface JmxExporterInfo { /** * Indicates whether you want to enable or disable the JMX Exporter. */ EnabledInBroker: __boolean; } export interface OpenMonitoring { /** * Prometheus settings. */ Prometheus: Prometheus; } export interface OpenMonitoringInfo { /** * Prometheus settings. */ Prometheus: PrometheusInfo; } export interface Prometheus { /** * Indicates whether you want to enable or disable the JMX Exporter. */ JmxExporter?: JmxExporter; /** * Indicates whether you want to enable or disable the Node Exporter. */ NodeExporter?: NodeExporter; } export interface PrometheusInfo { /** * Indicates whether you want to enable or disable the JMX Exporter. */ JmxExporter?: JmxExporterInfo; /** * Indicates whether you want to enable or disable the Node Exporter. */ NodeExporter?: NodeExporterInfo; } export interface RebootBrokerRequest { /** * The list of broker IDs to be rebooted. The reboot-broker operation supports rebooting one broker at a time. */ BrokerIds: __listOf__string; /** * The Amazon Resource Name (ARN) of the cluster to be updated. */ ClusterArn: __string; } export interface RebootBrokerResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * The Amazon Resource Name (ARN) of the cluster operation. */ ClusterOperationArn?: __string; } export interface S3 { Bucket?: __string; Enabled: __boolean; Prefix?: __string; } export interface Sasl { /** * Details for SASL/SCRAM client authentication. */ Scram?: Scram; /** * Indicates whether IAM access control is enabled. */ Iam?: Iam; } export interface Scram { /** * SASL/SCRAM authentication is enabled or not. */ Enabled?: __boolean; } export interface Iam { /** * Indicates whether IAM access control is enabled. */ Enabled?: __boolean; } export interface NodeInfo { /** * The start time. */ AddedToClusterTime?: __string; /** * The broker node info. */ BrokerNodeInfo?: BrokerNodeInfo; /** * The instance type. */ InstanceType?: __string; /** * The Amazon Resource Name (ARN) of the node. */ NodeARN?: __string; /** * The node type. */ NodeType?: NodeType; /** * The ZookeeperNodeInfo. */ ZookeeperNodeInfo?: ZookeeperNodeInfo; } export type NodeType = "BROKER"|string; export interface StateInfo { Code?: __string; Message?: __string; } export interface StorageInfo { /** * EBS volume information. */ EbsStorageInfo?: EBSStorageInfo; } export interface TagResourceRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the resource that's associated with the tags. */ ResourceArn: __string; /** * The key-value pair for the resource tag. */ Tags: __mapOf__string; } export interface Tls { /** * List of ACM Certificate Authority ARNs. */ CertificateAuthorityArnList?: __listOf__string; /** * Specifies whether you want to enable or disable TLS authentication. */ Enabled?: __boolean; } export interface Unauthenticated { /** * Specifies whether you want to enable or disable unauthenticated traffic to your cluster. */ Enabled?: __boolean; } export interface UnprocessedScramSecret { /** * Error code for associate/disassociate failure. */ ErrorCode?: __string; /** * Error message for associate/disassociate failure. */ ErrorMessage?: __string; /** * AWS Secrets Manager secret ARN. */ SecretArn?: __string; } export interface UntagResourceRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the resource that's associated with the tags. */ ResourceArn: __string; /** * Tag keys must be unique for a given cluster. In addition, the following restrictions apply: Each tag key must be unique. If you add a tag with a key that's already in use, your new tag overwrites the existing key-value pair. You can't start a tag key with aws: because this prefix is reserved for use by AWS. AWS creates tags that begin with this prefix on your behalf, but you can't edit or delete them. Tag keys must be between 1 and 128 Unicode characters in length. Tag keys must consist of the following characters: Unicode letters, digits, white space, and the following special characters: _ . / = + - @. */ TagKeys: __listOf__string; } export interface UpdateBrokerCountRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; /** * The version of cluster to update from. A successful operation will then generate a new version. */ CurrentVersion: __string; /** * The number of broker nodes that you want the cluster to have after this operation completes successfully. */ TargetNumberOfBrokerNodes: __integerMin1Max15; } export interface UpdateBrokerCountResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * The Amazon Resource Name (ARN) of the cluster operation. */ ClusterOperationArn?: __string; } export interface UpdateBrokerTypeRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; /** * The cluster version that you want to change. After this operation completes successfully, the cluster will have a new version. */ CurrentVersion: __string; /** * The Amazon MSK broker type that you want all of the brokers in this cluster to be. */ TargetInstanceType: __string; } export interface UpdateBrokerTypeResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * The Amazon Resource Name (ARN) of the cluster operation. */ ClusterOperationArn?: __string; } export interface UpdateBrokerStorageRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; /** * The version of cluster to update from. A successful operation will then generate a new version. */ CurrentVersion: __string; /** * Describes the target volume size and the ID of the broker to apply the update to. */ TargetBrokerEBSVolumeInfo: __listOfBrokerEBSVolumeInfo; } export interface UpdateBrokerStorageResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * The Amazon Resource Name (ARN) of the cluster operation. */ ClusterOperationArn?: __string; } export interface UpdateClusterConfigurationRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; /** * Represents the configuration that you want MSK to use for the brokers in a cluster. */ ConfigurationInfo: ConfigurationInfo; /** * The version of the cluster that needs to be updated. */ CurrentVersion: __string; } export interface UpdateClusterConfigurationResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * The Amazon Resource Name (ARN) of the cluster operation. */ ClusterOperationArn?: __string; } export interface UpdateClusterKafkaVersionRequest { /** * The Amazon Resource Name (ARN) of the cluster to be updated. */ ClusterArn: __string; /** * The custom configuration that should be applied on the new version of cluster. */ ConfigurationInfo?: ConfigurationInfo; /** * Current cluster version. */ CurrentVersion: __string; /** * Target Kafka version. */ TargetKafkaVersion: __string; } export interface UpdateClusterKafkaVersionResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * The Amazon Resource Name (ARN) of the cluster operation. */ ClusterOperationArn?: __string; } export interface UpdateMonitoringRequest { /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; /** * The version of the MSK cluster to update. Cluster versions aren't simple numbers. You can describe an MSK cluster to find its version. When this update operation is successful, it generates a new cluster version. */ CurrentVersion: __string; /** * Specifies which Apache Kafka metrics Amazon MSK gathers and sends to Amazon CloudWatch for this cluster. */ EnhancedMonitoring?: EnhancedMonitoring; /** * The settings for open monitoring. */ OpenMonitoring?: OpenMonitoringInfo; LoggingInfo?: LoggingInfo; } export interface UpdateMonitoringResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * The Amazon Resource Name (ARN) of the cluster operation. */ ClusterOperationArn?: __string; } export interface UpdateSecurityRequest { /** * Includes all client authentication related information. */ ClientAuthentication?: ClientAuthentication; /** * The Amazon Resource Name (ARN) that uniquely identifies the cluster. */ ClusterArn: __string; /** * The version of the MSK cluster to update. Cluster versions aren't simple numbers. You can describe an MSK cluster to find its version. When this update operation is successful, it generates a new cluster version. */ CurrentVersion: __string; /** * Includes all encryption-related information. */ EncryptionInfo?: EncryptionInfo; } export interface UpdateSecurityResponse { /** * The Amazon Resource Name (ARN) of the cluster. */ ClusterArn?: __string; /** * The Amazon Resource Name (ARN) of the cluster operation. */ ClusterOperationArn?: __string; } export interface UpdateConfigurationRequest { /** * The Amazon Resource Name (ARN) of the configuration. */ Arn: __string; /** * The description of the configuration revision. */ Description?: __string; /** * Contents of the server.properties file. When using the API, you must ensure that the contents of the file are base64 encoded. When using the AWS Management Console, the SDK, or the AWS CLI, the contents of server.properties can be in plaintext. */ ServerProperties: __blob; } export interface UpdateConfigurationResponse { /** * The Amazon Resource Name (ARN) of the configuration. */ Arn?: __string; /** * Latest revision of the configuration. */ LatestRevision?: ConfigurationRevision; } export interface ZookeeperNodeInfo { /** * The attached elastic network interface of the broker. */ AttachedENIId?: __string; /** * The virtual private cloud (VPC) IP address of the client. */ ClientVpcIpAddress?: __string; /** * Endpoints for accessing the ZooKeeper. */ Endpoints?: __listOf__string; /** * The role-specific ID for Zookeeper. */ ZookeeperId?: __double; /** * The version of Zookeeper. */ ZookeeperVersion?: __string; } export type __boolean = boolean; export type __blob = Buffer|Uint8Array|Blob|string; export type __double = number; export type __integer = number; export type __integerMin1Max15 = number; export type __integerMin1Max16384 = number; export type __listOfBrokerEBSVolumeInfo = BrokerEBSVolumeInfo[]; export type __listOfClusterInfo = ClusterInfo[]; export type __listOfClusterOperationInfo = ClusterOperationInfo[]; export type __listOfClusterOperationStep = ClusterOperationStep[]; export type __listOfCompatibleKafkaVersion = CompatibleKafkaVersion[]; export type __listOfConfiguration = Configuration[]; export type __listOfConfigurationRevision = ConfigurationRevision[]; export type __listOfKafkaVersion = KafkaVersion[]; export type __listOfNodeInfo = NodeInfo[]; export type __listOfUnprocessedScramSecret = UnprocessedScramSecret[]; export type __listOf__string = __string[]; export type __long = number; export type __mapOf__string = {[key: string]: __string}; export type __string = string; export type __stringMin1Max128 = string; export type __stringMin1Max64 = string; export type __stringMin5Max32 = string; export type __timestampIso8601 = Date; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2018-11-14"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the Kafka client. */ export import Types = Kafka; } export = Kafka;
the_stack
import {CommonModule} from '@angular/common'; import {Component, Directive, forwardRef, Inject, Injectable, InjectionToken, Injector, NgModule, Optional} from '@angular/core'; import {leaveView, specOnlyIsInstructionStateEmpty} from '@angular/core/src/render3/state'; import {inject, TestBed, waitForAsync} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {expect} from '@angular/platform-browser/testing/src/matchers'; describe('providers', () => { describe('inheritance', () => { it('should NOT inherit providers', () => { const SOME_DIRS = new InjectionToken('someDirs'); @Directive({ selector: '[super-dir]', providers: [{provide: SOME_DIRS, useClass: SuperDirective, multi: true}] }) class SuperDirective { } @Directive({ selector: '[sub-dir]', providers: [{provide: SOME_DIRS, useClass: SubDirective, multi: true}] }) class SubDirective extends SuperDirective { } @Directive({selector: '[other-dir]'}) class OtherDirective { constructor(@Inject(SOME_DIRS) public dirs: any) {} } @Component({selector: 'app-comp', template: `<div other-dir sub-dir></div>`}) class App { } TestBed.configureTestingModule( {declarations: [SuperDirective, SubDirective, OtherDirective, App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); const otherDir = fixture.debugElement.query(By.css('div')).injector.get(OtherDirective); expect(otherDir.dirs.length).toEqual(1); expect(otherDir.dirs[0] instanceof SubDirective).toBe(true); }); }); describe('lifecycles', () => { it('should inherit ngOnDestroy hooks on providers', () => { const logs: string[] = []; @Injectable() class SuperInjectableWithDestroyHook { ngOnDestroy() { logs.push('OnDestroy'); } } @Injectable() class SubInjectableWithDestroyHook extends SuperInjectableWithDestroyHook { } @Component({template: '', providers: [SubInjectableWithDestroyHook]}) class App { constructor(foo: SubInjectableWithDestroyHook) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual(['OnDestroy']); }); it('should not call ngOnDestroy for providers that have not been requested', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHook { ngOnDestroy() { logs.push('OnDestroy'); } } @Component({template: '', providers: [InjectableWithDestroyHook]}) class App { } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual([]); }); it('should only call ngOnDestroy once for multiple instances', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHook { ngOnDestroy() { logs.push('OnDestroy'); } } @Component({selector: 'my-cmp', template: ''}) class MyComponent { constructor(foo: InjectableWithDestroyHook) {} } @Component({ template: ` <my-cmp></my-cmp> <my-cmp></my-cmp> `, providers: [InjectableWithDestroyHook] }) class App { } TestBed.configureTestingModule({declarations: [App, MyComponent]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual(['OnDestroy']); }); it('should call ngOnDestroy when providing same token via useClass', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHook { ngOnDestroy() { logs.push('OnDestroy'); } } @Component({ template: '', providers: [{provide: InjectableWithDestroyHook, useClass: InjectableWithDestroyHook}] }) class App { constructor(foo: InjectableWithDestroyHook) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual(['OnDestroy']); }); it('should only call ngOnDestroy of value when providing via useClass', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHookToken { ngOnDestroy() { logs.push('OnDestroy Token'); } } @Injectable() class InjectableWithDestroyHookValue { ngOnDestroy() { logs.push('OnDestroy Value'); } } @Component({ template: '', providers: [{provide: InjectableWithDestroyHookToken, useClass: InjectableWithDestroyHookValue}] }) class App { constructor(foo: InjectableWithDestroyHookToken) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual(['OnDestroy Value']); }); it('should only call ngOnDestroy of value when providing via useExisting', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHookToken { ngOnDestroy() { logs.push('OnDestroy Token'); } } @Injectable() class InjectableWithDestroyHookExisting { ngOnDestroy() { logs.push('OnDestroy Existing'); } } @Component({ template: '', providers: [ InjectableWithDestroyHookExisting, {provide: InjectableWithDestroyHookToken, useExisting: InjectableWithDestroyHookExisting} ] }) class App { constructor(foo1: InjectableWithDestroyHookExisting, foo2: InjectableWithDestroyHookToken) { } } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(logs).toEqual(['OnDestroy Existing']); }); it('should invoke ngOnDestroy with the correct context when providing a type provider multiple times on the same node', () => { const resolvedServices: (DestroyService|undefined)[] = []; const destroyContexts: (DestroyService|undefined)[] = []; let parentService: DestroyService|undefined; let childService: DestroyService|undefined; @Injectable() class DestroyService { constructor() { resolvedServices.push(this); } ngOnDestroy() { destroyContexts.push(this); } } @Directive({selector: '[dir-one]', providers: [DestroyService]}) class DirOne { constructor(service: DestroyService) { childService = service; } } @Directive({selector: '[dir-two]', providers: [DestroyService]}) class DirTwo { constructor(service: DestroyService) { childService = service; } } @Component({template: '<div dir-one dir-two></div>', providers: [DestroyService]}) class App { constructor(service: DestroyService) { parentService = service; } } TestBed.configureTestingModule({declarations: [App, DirOne, DirTwo]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(parentService).toBeDefined(); expect(childService).toBeDefined(); expect(parentService).not.toBe(childService); expect(resolvedServices).toEqual([parentService, childService]); expect(destroyContexts).toEqual([parentService, childService]); }); it('should invoke ngOnDestroy with the correct context when providing a class provider multiple times on the same node', () => { const resolvedServices: (DestroyService|undefined)[] = []; const destroyContexts: (DestroyService|undefined)[] = []; const token = new InjectionToken<any>('token'); let parentService: DestroyService|undefined; let childService: DestroyService|undefined; @Injectable() class DestroyService { constructor() { resolvedServices.push(this); } ngOnDestroy() { destroyContexts.push(this); } } @Directive( {selector: '[dir-one]', providers: [{provide: token, useClass: DestroyService}]}) class DirOne { constructor(@Inject(token) service: DestroyService) { childService = service; } } @Directive( {selector: '[dir-two]', providers: [{provide: token, useClass: DestroyService}]}) class DirTwo { constructor(@Inject(token) service: DestroyService) { childService = service; } } @Component({ template: '<div dir-one dir-two></div>', providers: [{provide: token, useClass: DestroyService}] }) class App { constructor(@Inject(token) service: DestroyService) { parentService = service; } } TestBed.configureTestingModule({declarations: [App, DirOne, DirTwo]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(parentService).toBeDefined(); expect(childService).toBeDefined(); expect(parentService).not.toBe(childService); expect(resolvedServices).toEqual([parentService, childService]); expect(destroyContexts).toEqual([parentService, childService]); }); describe('ngOnDestroy on multi providers', () => { it('should invoke ngOnDestroy on multi providers with the correct context', () => { const destroyCalls: any[] = []; const SERVICES = new InjectionToken<any>('SERVICES'); @Injectable() class DestroyService { ngOnDestroy() { destroyCalls.push(this); } } @Injectable() class OtherDestroyService { ngOnDestroy() { destroyCalls.push(this); } } @Component({ template: '<div></div>', providers: [ {provide: SERVICES, useClass: DestroyService, multi: true}, {provide: SERVICES, useClass: OtherDestroyService, multi: true}, ] }) class App { constructor(@Inject(SERVICES) s: any) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(destroyCalls).toEqual([ jasmine.any(DestroyService), jasmine.any(OtherDestroyService) ]); }); it('should invoke destroy hooks on multi providers with the correct context, if only some have a destroy hook', () => { const destroyCalls: any[] = []; const SERVICES = new InjectionToken<any>('SERVICES'); @Injectable() class Service1 { } @Injectable() class Service2 { ngOnDestroy() { destroyCalls.push(this); } } @Injectable() class Service3 { } @Injectable() class Service4 { ngOnDestroy() { destroyCalls.push(this); } } @Component({ template: '<div></div>', providers: [ {provide: SERVICES, useClass: Service1, multi: true}, {provide: SERVICES, useClass: Service2, multi: true}, {provide: SERVICES, useClass: Service3, multi: true}, {provide: SERVICES, useClass: Service4, multi: true}, ] }) class App { constructor(@Inject(SERVICES) s: any) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(destroyCalls).toEqual([jasmine.any(Service2), jasmine.any(Service4)]); }); it('should not invoke ngOnDestroy on multi providers created via useFactory', () => { let destroyCalls = 0; const SERVICES = new InjectionToken<any>('SERVICES'); @Injectable() class DestroyService { ngOnDestroy() { destroyCalls++; } } @Injectable() class OtherDestroyService { ngOnDestroy() { destroyCalls++; } } @Component({ template: '<div></div>', providers: [ {provide: SERVICES, useFactory: () => new DestroyService(), multi: true}, {provide: SERVICES, useFactory: () => new OtherDestroyService(), multi: true}, ] }) class App { constructor(@Inject(SERVICES) s: any) {} } TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.destroy(); expect(destroyCalls).toBe(0); }); }); it('should call ngOnDestroy if host component is destroyed', () => { const logs: string[] = []; @Injectable() class InjectableWithDestroyHookToken { ngOnDestroy() { logs.push('OnDestroy Token'); } } @Component({ selector: 'comp-with-provider', template: '', providers: [InjectableWithDestroyHookToken], }) class CompWithProvider { constructor(token: InjectableWithDestroyHookToken) {} } @Component({ selector: 'app', template: '<comp-with-provider *ngIf="condition"></comp-with-provider>', }) class App { condition = true; } TestBed.configureTestingModule({ declarations: [App, CompWithProvider], imports: [CommonModule], }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); fixture.componentInstance.condition = false; fixture.detectChanges(); expect(logs).toEqual(['OnDestroy Token']); }); }); describe('components and directives', () => { class MyService { value = 'some value'; } @Component({selector: 'my-comp', template: ``}) class MyComp { constructor(public svc: MyService) {} } @Directive({selector: '[some-dir]'}) class MyDir { constructor(public svc: MyService) {} } it('should support providing components in tests without @Injectable', () => { @Component({selector: 'test-comp', template: '<my-comp></my-comp>'}) class TestComp { } TestBed.configureTestingModule({ declarations: [TestComp, MyComp], // providing MyComp is unnecessary but it shouldn't throw providers: [MyComp, MyService], }); const fixture = TestBed.createComponent(TestComp); const myCompInstance = fixture.debugElement.query(By.css('my-comp')).injector.get(MyComp); expect(myCompInstance.svc.value).toEqual('some value'); }); it('should support providing directives in tests without @Injectable', () => { @Component({selector: 'test-comp', template: '<div some-dir></div>'}) class TestComp { } TestBed.configureTestingModule({ declarations: [TestComp, MyDir], // providing MyDir is unnecessary but it shouldn't throw providers: [MyDir, MyService], }); const fixture = TestBed.createComponent(TestComp); const myCompInstance = fixture.debugElement.query(By.css('div')).injector.get(MyDir); expect(myCompInstance.svc.value).toEqual('some value'); }); // TODO(alxhub): find a way to isolate this test from running in a dirty // environment where a current LView exists (probably from some other test // bootstrapping and then not cleaning up). xdescribe('injection without bootstrapping', () => { beforeEach(() => { // Maybe something like this? while (!specOnlyIsInstructionStateEmpty()) { leaveView(); } TestBed.configureTestingModule({declarations: [MyComp], providers: [MyComp, MyService]}); }); it('should support injecting without bootstrapping', waitForAsync(inject([MyComp, MyService], (comp: MyComp, service: MyService) => { expect(comp.svc.value).toEqual('some value'); }))); }); }); describe('forward refs', () => { it('should support forward refs in provider deps', () => { class MyService { constructor(public dep: {value: string}) {} } class OtherService { value = 'one'; } @Component({selector: 'app-comp', template: ``}) class AppComp { constructor(public myService: MyService) {} } @NgModule({ providers: [ OtherService, { provide: MyService, useFactory: (dep: {value: string}) => new MyService(dep), deps: [forwardRef(() => OtherService)] } ], declarations: [AppComp] }) class MyModule { } TestBed.configureTestingModule({imports: [MyModule]}); const fixture = TestBed.createComponent(AppComp); expect(fixture.componentInstance.myService.dep.value).toBe('one'); }); it('should support forward refs in useClass when impl version is also provided', () => { @Injectable({providedIn: 'root', useClass: forwardRef(() => SomeProviderImpl)}) abstract class SomeProvider { } @Injectable() class SomeProviderImpl extends SomeProvider { } @Component({selector: 'my-app', template: ''}) class App { constructor(public foo: SomeProvider) {} } // We don't configure the `SomeProvider` in the TestingModule so that it uses the // tree-shakable provider given in the `@Injectable` decorator above, which makes use of the // `forwardRef()`. TestBed.configureTestingModule({declarations: [App]}); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.foo).toBeAnInstanceOf(SomeProviderImpl); }); it('should support forward refs in useClass when token is provided', () => { @Injectable({providedIn: 'root'}) abstract class SomeProvider { } @Injectable() class SomeProviderImpl extends SomeProvider { } @Component({selector: 'my-app', template: ''}) class App { constructor(public foo: SomeProvider) {} } TestBed.configureTestingModule({ declarations: [App], providers: [{provide: SomeProvider, useClass: forwardRef(() => SomeProviderImpl)}] }); const fixture = TestBed.createComponent(App); fixture.detectChanges(); expect(fixture.componentInstance.foo).toBeAnInstanceOf(SomeProviderImpl); }); }); describe('flags', () => { class MyService { constructor(public value: OtherService|null) {} } class OtherService {} it('should support Optional flag in deps', () => { const injector = Injector.create([{provide: MyService, deps: [[new Optional(), OtherService]]}]); expect(injector.get(MyService).value).toBe(null); }); it('should support Optional flag in deps without instantiating it', () => { const injector = Injector.create([{provide: MyService, deps: [[Optional, OtherService]]}]); expect(injector.get(MyService).value).toBe(null); }); }); describe('view providers', () => { it('should have access to viewProviders within the same component', () => { @Component({ selector: 'comp', template: '{{s}}-{{n}}', providers: [ {provide: Number, useValue: 1, multi: true}, ], viewProviders: [ {provide: String, useValue: 'bar'}, {provide: Number, useValue: 2, multi: true}, ] }) class Comp { constructor(private s: String, private n: Number) {} } TestBed.configureTestingModule({declarations: [Comp]}); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('bar-1,2'); }); it('should have access to viewProviders of the host component', () => { @Component({ selector: 'repeated', template: '[{{s}}-{{n}}]', }) class Repeated { constructor(private s: String, private n: Number) {} } @Component({ template: ` <div> <ng-container *ngFor="let item of items"> <repeated></repeated> </ng-container> </div> `, providers: [ {provide: Number, useValue: 1, multi: true}, ], viewProviders: [ {provide: String, useValue: 'foo'}, {provide: Number, useValue: 2, multi: true}, ], }) class ComponentWithProviders { items = [1, 2, 3]; } TestBed.configureTestingModule({ declarations: [ComponentWithProviders, Repeated], imports: [CommonModule], }); const fixture = TestBed.createComponent(ComponentWithProviders); fixture.detectChanges(); expect(fixture.nativeElement.textContent).toBe('[foo-1,2][foo-1,2][foo-1,2]'); }); }); });
the_stack
import { INestApplication } from '@nestjs/common' import { Test } from '@nestjs/testing' import { AppModule } from '../../../../app/app.module' import { DeploymentRepositoryV2 } from '../../../../app/v2/api/deployments/repository/deployment.repository' import { FixtureUtilsService } from '../fixture-utils.service' import { TestSetupUtils } from '../test-setup-utils' import { EntityManager } from 'typeorm' import { HookParams } from '../../../../app/v2/operator/interfaces/params.interface' import * as request from 'supertest' import { DeploymentEntityV2 as DeploymentEntity } from '../../../../app/v2/api/deployments/entity/deployment.entity' import { ComponentEntityV2 as ComponentEntity } from '../../../../app/v2/api/deployments/entity/component.entity' import { UrlConstants } from '../test-constants' import { getSimpleManifests } from '../../fixtures/manifests.fixture' describe('Reconcile deployments usecase', () => { let fixtureUtilsService: FixtureUtilsService let app: INestApplication let manager: EntityManager let hookParamsWithDeploymentNotReady: HookParams beforeAll(async() => { const module = Test.createTestingModule({ imports: [ await AppModule.forRootAsync() ], providers: [ FixtureUtilsService, DeploymentRepositoryV2 ] }) app = await TestSetupUtils.createApplication(module) TestSetupUtils.seApplicationConstants() fixtureUtilsService = app.get<FixtureUtilsService>(FixtureUtilsService) manager = fixtureUtilsService.manager hookParamsWithDeploymentNotReady = { 'controller': { 'kind': 'CompositeController', 'apiVersion': 'metacontroller.k8s.io/v1alpha1', 'metadata': { 'name': 'charlesdeployments-controller', 'uid': '67a4c2e9-4a27-4c8c-8c99-735c96ead809', 'resourceVersion': '834', 'generation': 1, 'creationTimestamp': '2021-01-18T13:29:13Z', 'labels': { 'app.kubernetes.io/managed-by': 'Helm' }, 'annotations': { 'meta.helm.sh/release-name': 'charlescd', 'meta.helm.sh/release-namespace': 'default' } }, 'spec': { 'parentResource': { 'apiVersion': 'charlescd.io/v1', 'resource': 'charlesdeployments' }, 'childResources': [ { 'apiVersion': 'v1', 'resource': 'services', 'updateStrategy': { 'method': 'Recreate', 'statusChecks': {} } }, { 'apiVersion': 'apps/v1', 'resource': 'deployments', 'updateStrategy': { 'method': 'Recreate', 'statusChecks': {} } } ], 'hooks': { 'sync': { 'webhook': { 'url': 'http://charlescd-butler.default.svc.cluster.local:3000/v2/operator/deployment/hook/reconcile' } }, 'finalize': { 'webhook': { 'url': 'http://charlescd-butler.default.svc.cluster.local:3000/v2/operator/deployment/hook/finalize' } } }, 'generateSelector': true }, 'status': {} }, 'parent': { 'apiVersion': 'charlescd.io/v1', 'kind': 'CharlesDeployment', 'metadata': { 'creationTimestamp': '2021-01-18T13:33:14Z', 'finalizers': [ 'metacontroller.app/compositecontroller-charlesdeployments-controller' ], 'generation': 1, 'labels': { // this key is used to fetch the deployment 'deployment_id': 'b7d08a07-f29d-452e-a667-7a39820f3262' }, 'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'namespace': 'default', 'resourceVersion': '1368', 'uid': 'aeb60d21-75d8-40d5-8639-9c5623c35921' }, 'spec': { 'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'components': [ { 'chart': 'http://fake-repo/repos/charlescd-fake/helm-chart', 'name': 'batata', 'tag': 'latest' }, { 'chart': 'http://fake-repo/repos/charlescd-fake/helm-chart', 'name': 'jilo', 'tag': 'latest' } ], 'deploymentId': 'b7d08a07-f29d-452e-a667-7a39820f3262' } }, 'children': { 'Deployment.apps/v1': { 'hello-kubernetes-build-image-tag-b46fd548-0082-4021-ba80-a50703c44a3b': { 'apiVersion': 'apps/v1', 'kind': 'Deployment', 'metadata': { 'creationTimestamp': '2021-01-15T21:01:22Z', 'generation': 1, 'labels': { 'app': 'hello-kubernetes', 'circleId': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'controller-uid': '5c6e0a99-f05b-4198-8499-469fa34f755b', // this key is used to match the deployment 'deploymentId': 'e728a072-b0aa-4459-88ba-0f4a9b71ae54', 'version': 'hello-kubernetes' }, 'name': 'batata-ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'namespace': 'default', 'ownerReferences': [ { 'apiVersion': 'charlescd.io/v1', 'blockOwnerDeletion': true, 'controller': true, 'kind': 'CharlesDeployment', 'name': 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'uid': '5c6e0a99-f05b-4198-8499-469fa34f755b' } ], 'resourceVersion': '6755', 'uid': '1127f97a-4288-4dfc-8cc3-6c9a039b26cf' }, 'spec': { 'progressDeadlineSeconds': 600, 'replicas': 1, 'revisionHistoryLimit': 10, 'selector': { 'matchLabels': { 'app': 'batata', 'version': 'batata' } }, 'strategy': { 'rollingUpdate': { 'maxSurge': '25%', 'maxUnavailable': '25%' }, 'type': 'RollingUpdate' }, 'template': { 'metadata': { 'annotations': { 'sidecar.istio.io/inject': 'true' }, 'creationTimestamp': null, 'labels': { 'app': 'batata', 'version': 'batata' } }, 'spec': { 'containers': [ { 'args': [ '-text', 'hello' ], 'image': 'hashicorp/http-echo', 'imagePullPolicy': 'Always', 'livenessProbe': { 'failureThreshold': 3, 'httpGet': { 'path': '/', 'port': 5678, 'scheme': 'HTTP' }, 'initialDelaySeconds': 30, 'periodSeconds': 20, 'successThreshold': 1, 'timeoutSeconds': 1 }, 'name': 'batata', 'readinessProbe': { 'failureThreshold': 3, 'httpGet': { 'path': '/', 'port': 5678, 'scheme': 'HTTP' }, 'initialDelaySeconds': 30, 'periodSeconds': 20, 'successThreshold': 1, 'timeoutSeconds': 1 }, 'resources': { 'limits': { 'cpu': '128m', 'memory': '128Mi' }, 'requests': { 'cpu': '64m', 'memory': '64Mi' } }, 'terminationMessagePath': '/dev/termination-log', 'terminationMessagePolicy': 'File' } ], 'dnsPolicy': 'ClusterFirst', 'restartPolicy': 'Always', 'schedulerName': 'default-scheduler', 'securityContext': {}, 'terminationGracePeriodSeconds': 30 } } }, 'status': { 'availableReplicas': 1, 'conditions': [ { 'lastTransitionTime': '2021-01-15T21:01:22Z', 'lastUpdateTime': '2021-01-15T21:02:06Z', 'message': 'ReplicaSet "batata-ed2a1669-34b8-4af2-b42c-acbad2ec6b60-7f7dfc545f" has successfully progressed.', 'reason': 'NewReplicaSetAvailable', 'status': 'True', 'type': 'Progressing' } ], 'observedGeneration': 1, 'readyReplicas': 1, 'replicas': 1, 'updatedReplicas': 1 } }, }, 'Service.v1': {} }, 'finalizing': false } }) afterAll(async() => { await fixtureUtilsService.clearDatabase() await app.close() }) beforeEach(async() => { await fixtureUtilsService.clearDatabase() }) it('should generate the reconcile deployment object with the correct metadata changes', async() => { const previousDeployment: DeploymentEntity = new DeploymentEntity( '29f3a5ee-73f5-4957-b2e9-47d3b493a484', 'user-1', 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'http://localhost:1234/notifications/deployment?deploymentId=1', [ new ComponentEntity( UrlConstants.helmRepository, 'v1', 'https://repository.com/A:v1', 'A', '5209259f-3b1f-4fa4-b32c-e80eb33e819e', null, null, getSimpleManifests('A', 'my-namespace', 'imageurl.com') ) ], false, 'my-namespace', 60 ) previousDeployment.current = false previousDeployment.healthy = false const currentDeployment: DeploymentEntity = new DeploymentEntity( 'b7d08a07-f29d-452e-a667-7a39820f3262', 'user-1', 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', 'http://localhost:1234/notifications/deployment?deploymentId=1', [ new ComponentEntity( UrlConstants.helmRepository, 'v1', 'https://repository.com/A:v1', 'A', '222cd8db-3767-45d5-a415-7cca09cccf91', null, null, getSimpleManifests('A', 'my-namespace', 'imageurl.com') ) ], false, 'my-namespace', 60 ) currentDeployment.current = true currentDeployment.healthy = false currentDeployment.previousDeploymentId = previousDeployment.id await manager.save(previousDeployment) await manager.save(currentDeployment) const expectedReconcileObj = { children: [ { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { labels: { app: 'A', circleId: 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', component: 'A', deploymentId: '29f3a5ee-73f5-4957-b2e9-47d3b493a484', tag: 'tag-example', version: 'A' }, name: 'A-v1-29f3a5ee-73f5-4957-b2e9-47d3b493a484', namespace: 'my-namespace' }, spec: { replicas: 1, selector: { matchLabels: { app: 'A', version: 'A' } }, template: { metadata: { annotations: { 'sidecar.istio.io/inject': 'true' }, labels: { app: 'A', circleId: 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', deploymentId: '29f3a5ee-73f5-4957-b2e9-47d3b493a484', version: 'A' } }, spec: { containers: [ { image: 'imageurl.com', imagePullPolicy: 'Always', livenessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, name: 'A', readinessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, resources: { limits: { cpu: '128m', memory: '128Mi' }, requests: { cpu: '64m', memory: '64Mi' } } } ], imagePullSecrets: [ { name: 'realwavelab-registry' } ] } } } }, { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { labels: { app: 'A', circleId: 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', component: 'A', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', tag: 'tag-example', version: 'A' }, name: 'A-v1-b7d08a07-f29d-452e-a667-7a39820f3262', namespace: 'my-namespace' }, spec: { replicas: 1, selector: { matchLabels: { app: 'A', version: 'A' } }, template: { metadata: { annotations: { 'sidecar.istio.io/inject': 'true' }, labels: { app: 'A', circleId: 'ed2a1669-34b8-4af2-b42c-acbad2ec6b60', deploymentId: 'b7d08a07-f29d-452e-a667-7a39820f3262', version: 'A' } }, spec: { containers: [ { image: 'imageurl.com', imagePullPolicy: 'Always', livenessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, name: 'A', readinessProbe: { failureThreshold: 3, httpGet: { path: '/', port: 80, scheme: 'HTTP' }, initialDelaySeconds: 30, periodSeconds: 20, successThreshold: 1, timeoutSeconds: 1 }, resources: { limits: { cpu: '128m', memory: '128Mi' }, requests: { cpu: '64m', memory: '64Mi' } } } ], imagePullSecrets: [ { name: 'realwavelab-registry' } ] } } } } ], resyncAfterSeconds: 5 } await request(app.getHttpServer()) .post('/v2/operator/deployment/hook/reconcile') .send(hookParamsWithDeploymentNotReady) .expect(200, expectedReconcileObj) }) })
the_stack
import { Observable } from 'rxjs'; import { ComponentType } from 'react'; import { GrafanaPlugin, PluginMeta } from './plugin'; import { PanelData } from './panel'; import { LogRowModel } from './logs'; import { AnnotationEvent, AnnotationQuery, AnnotationSupport } from './annotations'; import { DataTopic, KeyValue, LoadingState, TableData, TimeSeries } from './data'; import { DataFrame, DataFrameDTO } from './dataFrame'; import { RawTimeRange, TimeRange } from './time'; import { ScopedVars } from './ScopedVars'; import { CoreApp } from './app'; import { LiveChannelSupport } from './live'; import { CustomVariableSupport, DataSourceVariableSupport, StandardVariableSupport } from './variables'; import { makeClassES5Compatible } from '../utils/makeClassES5Compatible'; export interface DataSourcePluginOptionsEditorProps<JSONData = DataSourceJsonData, SecureJSONData = {}> { options: DataSourceSettings<JSONData, SecureJSONData>; onOptionsChange: (options: DataSourceSettings<JSONData, SecureJSONData>) => void; } // Utility type to extract the query type TQuery from a class extending DataSourceApi<TQuery, TOptions> export type DataSourceQueryType<DSType> = DSType extends DataSourceApi<infer TQuery, any> ? TQuery : never; // Utility type to extract the options type TOptions from a class extending DataSourceApi<TQuery, TOptions> export type DataSourceOptionsType<DSType> = DSType extends DataSourceApi<any, infer TOptions> ? TOptions : never; export class DataSourcePlugin< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataSourceQueryType<DSType>, TOptions extends DataSourceJsonData = DataSourceOptionsType<DSType>, TSecureOptions = {} > extends GrafanaPlugin<DataSourcePluginMeta<TOptions>> { components: DataSourcePluginComponents<DSType, TQuery, TOptions, TSecureOptions> = {}; constructor(public DataSourceClass: DataSourceConstructor<DSType, TQuery, TOptions>) { super(); } setConfigEditor(editor: ComponentType<DataSourcePluginOptionsEditorProps<TOptions, TSecureOptions>>) { this.components.ConfigEditor = editor; return this; } setConfigCtrl(ConfigCtrl: any) { this.angularConfigCtrl = ConfigCtrl; return this; } setQueryCtrl(QueryCtrl: any) { this.components.QueryCtrl = QueryCtrl; return this; } setAnnotationQueryCtrl(AnnotationsQueryCtrl: any) { this.components.AnnotationsQueryCtrl = AnnotationsQueryCtrl; return this; } setQueryEditor(QueryEditor: ComponentType<QueryEditorProps<DSType, TQuery, TOptions>>) { this.components.QueryEditor = QueryEditor; return this; } setExploreQueryField(ExploreQueryField: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>) { this.components.ExploreQueryField = ExploreQueryField; return this; } setExploreMetricsQueryField(ExploreQueryField: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>) { this.components.ExploreMetricsQueryField = ExploreQueryField; return this; } setExploreLogsQueryField(ExploreQueryField: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>) { this.components.ExploreLogsQueryField = ExploreQueryField; return this; } setQueryEditorHelp(QueryEditorHelp: ComponentType<QueryEditorHelpProps<TQuery>>) { this.components.QueryEditorHelp = QueryEditorHelp; return this; } /** * @deprecated prefer using `setQueryEditorHelp` */ setExploreStartPage(ExploreStartPage: ComponentType<QueryEditorHelpProps<TQuery>>) { return this.setQueryEditorHelp(ExploreStartPage); } /* * @deprecated -- prefer using {@link StandardVariableSupport} or {@link CustomVariableSupport} or {@link DataSourceVariableSupport} in data source instead * */ setVariableQueryEditor(VariableQueryEditor: any) { this.components.VariableQueryEditor = VariableQueryEditor; return this; } setMetadataInspector(MetadataInspector: ComponentType<MetadataInspectorProps<DSType, TQuery, TOptions>>) { this.components.MetadataInspector = MetadataInspector; return this; } setComponentsFromLegacyExports(pluginExports: any) { this.angularConfigCtrl = pluginExports.ConfigCtrl; this.components.QueryCtrl = pluginExports.QueryCtrl; this.components.AnnotationsQueryCtrl = pluginExports.AnnotationsQueryCtrl; this.components.ExploreQueryField = pluginExports.ExploreQueryField; this.components.QueryEditor = pluginExports.QueryEditor; this.components.QueryEditorHelp = pluginExports.QueryEditorHelp; this.components.VariableQueryEditor = pluginExports.VariableQueryEditor; } } export interface DataSourcePluginMeta<T extends KeyValue = {}> extends PluginMeta<T> { builtIn?: boolean; // Is this for all metrics?: boolean; logs?: boolean; annotations?: boolean; alerting?: boolean; tracing?: boolean; mixed?: boolean; hasQueryHelp?: boolean; category?: string; queryOptions?: PluginMetaQueryOptions; sort?: number; streaming?: boolean; unlicensed?: boolean; isBackend?: boolean; } interface PluginMetaQueryOptions { cacheTimeout?: boolean; maxDataPoints?: boolean; minInterval?: boolean; } export interface DataSourcePluginComponents< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData, TSecureOptions = {} > { QueryCtrl?: any; AnnotationsQueryCtrl?: any; VariableQueryEditor?: any; QueryEditor?: ComponentType<QueryEditorProps<DSType, TQuery, TOptions>>; ExploreQueryField?: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>; ExploreMetricsQueryField?: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>; ExploreLogsQueryField?: ComponentType<ExploreQueryFieldProps<DSType, TQuery, TOptions>>; QueryEditorHelp?: ComponentType<QueryEditorHelpProps<TQuery>>; ConfigEditor?: ComponentType<DataSourcePluginOptionsEditorProps<TOptions, TSecureOptions>>; MetadataInspector?: ComponentType<MetadataInspectorProps<DSType, TQuery, TOptions>>; } // Only exported for tests export interface DataSourceConstructor< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { new (instanceSettings: DataSourceInstanceSettings<TOptions>, ...args: any[]): DSType; } /** * The main data source abstraction interface, represents an instance of a data source * * Although this is a class, datasource implementations do not *yet* need to extend it. * As such, we can not yet add functions with default implementations. */ abstract class DataSourceApi< TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData, TQueryImportConfiguration extends Record<string, object> = {} > { /** * Set in constructor */ readonly name: string; /** * Set in constructor */ readonly id: number; /** * Set in constructor */ readonly type: string; /** * Set in constructor */ readonly uid: string; /** * min interval range */ interval?: string; constructor(instanceSettings: DataSourceInstanceSettings<TOptions>) { this.name = instanceSettings.name; this.id = instanceSettings.id; this.type = instanceSettings.type; this.meta = {} as DataSourcePluginMeta; this.uid = instanceSettings.uid; } /** * Imports queries from a different datasource */ async importQueries?(queries: DataQuery[], originDataSource: DataSourceApi<DataQuery>): Promise<TQuery[]>; /** * Returns configuration for importing queries from other data sources */ getImportQueryConfiguration?(): TQueryImportConfiguration; /** * Initializes a datasource after instantiation */ init?: () => void; /** * Query for data, and optionally stream results */ abstract query(request: DataQueryRequest<TQuery>): Promise<DataQueryResponse> | Observable<DataQueryResponse>; /** * Test & verify datasource settings & connection details (returning TestingStatus) * * When verification fails - errors specific to the data source should be handled here and converted to * a TestingStatus object. Unknown errors and HTTP errors can be re-thrown and will be handled here: * public/app/features/datasources/state/actions.ts */ abstract testDatasource(): Promise<any>; /** * Get hints for query improvements */ getQueryHints?(query: TQuery, results: any[], ...rest: any): QueryHint[]; /** * Convert a query to a simple text string */ getQueryDisplayText?(query: TQuery): string; /** * Retrieve context for a given log row */ getLogRowContext?: <TContextQueryOptions extends {}>( row: LogRowModel, options?: TContextQueryOptions ) => Promise<DataQueryResponse>; /** * Variable query action. */ metricFindQuery?(query: any, options?: any): Promise<MetricFindValue[]>; /** * Get tag keys for adhoc filters */ getTagKeys?(options?: any): Promise<MetricFindValue[]>; /** * Get tag values for adhoc filters */ getTagValues?(options: any): Promise<MetricFindValue[]>; /** * Set after constructor call, as the data source instance is the most common thing to pass around * we attach the components to this instance for easy access */ components?: DataSourcePluginComponents<DataSourceApi<TQuery, TOptions>, TQuery, TOptions>; /** * static information about the datasource */ meta: DataSourcePluginMeta; /** * Used by alerting to check if query contains template variables */ targetContainsTemplate?(query: TQuery): boolean; /** * Used in explore */ modifyQuery?(query: TQuery, action: QueryFixAction): TQuery; /** * Used in explore */ getHighlighterExpression?(query: TQuery): string[]; /** * Used in explore */ languageProvider?: any; getVersion?(optionalOptions?: any): Promise<string>; showContextToggle?(row?: LogRowModel): boolean; interpolateVariablesInQueries?(queries: TQuery[], scopedVars: ScopedVars | {}): TQuery[]; /** * An annotation processor allows explicit control for how annotations are managed. * * It is only necessary to configure an annotation processor if the default behavior is not desirable */ annotations?: AnnotationSupport<TQuery>; /** * Can be optionally implemented to allow datasource to be a source of annotations for dashboard. * This function will only be called if an angular {@link AnnotationsQueryCtrl} is configured and * the {@link annotations} is undefined * * @deprecated -- prefer using {@link AnnotationSupport} */ annotationQuery?(options: AnnotationQueryRequest<TQuery>): Promise<AnnotationEvent[]>; /** * Define live streaming behavior within this datasource settings * * Note: `plugin.json` must also define `live: true` * * @alpha -- experimental */ channelSupport?: LiveChannelSupport; /** * Defines new variable support * @alpha -- experimental */ variables?: | StandardVariableSupport<DataSourceApi<TQuery, TOptions>> | CustomVariableSupport<DataSourceApi<TQuery, TOptions>> | DataSourceVariableSupport<DataSourceApi<TQuery, TOptions>>; } export interface MetadataInspectorProps< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > { datasource: DSType; // All Data from this DataSource data: DataFrame[]; } export interface QueryEditorProps< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData, TVQuery extends DataQuery = TQuery > { datasource: DSType; query: TVQuery; onRunQuery: () => void; onChange: (value: TVQuery) => void; onBlur?: () => void; /** * Contains query response filtered by refId of QueryResultBase and possible query error */ data?: PanelData; range?: TimeRange; exploreId?: any; history?: HistoryItem[]; queries?: DataQuery[]; app?: CoreApp; } // TODO: not really needed but used as type in some data sources and in DataQueryRequest export enum ExploreMode { Logs = 'Logs', Metrics = 'Metrics', Tracing = 'Tracing', } export interface ExploreQueryFieldProps< DSType extends DataSourceApi<TQuery, TOptions>, TQuery extends DataQuery = DataQuery, TOptions extends DataSourceJsonData = DataSourceJsonData > extends QueryEditorProps<DSType, TQuery, TOptions> { history: any[]; onBlur?: () => void; exploreId?: any; } export interface QueryEditorHelpProps<TQuery extends DataQuery = DataQuery> { datasource: DataSourceApi<TQuery>; onClickExample: (query: TQuery) => void; exploreId?: any; } /** * Starting in v6.2 DataFrame can represent both TimeSeries and TableData */ export type LegacyResponseData = TimeSeries | TableData | any; export type DataQueryResponseData = DataFrame | DataFrameDTO | LegacyResponseData; export interface DataQueryResponse { /** * The response data. When streaming, this may be empty * or a partial result set */ data: DataQueryResponseData[]; /** * When returning multiple partial responses or streams * Use this key to inform Grafana how to combine the partial responses * Multiple responses with same key are replaced (latest used) */ key?: string; /** * Optionally include error info along with the response data */ error?: DataQueryError; /** * Use this to control which state the response should have * Defaults to LoadingState.Done if state is not defined */ state?: LoadingState; } /** * These are the common properties available to all queries in all datasources * Specific implementations will extend this interface adding the required properties * for the given context */ export interface DataQuery { /** * A - Z */ refId: string; /** * true if query is disabled (ie should not be returned to the dashboard) */ hide?: boolean; /** * Unique, guid like, string used in explore mode */ key?: string; /** * Specify the query flavor */ queryType?: string; /** * The data topic results should be attached to */ dataTopic?: DataTopic; /** * For mixed data sources the selected datasource is on the query level. * For non mixed scenarios this is undefined. */ datasource?: string | null; } export enum DataQueryErrorType { Cancelled = 'cancelled', Timeout = 'timeout', Unknown = 'unknown', } export interface DataQueryError { data?: { /** * Short information about the error */ message?: string; /** * Detailed information about the error. Only returned when app_mode is development. */ error?: string; }; message?: string; status?: string; statusText?: string; refId?: string; type?: DataQueryErrorType; } export interface DataQueryRequest<TQuery extends DataQuery = DataQuery> { requestId: string; // Used to identify results and optionally cancel the request in backendSrv interval: string; intervalMs: number; maxDataPoints?: number; range: TimeRange; reverse?: boolean; scopedVars: ScopedVars; targets: TQuery[]; timezone: string; app: CoreApp | string; cacheTimeout?: string; rangeRaw?: RawTimeRange; timeInfo?: string; // The query time description (blue text in the upper right) panelId?: number; dashboardId?: number; // Request Timing startTime: number; endTime?: number; // Explore state used by various datasources liveStreaming?: boolean; } export interface DataQueryTimings { dataProcessingTime: number; } export interface QueryFix { label: string; action?: QueryFixAction; } export interface QueryFixAction { type: string; query?: string; preventSubmit?: boolean; } export interface QueryHint { type: string; label: string; fix?: QueryFix; } export interface MetricFindValue { text: string; value?: string | number; expandable?: boolean; } export interface DataSourceJsonData { authType?: string; defaultRegion?: string; profile?: string; manageAlerts?: boolean; } /** * Data Source instance edit model. This is returned from: * /api/datasources */ export interface DataSourceSettings<T extends DataSourceJsonData = DataSourceJsonData, S = {}> { id: number; uid: string; orgId: number; name: string; typeLogoUrl: string; type: string; typeName: string; access: string; url: string; password: string; user: string; database: string; basicAuth: boolean; basicAuthPassword: string; basicAuthUser: string; isDefault: boolean; jsonData: T; secureJsonData?: S; secureJsonFields: KeyValue<boolean>; readOnly: boolean; withCredentials: boolean; version?: number; } /** * Frontend settings model that is passed to Datasource constructor. This differs a bit from the model above * as this data model is available to every user who has access to a data source (Viewers+). This is loaded * in bootData (on page load), or from: /api/frontend/settings */ export interface DataSourceInstanceSettings<T extends DataSourceJsonData = DataSourceJsonData> { id: number; uid: string; type: string; name: string; meta: DataSourcePluginMeta; url?: string; jsonData: T; username?: string; password?: string; // when access is direct, for some legacy datasources database?: string; isDefault?: boolean; /** * This is the full Authorization header if basic auth is enabled. * Only available here when access is Browser (direct), when access is Server (proxy) * The basic auth header, username & password is never exposed to browser/Frontend * so this will be empty then. */ basicAuth?: string; withCredentials?: boolean; } /** * @deprecated -- use {@link DataSourceInstanceSettings} instead */ export interface DataSourceSelectItem { name: string; value: string | null; meta: DataSourcePluginMeta; } /** * Options passed to the datasource.annotationQuery method. See docs/plugins/developing/datasource.md * * @deprecated -- use {@link AnnotationSupport} */ export interface AnnotationQueryRequest<MoreOptions = {}> { range: TimeRange; rangeRaw: RawTimeRange; // Should be DataModel but cannot import that here from the main app. Needs to be moved to package first. dashboard: any; annotation: AnnotationQuery; } export interface HistoryItem<TQuery extends DataQuery = DataQuery> { ts: number; query: TQuery; } abstract class LanguageProvider { abstract datasource: DataSourceApi<any, any>; abstract request: (url: string, params?: any) => Promise<any>; /** * Returns startTask that resolves with a task list when main syntax is loaded. * Task list consists of secondary promises that load more detailed language features. */ abstract start: () => Promise<Array<Promise<any>>>; startTask?: Promise<any[]>; } //@ts-ignore LanguageProvider = makeClassES5Compatible(LanguageProvider); export { LanguageProvider }; //@ts-ignore DataSourceApi = makeClassES5Compatible(DataSourceApi); export { DataSourceApi };
the_stack
import chai from 'chai'; import sinon from 'sinon'; import is from 'is'; import Joi from '@hapi/joi'; import { Transaction as DatastoreTransaction } from '@google-cloud/datastore'; import GstoreEntity, { Entity } from './entity'; import GstoreSchema, { SchemaPathDefinition } from './schema'; import Model from './model'; import { Gstore, EntityKey } from './index'; import { ERROR_CODES } from './errors'; import dsFactory from '../__tests__/mocks/datastore'; import Transaction from '../__tests__/mocks/transaction'; import entitiesMock from '../__tests__/mocks/entities'; import Query from '../__tests__/mocks/query'; const ds = dsFactory({ namespace: 'com.mydomain' }); const gstore = new Gstore(); const gstoreWithCache = new Gstore({ cache: { config: { ttl: { queries: 600 } } } }); const { expect, assert } = chai; const { generateEntities } = entitiesMock; const { Schema } = gstore; describe('Model', () => { let schema: GstoreSchema; let GstoreModel: Model; let mockEntity; let mockEntities: any; let transaction: DatastoreTransaction; beforeEach(() => { gstore.models = {}; gstore.cache = undefined; gstore.config.errorOnEntityNotFound = true; gstore.connect(ds); gstoreWithCache.connect(ds); schema = new Schema({ name: { type: String }, lastname: { type: String, excludeFromIndexes: true }, password: { read: false }, age: { type: Number, excludeFromIndexes: true }, birthday: { type: Date }, street: {}, website: { validate: 'isURL' }, email: { validate: 'isEmail' }, ip: { validate: { rule: 'isIP', args: [4] } }, ip2: { validate: { rule: 'isIP' } }, // no args passed modified: { type: Boolean }, tags: { type: Array }, prefs: { type: Object }, price: { type: Schema.Types.Double, write: false }, icon: { type: Buffer }, location: { type: Schema.Types.GeoPoint }, }); schema.virtual('fullname').get(() => undefined); ({ mockEntity, mockEntities } = generateEntities()); transaction = new Transaction(); sinon.spy(ds, 'save'); sinon.stub(ds, 'transaction').callsFake(() => transaction); sinon.spy(transaction, 'save'); sinon.spy(transaction, 'commit'); sinon.spy(transaction, 'rollback'); sinon.stub(transaction, 'get').resolves([mockEntity]); sinon.stub(transaction, 'run').resolves([transaction, { apiData: 'ok' }]); GstoreModel = gstore.model('Blog', schema); }); afterEach(() => { ds.save.restore(); ds.transaction.restore(); (transaction.save as any).restore(); (transaction.commit as any).restore(); (transaction.rollback as any).restore(); }); describe('compile()', () => { beforeEach(() => { gstore.models = {}; GstoreModel = gstore.model('Blog', schema); }); test('should set properties on compile and return GstoreModel', () => { assert.isDefined(GstoreModel.schema); assert.isDefined(GstoreModel.gstore); assert.isDefined(GstoreModel.entityKind); }); test('should create new models classes', () => { const User = gstore.model('User', new Schema({})); expect(User.entityKind).equal('User'); expect(GstoreModel.entityKind).equal('Blog'); }); test('should execute methods passed to schema.methods', () => { const imageSchema = new Schema({}); const ImageModel = gstore.model('Image', imageSchema); sinon.stub(ImageModel, 'get').callsFake((id: any, cb: any): any => { cb(null, mockEntities[0]); }); schema.methods.fullName = function fullName(cb): any { return cb(null, `${this.get('name')} ${this.get('lastname')}`); }; schema.methods.getImage = function getImage(cb): any { return this.model('Image').get(this.entityData.imageIdx, cb); }; GstoreModel = gstore.model('MyEntity', schema); const entity = new GstoreModel({ name: 'John', lastname: 'Snow' }); entity.fullName((err: any, result: any) => { expect(result).equal('John Snow'); }); entity.getImage.call(entity, (err: any, result: any) => { expect(result).equal(mockEntities[0]); }); }); test('should add __meta object', () => { GstoreModel = gstore.model('MyEntity', schema); assert.isDefined(GstoreModel.schema.__meta); expect(GstoreModel.schema.__meta.geoPointsProps).deep.equal(['location']); }); }); describe('sanitize()', () => { test('should remove keys not "writable"', () => { let data: any = { price: 20, unknown: 'hello', name: 'John' }; data = GstoreModel.sanitize(data); assert.isUndefined(data.price); assert.isUndefined(data.unknown); }); test('should convert "null" string to null', () => { let data: any = { name: 'null', }; data = GstoreModel.sanitize(data); expect(data.name).equal(null); }); test('return an empty object if data is not an object', () => { let data = 'hello'; // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore data = GstoreModel.sanitize(data); expect(data).deep.equal({}); }); test('should not mutate the entityData passed', () => { const data = { name: 'John' }; const data2 = GstoreModel.sanitize(data); expect(data2).not.equal(data); }); test('should remove not writable & unknown props in Joi schema', () => { schema = new Schema( { createdOn: { joi: Joi.date(), write: false }, }, { joi: true }, ); GstoreModel = gstore.model('BlogJoi', schema); const entityData = GstoreModel.sanitize({ createdOn: Date.now(), unknown: 123 }); assert.isUndefined(entityData.createdOn); assert.isUndefined(entityData.unknown); }); test('should *not* remove unknown props in Joi schema', () => { schema = new Schema( { createdOn: { joi: Joi.date(), write: false }, }, { joi: { options: { allowUnknown: true } } }, ); GstoreModel = gstore.model('BlogJoi', schema); const entityData = GstoreModel.sanitize({ createdOn: Date.now(), unknown: 123 }); assert.isDefined(entityData.unknown); }); test('should return the same value object from Model.sanitize and Entity.validate in Joi schema', () => { schema = new Schema( { foo: { joi: Joi.object({ bar: Joi.any() }).required() }, // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore createdOn: { joi: Joi.date().default(() => new Date('01-01-2019'), 'static createdOn') }, }, { joi: true }, ); GstoreModel = gstore.model('BlogJoi', schema); const data = { foo: { unknown: 123 } }; const entityData = GstoreModel.sanitize(data); const { value: validationData, error: validationError } = new GstoreModel(data).validate(); assert.isUndefined(entityData.foo.unknown); assert.isNull(validationError); assert.deepEqual(entityData, validationData); }); test('should preserve the datastore.KEY', () => { const key = GstoreModel.key(123); let data: any = { foo: 'bar' }; data[GstoreModel.gstore.ds.KEY] = key; data = GstoreModel.sanitize(data); expect(data[GstoreModel.gstore.ds.KEY]).to.equal(key); }); test('should preserve the datastore.KEY with Joi Schemas', () => { schema = new Schema({}, { joi: true }); GstoreModel = gstore.model('SanitizeJoiSchemaPreserveKEY', schema); const key = GstoreModel.key(123); const data: any = { foo: 'bar' }; data[GstoreModel.gstore.ds.KEY] = key; const sanitized = GstoreModel.sanitize(data); expect(sanitized[gstore.ds.KEY as any]).to.equal(key); }); describe('populated entities', () => { beforeEach(() => { schema = new Schema({ ref: { type: Schema.Types.Key } }); GstoreModel = gstore.model('SanitizeReplacePopulatedEntity', schema); }); test('should replace a populated entity ref with its entity key', () => { const key = GstoreModel.key('abc'); const data = { ref: { title: 'Entity title populated', [gstore.ds.KEY]: key, }, }; const sanitized = GstoreModel.sanitize(data); assert.isTrue(gstore.ds.isKey(sanitized.ref)); expect(sanitized.ref).to.equal(key); }); test('should not replace a ref that is not an object', () => { const data = { ref: null }; const sanitized = GstoreModel.sanitize(data); assert.isFalse(gstore.ds.isKey(sanitized.ref)); expect(sanitized.ref).to.equal(null); }); }); }); describe('key()', () => { test('should create from entityKind', () => { const key = GstoreModel.key() as EntityKey; expect(key.path[0]).equal('Blog'); assert.isUndefined(key.path[1]); }); test('should create array of ids', () => { const keys = GstoreModel.key([22, 69]); expect(is.array(keys)).equal(true); expect(keys.length).equal(2); expect(keys[1].path[1]).equal(69); }); test('should create array of ids with ancestors and namespace', () => { const namespace = 'com.mydomain-dev'; const keys = GstoreModel.key([22, 69], ['Parent', 'keyParent'], namespace); expect(keys[0].path[0]).equal('Parent'); expect(keys[0].path[1]).equal('keyParent'); expect(keys[1].namespace).equal(namespace); }); }); describe('get()', () => { let entity: Entity<any>; beforeEach(() => { entity = { name: 'John' }; entity[ds.KEY] = GstoreModel.key(123); sinon.stub(ds, 'get').resolves([entity]); }); afterEach(() => { ds.get.restore(); }); test('passing an integer id', () => { return GstoreModel.get(123).then((_entity) => { expect(ds.get.getCall(0).args[0].constructor.name).equal('Key'); expect(_entity instanceof GstoreEntity).equal(true); }); }); test('passing an string id', () => GstoreModel.get('keyname').then((_entity) => { expect(_entity instanceof GstoreEntity).equal(true); })); test('passing an array of ids', () => { ds.get.restore(); const entity1: any = { name: 'John' }; entity1[ds.KEY] = ds.key(['BlogPost', 22]); const entity2: any = { name: 'John' }; entity2[ds.KEY] = ds.key(['BlogPost', 69]); sinon.stub(ds, 'get').resolves([[entity2, entity1]]); // not sorted return GstoreModel.get([22, 69], undefined, undefined, undefined, { preserveOrder: true }).then((_entity) => { expect(is.array(ds.get.getCall(0).args[0])).equal(true); expect(is.array(_entity)).equal(true); expect(_entity[0].entityKey.id).equal(22); // sorted }); }); test('should consistently return an array when providing id as an Array', () => GstoreModel.get(['abc']).then((_entity) => { assert.isTrue(is.array(_entity)); })); test('not converting string with mix of number and non number', () => GstoreModel.get('123:456').then(() => { expect(ds.get.getCall(0).args[0].name).equal('123:456'); })); test('passing an ancestor path array', () => { const ancestors = ['Parent', 'keyname']; return GstoreModel.get(123, ancestors).then(() => { expect(ds.get.getCall(0).args[0].constructor.name).equal('Key'); expect(ds.get.getCall(0).args[0].parent.kind).equal(ancestors[0]); expect(ds.get.getCall(0).args[0].parent.name).equal(ancestors[1]); }); }); test('should allow a namespace', () => { const namespace = 'com.mydomain-dev'; return GstoreModel.get(123, undefined, namespace).then(() => { expect(ds.get.getCall(0).args[0].namespace).equal(namespace); }); }); test('on datastore get error, should reject error', (done) => { ds.get.restore(); const error = { code: 500, message: 'Something went really bad' }; sinon.stub(ds, 'get').rejects(error); GstoreModel.get(123) .populate('test') .catch((err) => { expect(err).equal(error); done(); }); }); test('on no entity found, should return a "ERR_ENTITY_NOT_FOUND" error', () => { ds.get.restore(); sinon.stub(ds, 'get').resolves([]); return GstoreModel.get(123).catch((err) => { expect(err.code).equal(ERROR_CODES.ERR_ENTITY_NOT_FOUND); }); }); test('on no entity found, should return a null', () => { ds.get.restore(); gstore.config.errorOnEntityNotFound = false; sinon.stub(ds, 'get').resolves([]); return GstoreModel.get(123).then((e) => { expect(e).equal(null); }); }); test('should get in a transaction', () => GstoreModel.get(123, undefined, undefined, transaction).then((_entity) => { expect((transaction.get as any).called).equal(true); expect(ds.get.called).equal(false); expect(_entity instanceof GstoreEntity).equal(true); })); test('should throw error if transaction not an instance of glcoud Transaction', () => // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore GstoreModel.get(123, undefined, undefined, {}).catch((err) => { expect(err.message).equal('Transaction needs to be a gcloud Transaction'); })); test('should return error from Transaction.get()', () => { (transaction.get as any).restore(); const error = { code: 500, message: 'Houston we really need you' }; sinon.stub(transaction, 'get').rejects(error); return GstoreModel.get(123, undefined, undefined, transaction).catch((err) => { expect(err).equal(error); }); }); test('should get data through a Dataloader instance (singe key)', () => { const dataloader = gstore.createDataLoader(); const spy = sinon.stub(dataloader, 'load').resolves(entity); return GstoreModel.get(123, undefined, undefined, undefined, { dataloader }).then((res) => { expect(spy.called).equal(true); const args = spy.getCall(0).args[0]; const key = ds.key({ path: ['Blog', 123], namespace: 'com.mydomain' }); expect(args).deep.equal(key); expect(res.name).equal('John'); }); }); test('should get data through a Dataloader instance (multiple key)', () => { const dataloader = gstore.createDataLoader(); const spy = sinon.stub(dataloader, 'loadMany').resolves([{}, {}]); return GstoreModel.get([123, 456], undefined, undefined, undefined, { dataloader }).then(() => { expect(spy.called).equal(true); const args = spy.getCall(0).args[0]; const key1 = ds.key({ path: ['Blog', 123], namespace: 'com.mydomain' }); const key2 = ds.key({ path: ['Blog', 456], namespace: 'com.mydomain' }); expect(args[0]).deep.equal(key1); expect(args[1]).deep.equal(key2); }); }); test('should throw an error if dataloader is not a DataLoader instance', (done) => { const dataloader = {}; GstoreModel.get([123, 456], undefined, undefined, undefined, { dataloader }).then( () => undefined, (err) => { expect(err.name).equal('GstoreError'); expect(err.message).equal('dataloader must be a "DataLoader" instance'); done(); }, ); }); test('should allow to chain populate() calls and then call the Model.populate() method', () => { const populateSpy = sinon.spy(GstoreModel, '__populate'); const options = { dataLoader: { foo: 'bar' } }; return GstoreModel.get(123, undefined, undefined, undefined, options as any) .populate('company', ['name', 'phone-number']) .then(() => { expect(populateSpy.called).equal(true); const { args } = populateSpy.getCall(0); expect(args[0]![0]).deep.equal([{ path: 'company', select: ['name', 'phone-number'] }]); expect(args[1]).deep.equal({ ...options, transaction: undefined }); (GstoreModel.__populate as any).restore(); }); }); describe('when cache is active', () => { beforeEach(() => { gstore.cache = gstoreWithCache.cache; }); afterEach(() => { // empty the cache gstore.cache!.reset(); delete gstore.cache; }); test('should get value from cache', () => { sinon.spy(GstoreModel.gstore.cache!.keys, 'read'); const key = GstoreModel.key(123); const value = { name: 'Michael' }; return gstore.cache!.keys.set(key, value).then(() => GstoreModel.get(123, undefined, undefined, undefined, { ttl: 334455 }).then((response) => { assert.ok(!ds.get.called); expect(response.entityData).include(value); assert.ok((GstoreModel.gstore.cache!.keys.read as any).called); const { args } = (GstoreModel.gstore.cache!.keys.read as any).getCall(0); expect(args[0].id).equal(123); expect(args[1].ttl).equal(334455); (GstoreModel.gstore.cache!.keys.read as any).restore(); }), ); }); test('should throw an Error if entity not found in cache', (done) => { ds.get.resolves([]); GstoreModel.get(12345, undefined, undefined, undefined, { ttl: 334455 }).catch((err) => { expect(err.code).equal(ERROR_CODES.ERR_ENTITY_NOT_FOUND); done(); }); }); test('should return null if entity not found in cache', (done) => { ds.get.resolves([]); gstore.config.errorOnEntityNotFound = false; GstoreModel.get(12345, undefined, undefined, undefined, { ttl: 334455 }).then((en) => { expect(en).equal(null); gstore.config.errorOnEntityNotFound = true; done(); }); }); test('should *not* get value from cache when deactivated in options', () => { const key = GstoreModel.key(123); const value = { name: 'Michael' }; return gstore .cache!.keys.set(key, value) .then(() => GstoreModel.get(123, undefined, undefined, undefined, { cache: false }).then((response) => { assert.ok(ds.get.called); expect(response.entityData).contains(entity); ds.get.reset(); ds.get.resolves([entity]); }), ) .then(() => GstoreModel.get(123).then(() => { // Make sure we get from the cache // if no options config is passed assert.ok(!ds.get.called); }), ); }); test('should *not* get value from cache when global ttl === -1', () => { const originalConf = gstore.cache!.config.ttl; gstore.cache!.config.ttl = { ...gstore.cache!.config.ttl, keys: -1 }; const key = GstoreModel.key(123); return gstore.cache!.keys.set(key, {}).then(() => GstoreModel.get(123).then(() => { assert.ok(ds.get.called); gstore.cache!.config.ttl = originalConf; }), ); }); test('should get value from fetchHandler', () => GstoreModel.get(123).then((response) => { assert.ok(ds.get.called); const { args } = ds.get.getCall(0); expect(args[0].id).equal(123); expect(response.entityData).include(entity); })); test('should get key from fetchHandler and Dataloader', () => { const dataloader = gstore.createDataLoader(); const spy = sinon.stub(dataloader, 'load').resolves(entity); return GstoreModel.get(123, undefined, undefined, undefined, { dataloader }).then((res) => { expect(spy.called).equal(true); expect(res.name).equal('John'); }); }); test('should get multiple keys from fetchHandler and Dataloader', () => { const entity2: any = { name: 'Mick' }; entity2[ds.KEY] = GstoreModel.key(456); const dataloader = gstore.createDataLoader(); const spy = sinon.stub(dataloader, 'loadMany').resolves([entity, entity2]); return GstoreModel.get([123, 456], undefined, undefined, undefined, { dataloader }).then((res) => { expect(spy.called).equal(true); expect(res[0].name).equal('John'); expect(res[1].name).equal('Mick'); }); }); test('should get value from cache and call the fetchHandler **only** with keys not in the cache', () => { const key = GstoreModel.key(456); const cacheEntity: any = { name: 'John' }; cacheEntity[ds.KEY] = key; return gstore.cache!.keys.set(key, cacheEntity).then(() => GstoreModel.get([123, 456]).then((response) => { assert.ok(ds.get.called); const { args } = ds.get.getCall(0); expect(args[0][0].id).equal(123); expect(response.length).equal(2); }), ); }); test('should allow to chain populate() calls and then call the Model.populate() method', () => { const spy = sinon.spy(GstoreModel, '__populate'); const key = GstoreModel.key(123); const value = { foo: 'bar' }; return gstore.cache!.keys.set(key, value).then(() => GstoreModel.get(123) .populate('company', ['name', 'phone-number']) .then(() => { expect(spy.called).equal(true); const { args } = spy.getCall(0); expect(args[0]![0]).deep.equal([{ path: 'company', select: ['name', 'phone-number'] }]); (GstoreModel.__populate as any).restore(); }), ); }); }); }); describe('update()', () => { test('should run in a transaction', () => GstoreModel.update(123, {}).then(() => { expect(ds.transaction.called).equal(true); expect((transaction.run as any).called).equal(true); expect((transaction.commit as any).called).equal(true); })); test('should return an entity instance', () => GstoreModel.update(123, {}).then((entity) => { expect(entity instanceof GstoreEntity).equal(true); })); test('should first get the entity by Key', () => GstoreModel.update(123, {}).then(() => { expect((transaction.get as any).getCall(0).args[0].constructor.name).equal('Key'); expect((transaction.get as any).getCall(0).args[0].path[1]).equal(123); })); test('should not convert a string id with mix of number and alpha chars', () => GstoreModel.update('123:456', {}).then(() => { expect((transaction.get as any).getCall(0).args[0].name).equal('123:456'); })); test('should rollback if error while getting entity', () => { (transaction.get as any).restore(); const error = { code: 500, message: 'Houston we got a problem' }; sinon.stub(transaction, 'get').rejects(error); return GstoreModel.update(123, {}).catch((err) => { expect(err).deep.equal(error); expect((transaction.rollback as any).called).equal(true); expect((transaction.commit as any).called).equal(false); }); }); test('should return "ERR_ENTITY_NOT_FOUND" if entity not found', () => { (transaction.get as any).restore(); sinon.stub(transaction, 'get').resolves([]); return GstoreModel.update('keyname', {}).catch((err) => { expect(err.code).equal(ERROR_CODES.ERR_ENTITY_NOT_FOUND); }); }); test('should return error if any while saving', (done) => { (transaction.run as any).restore(); const error = { code: 500, message: 'Houston wee need you.' }; sinon.stub(transaction, 'run').rejects([error]); GstoreModel.update(123, {}).catch((err) => { expect(err).equal(error); done(); }); }); test('accept an ancestor path', () => { const ancestors = ['Parent', 'keyname']; return GstoreModel.update(123, {}, ancestors).then(() => { expect((transaction.get as any).getCall(0).args[0].path[0]).equal('Parent'); expect((transaction.get as any).getCall(0).args[0].path[1]).equal('keyname'); }); }); test('should allow a namespace', () => { const namespace = 'com.mydomain-dev'; return GstoreModel.update(123, {}, undefined, namespace).then(() => { expect((transaction.get as any).getCall(0).args[0].namespace).equal(namespace); }); }); test('should save and replace data', () => { const data = { name: 'Mick' }; return GstoreModel.update(123, data, undefined, undefined, undefined, { replace: true }).then((entity) => { expect(entity.entityData.name).equal('Mick'); expect(entity.entityData.lastname).equal(null); expect(entity.entityData.email).equal(null); }); }); test('should accept a DataLoader instance, add it to the entity created and clear the key', () => { const dataloader = gstore.createDataLoader(); const spy = sinon.spy(dataloader, 'clear'); return GstoreModel.update(123, {}, undefined, undefined, undefined, { dataloader }).then((entity) => { const keyToClear = spy.getCalls()[0].args[0]; expect(keyToClear.kind).equal('Blog'); expect(keyToClear.id).equal(123); expect(entity.dataloader).equal(dataloader); }); }); test('should merge the new data with the entity data', () => { const data = { name: 'Sebas', lastname: 'Snow', }; return GstoreModel.update(123, data, ['Parent', 'keyNameParent']).then((entity) => { expect(entity.entityData.name).equal('Sebas'); expect(entity.entityData.lastname).equal('Snow'); expect(entity.entityData.email).equal('john@snow.com'); }); }); test('should call save() on the transaction', () => { return GstoreModel.update(123, {}, undefined, undefined, transaction).then(() => { expect((transaction.save as any).called).equal(true); }); }); test('should return error and rollback transaction if not passing validation', () => GstoreModel.update(123, { unknown: 1 }).catch((err) => { assert.isDefined(err); expect((transaction.rollback as any).called).equal(true); })); test('should return error if not passing validation', () => GstoreModel.update(123, { unknown: 1 }, undefined, undefined, undefined, { replace: true }).catch((err) => { assert.isDefined(err); })); test('should run inside an *existing* transaction', () => GstoreModel.update(123, {}, undefined, undefined, transaction).then((entity) => { expect(ds.transaction.called).equal(false); expect((transaction.get as any).called).equal(true); expect((transaction.save as any).called).equal(true); expect(entity instanceof GstoreEntity).equal(true); })); test('should throw error if transaction passed is not instance of gcloud Transaction', () => // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore GstoreModel.update(123, {}, undefined, undefined, {}).catch((err) => { expect(err.message).equal('Transaction needs to be a gcloud Transaction'); })); describe('when cache is active', () => { beforeEach(() => { gstore.cache = gstoreWithCache.cache; }); afterEach(() => { // empty the cache gstore.cache!.reset(); delete gstore.cache; }); test('should call Model.clearCache() passing the key updated', () => { sinon.spy(GstoreModel, 'clearCache'); return GstoreModel.update(123, { name: 'Nuri' }, ['Parent', 'keyNameParent']).then((entity) => { assert.ok((GstoreModel.clearCache as any).called); expect((GstoreModel.clearCache as any).getCall(0).args[0].id).equal(123); expect(entity.name).equal('Nuri'); (GstoreModel.clearCache as any).restore(); }); }); test('on error when clearing the cache, should add the entityUpdated on the error', (done) => { const err = new Error('Houston something bad happened'); sinon.stub(gstore.cache!.queries, 'clearQueriesByKind').rejects(err); GstoreModel.update(123, { name: 'Nuri' }).catch((e) => { expect(e.__entityUpdated.name).equal('Nuri'); expect(e.__cacheError).equal(err); (gstore.cache!.queries.clearQueriesByKind as any).restore(); done(); }); }); }); }); describe('delete()', () => { beforeEach(() => { sinon.stub(ds, 'delete').resolves([{ indexUpdates: 3 }]); sinon.stub(transaction, 'delete').callsFake(() => true); }); afterEach(() => { ds.delete.restore(); (transaction.delete as any).restore(); }); test('should call ds.delete with correct Key (int id)', () => GstoreModel.delete(123).then((response) => { expect(ds.delete.called).equal(true); expect(ds.delete.getCall(0).args[0].constructor.name).equal('Key'); expect(response.success).equal(true); })); test('should call ds.delete with correct Key (string id)', () => GstoreModel.delete('keyName').then((response) => { expect(ds.delete.called).equal(true); expect(ds.delete.getCall(0).args[0].path[1]).equal('keyName'); expect(response.success).equal(true); })); test('not converting string id with mix of number and alpha chars', () => GstoreModel.delete('123:456').then(() => { expect(ds.delete.getCall(0).args[0].name).equal('123:456'); })); test('should allow array of ids', () => GstoreModel.delete([22, 69]).then(() => { expect(is.array(ds.delete.getCall(0).args[0])).equal(true); })); test('should allow ancestors', () => GstoreModel.delete(123, ['Parent', 123]).then(() => { const key = ds.delete.getCall(0).args[0]; expect(key.parent.kind).equal('Parent'); expect(key.parent.id).equal(123); })); test('should allow a namespace', () => { const namespace = 'com.mydomain-dev'; return GstoreModel.delete('keyName', undefined, namespace).then(() => { const key = ds.delete.getCall(0).args[0]; expect(key.namespace).equal(namespace); }); }); test('should delete entity in a transaction', () => GstoreModel.delete(123, undefined, undefined, transaction).then(() => { expect((transaction.delete as any).called).equal(true); expect((transaction.delete as any).getCall(0).args[0].path[1]).equal(123); })); test('should deal with empty responses', () => { ds.delete.restore(); sinon.stub(ds, 'delete').resolves(); return GstoreModel.delete(1).then((response) => { assert.isDefined(response.key); }); }); test('should delete entity in a transaction in sync', () => { GstoreModel.delete(123, undefined, undefined, transaction); expect((transaction.delete as any).called).equal(true); expect((transaction.delete as any).getCall(0).args[0].path[1]).equal(123); }); test('should throw error if transaction passed is not instance of gcloud Transaction', () => // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore GstoreModel.delete(123, undefined, undefined, {}).catch((err) => { expect(err.message).equal('Transaction needs to be a gcloud Transaction'); })); test('should set "success" to false if no entity deleted', () => { ds.delete.restore(); sinon.stub(ds, 'delete').resolves([{ indexUpdates: 0 }]); return GstoreModel.delete(123).then((response) => { expect(response.success).equal(false); }); }); test('should not set success neither apiRes', () => { ds.delete.restore(); sinon.stub(ds, 'delete').resolves([{}]); return GstoreModel.delete(123).then((response) => { assert.isUndefined(response.success); }); }); test('should handle errors', () => { ds.delete.restore(); const error = { code: 500, message: 'We got a problem Houston' }; sinon.stub(ds, 'delete').rejects(error); return GstoreModel.delete(123).catch((err) => { expect(err).equal(error); }); }); test('should call pre hooks', () => { const spy = { beforeSave: (): Promise<void> => Promise.resolve(), }; sinon.spy(spy, 'beforeSave'); schema.pre('delete', spy.beforeSave); GstoreModel = gstore.model('Blog-1', schema); return GstoreModel.delete(123).then(() => { expect((spy.beforeSave as any).calledBefore(ds.delete)).equal(true); }); }); test('pre hook should override id passed', () => { const spy = { beforeSave: (): Promise<any> => Promise.resolve({ __override: [666] }), }; sinon.spy(spy, 'beforeSave'); schema.pre('delete', spy.beforeSave); GstoreModel = gstore.model('Blog-2', schema); return GstoreModel.delete(123).then(() => { expect(ds.delete.getCall(0).args[0].id).equal(666); }); }); test('should set "pre" hook scope to entity being deleted (1)', (done) => { schema.pre('delete', function preDelete(this: any) { expect(this instanceof GstoreEntity).equal(true); done(); return Promise.resolve(); }); GstoreModel = gstore.model('Blog-3', schema); GstoreModel.delete(123); }); test('should set "pre" hook scope to entity being deleted (2)', () => { schema.pre('delete', function preDelete(this: any) { expect(this.entityKey.id).equal(777); return Promise.resolve(); }); GstoreModel = gstore.model('Blog-4', schema); // ... passing a datastore.key return GstoreModel.delete(undefined, undefined, undefined, undefined, GstoreModel.key(777)); }); test('should NOT set "pre" hook scope if deleting an array of ids', () => { let scope: any; schema.pre('delete', function preDelete(this: any) { scope = this; return Promise.resolve(); }); GstoreModel = gstore.model('Blog-5', schema); return GstoreModel.delete([123, 456]).then(() => { expect(scope).equal(null); }); }); test('should call post hooks', () => { const spy = { afterDelete: (): Promise<void> => Promise.resolve(), }; sinon.spy(spy, 'afterDelete'); schema.post('delete', spy.afterDelete); GstoreModel = gstore.model('Blog-6', schema); return GstoreModel.delete(123).then(() => { expect((spy.afterDelete as any).called).equal(true); }); }); test('should pass key deleted to post hooks and set the scope to the entity deleted', (done) => { schema.post('delete', function postDeleteHook(this: any, { key }) { expect(key.constructor.name).equal('Key'); expect(key.id).equal(123); expect(this instanceof GstoreEntity).equal(true); expect(this.entityKey).equal(key); done(); return Promise.resolve(); }); GstoreModel = gstore.model('Blog-7', schema); GstoreModel.delete(123); }); test('should pass array of keys deleted to post hooks', () => { const ids = [123, 456]; schema.post('delete', (response) => { expect(response.key.length).equal(ids.length); expect(response.key[1].id).equal(456); return Promise.resolve(); }); GstoreModel = gstore.model('Blog-8', schema); return GstoreModel.delete(ids).then(() => undefined); }); test('transaction.execPostHooks() should call post hooks', () => { const spy = { afterDelete: (): Promise<void> => Promise.resolve(), }; sinon.spy(spy, 'afterDelete'); schema = new Schema({ name: { type: String } }); schema.post('delete', spy.afterDelete); GstoreModel = gstore.model('Blog-9', schema); return GstoreModel.delete(123, undefined, undefined, transaction).then(() => { transaction.execPostHooks().then(() => { expect((spy.afterDelete as any).called).equal(true); expect((spy.afterDelete as any).calledOnce).equal(true); }); }); }); test('should accept a DataLoader instance and clear the cached key after deleting', () => { const dataloader = gstore.createDataLoader(); const spy = sinon.spy(dataloader, 'clear'); return GstoreModel.delete(123, undefined, undefined, undefined, undefined, { dataloader }).then(() => { const keyToClear = spy.getCalls()[0].args[0]; expect(keyToClear.kind).equal('Blog'); expect(keyToClear.id).equal(123); }); }); describe('when cache is active', () => { beforeEach(() => { gstore.cache = gstoreWithCache.cache; }); afterEach(() => { // empty the cache gstore.cache!.reset(); delete gstore.cache; }); test('should call Model.clearCache() passing the key deleted', () => { sinon.spy(GstoreModel, 'clearCache'); return GstoreModel.delete(445566).then((response) => { assert.ok((GstoreModel.clearCache as any).called); expect((GstoreModel.clearCache as any).getCall(0).args[0].id).equal(445566); expect(response.success).equal(true); (GstoreModel.clearCache as any).restore(); }); }); test('on error when clearing the cache, should add the entityUpdated on the error', (done) => { const err = new Error('Houston something bad happened'); sinon.stub(gstore.cache!.queries, 'clearQueriesByKind').rejects(err); GstoreModel.delete(1234).catch((e) => { expect(e.__response.success).equal(true); expect(e.__cacheError).equal(err); (gstore.cache!.queries.clearQueriesByKind as any).restore(); done(); }); }); }); }); describe('deleteAll()', () => { let queryMock: any; beforeEach(() => { queryMock = new Query(ds, { entities: mockEntities }); sinon.spy(queryMock, 'run'); sinon.spy(queryMock, 'hasAncestor'); sinon.stub(ds, 'createQuery').callsFake(() => queryMock); sinon.stub(ds, 'delete').callsFake(() => { // We need to update our mock response of the Query // to not enter in an infinite loop as we recursivly query // until there are no more entities ds.createQuery.restore(); sinon.stub(ds, 'createQuery').callsFake(() => new Query(ds, { entities: [] })); return Promise.resolve([{ indexUpdates: 3 }]); }); sinon.spy(GstoreModel, 'query'); }); afterEach(() => { ds.delete.restore(); ds.createQuery.restore(); if (queryMock.run.restore) { queryMock.run.restore(); } if (queryMock.hasAncestor.restore) { queryMock.hasAncestor.restore(); } }); test('should get all entities through Query', () => GstoreModel.deleteAll().then(() => { expect((GstoreModel.query as any).called).equal(true); expect((GstoreModel.query as any).getCall(0).args.length).equal(1); })); test('should catch error if could not fetch entities', () => { const error = { code: 500, message: 'Something went wrong' }; queryMock.run.restore(); sinon.stub(queryMock, 'run').rejects(error); return GstoreModel.deleteAll().catch((err) => { expect(err).equal(error); }); }); test('if pre hooks, should call "delete" on all entities found (in series)', () => { schema = new Schema({}); const spies = { pre: (): Promise<void> => Promise.resolve(), }; sinon.spy(spies, 'pre'); schema.pre('delete', spies.pre); GstoreModel = gstore.model('NewBlog', schema); sinon.spy(GstoreModel, 'delete'); return GstoreModel.deleteAll().then(() => { expect((spies.pre as any).callCount).equal(mockEntities.length); expect((GstoreModel.delete as any).callCount).equal(mockEntities.length); expect((GstoreModel.delete as any).getCall(0).args.length).equal(5); expect((GstoreModel.delete as any).getCall(0).args[4].constructor.name).equal('Key'); }); }); test('if post hooks, should call "delete" on all entities found (in series)', () => { schema = new Schema({}); const spies = { post: (): Promise<void> => Promise.resolve(), }; sinon.spy(spies, 'post'); schema.post('delete', spies.post); GstoreModel = gstore.model('NewBlog', schema); sinon.spy(GstoreModel, 'delete'); return GstoreModel.deleteAll().then(() => { expect((spies.post as any).callCount).equal(mockEntities.length); expect((GstoreModel.delete as any).callCount).equal(2); }); }); test('if NO hooks, should call delete passing an array of keys', () => { sinon.spy(GstoreModel, 'delete'); return GstoreModel.deleteAll().then(() => { expect((GstoreModel.delete as any).callCount).equal(1); const { args } = (GstoreModel.delete as any).getCall(0); expect(is.array(args[4])).equal(true); expect(args[4]).deep.equal([mockEntities[0][ds.KEY], mockEntities[1][ds.KEY]]); (GstoreModel.delete as any).restore(); }); }); test('should call with ancestors', () => { const ancestors = ['Parent', 'keyname']; return GstoreModel.deleteAll(ancestors).then(() => { expect(queryMock.hasAncestor.calledOnce).equal(true); expect(queryMock.ancestors.path).deep.equal(ancestors); }); }); test('should call with namespace', () => { const namespace = 'com.new-domain.dev'; return GstoreModel.deleteAll(undefined, namespace).then(() => { expect(ds.createQuery.getCall(0).args[0]).equal(namespace); }); }); test('should return success:true if all ok', () => GstoreModel.deleteAll().then((response) => { expect(response.success).equal(true); })); test('should return error if any while deleting', () => { const error = { code: 500, message: 'Could not delete' }; sinon.stub(GstoreModel, 'delete').rejects(error); return GstoreModel.deleteAll().catch((err) => { expect(err).equal(error); }); }); test('should delete entites by batches of 500', (done) => { ds.createQuery.restore(); const entities = []; const entity: any = { name: 'Mick', lastname: 'Jagger' }; entity[ds.KEY] = ds.key(['BlogPost', 'keyname']); for (let i = 0; i < 1200; i += 1) { entities.push(entity); } const queryMock2 = new Query(ds, { entities }); sinon.stub(ds, 'createQuery').callsFake(() => queryMock2); GstoreModel.deleteAll().then(() => { expect(false).equal(false); done(); }); }); describe('when cache is active', () => { beforeEach(() => { gstore.cache = gstoreWithCache.cache; }); afterEach(() => { // empty the cache gstore.cache!.reset(); delete gstore.cache; }); test('should delete all the keys from the cache and clear the Queries', (done) => { ds.createQuery.restore(); const entities = []; const entity: any = { name: 'Mick', lastname: 'Jagger' }; entity[ds.KEY] = ds.key(['BlogPost', 'keyname']); for (let i = 0; i < 1200; i += 1) { entities.push(entity); } queryMock = new Query(ds, { entities }); sinon.stub(ds, 'createQuery').callsFake( () => // Check queryMock, ); sinon.spy(gstore.cache!.keys, 'del'); sinon.spy(gstore.cache!.queries, 'clearQueriesByKind'); GstoreModel.deleteAll().then(() => { expect((gstore.cache!.queries.clearQueriesByKind as any).callCount).equal(1); expect((gstore.cache!.keys.del as any).callCount).equal(3); const keys1 = (gstore.cache!.keys.del as any).getCall(0).args; const keys2 = (gstore.cache!.keys.del as any).getCall(1).args; const keys3 = (gstore.cache!.keys.del as any).getCall(2).args; expect(keys1.length + keys2.length + keys3.length).equal(1200); (gstore.cache!.keys.del as any).restore(); (gstore.cache!.queries.clearQueriesByKind as any).restore(); done(); }); }); }); }); describe('excludeFromIndexes', () => { test('should add properties to schema as optional', () => { const arr = ['newProp', 'url']; GstoreModel.excludeFromIndexes(arr); expect(GstoreModel.schema.excludedFromIndexes).deep.equal({ lastname: ['lastname'], age: ['age'], newProp: ['newProp'], url: ['url'], tags: [], prefs: [], }); expect((schema.path('newProp')! as SchemaPathDefinition).optional).equal(true); }); test('should only modifiy excludeFromIndexes on properties that already exist', () => { const prop = 'lastname'; GstoreModel.excludeFromIndexes(prop); expect(GstoreModel.schema.excludedFromIndexes).deep.equal({ lastname: ['lastname'], age: ['age'], tags: [], prefs: [], }); assert.isUndefined((schema.path('lastname')! as SchemaPathDefinition).optional); expect((schema.path('lastname')! as SchemaPathDefinition).excludeFromIndexes).equal(true); }); }); describe('hooksTransaction()', () => { beforeEach(() => { delete transaction.hooks; }); test('should add hooks to a transaction', () => { GstoreModel.__hooksTransaction(transaction, [(): any => Promise.resolve(), (): any => Promise.resolve()]); assert.isDefined(transaction.hooks.post); expect(transaction.hooks.post.length).equal(2); assert.isDefined(transaction.execPostHooks); }); test('should not override previous hooks on transaction', () => { const fn = (): void => undefined; transaction.hooks = { post: [fn], }; GstoreModel.__hooksTransaction(transaction, [(): any => Promise.resolve()]); expect(transaction.hooks.post[0]).equal(fn); }); test('--> execPostHooks() should chain each Promised hook from transaction', () => { const postHook1 = sinon.stub().resolves(1); const postHook2 = sinon.stub().resolves(2); GstoreModel.__hooksTransaction(transaction, [postHook1, postHook2]); return transaction.execPostHooks().then((result: any) => { expect(postHook1.called).equal(true); expect(postHook2.called).equal(true); expect(result).equal(2); }); }); test('--> execPostHooks() should resolve if no hooks', () => { GstoreModel.__hooksTransaction(transaction, []); delete transaction.hooks.post; return transaction.execPostHooks().then(() => { expect(true).equal(true); }); }); }); describe('clearCache', () => { beforeEach(() => { gstore.cache = gstoreWithCache.cache; }); afterEach(() => { // empty the cache gstore.cache!.reset(); if ((gstore.cache!.queries.clearQueriesByKind as any).restore) { (gstore.cache!.queries.clearQueriesByKind as any).restore(); } delete gstore.cache; }); test('should delete the cache', () => { sinon.spy(gstore.cache!.keys, 'del'); return GstoreModel.clearCache([GstoreModel.key(112233), GstoreModel.key(778899)]).then(() => { assert.ok((gstore.cache!.keys.del as any).called); expect((gstore.cache!.keys.del as any).getCall(0).args[0].id).equal(112233); expect((gstore.cache!.keys.del as any).getCall(0).args[1].id).equal(778899); (gstore.cache!.keys.del as any).restore(); }); }); test('should clear all queries linked to its entity kind', () => { sinon.spy(gstore.cache!.queries, 'clearQueriesByKind'); return GstoreModel.clearCache().then(() => { assert.ok((gstore.cache!.queries.clearQueriesByKind as any).called); const { args } = (gstore.cache!.queries.clearQueriesByKind as any).getCall(0); expect(args[0]).equal(GstoreModel.entityKind); }); }); test('should bubble up errors', (done) => { const err = new Error('Houston something bad happened'); sinon.stub(gstore.cache!.queries, 'clearQueriesByKind').rejects(err); GstoreModel.clearCache(GstoreModel.key(123)).catch((e) => { expect(e).equal(err); done(); }); }); test('should not throw error if Redis is not present', () => { const err: any = new Error('Redis store not founc'); err.code = 'ERR_NO_REDIS'; sinon.stub(gstore.cache!.queries, 'clearQueriesByKind').rejects(err); GstoreModel.clearCache(GstoreModel.key(123)).then((res) => { expect(res.success).equal(true); }); }); }); describe('populate()', () => { let entity; let key0: EntityKey; let key1: EntityKey; let key2: EntityKey; let fetchData1: any; let fetchData2: any; let refs: any; let entities: any; beforeEach(() => { gstore.connect(ds); schema = new Schema({ name: { type: String }, ref: { type: Schema.Types.Key }, }); GstoreModel = gstore.model('ModelTests-populate', schema); key0 = GstoreModel.key(123); key1 = GstoreModel.key(456); key2 = GstoreModel.key(789); entity = new GstoreModel({ name: 'Level0', ref: key1 }, undefined, undefined, undefined, key0); fetchData1 = { name: 'Level1', ref: key2 }; fetchData1[ds.KEY] = key1; fetchData2 = { name: 'Level2' }; fetchData2[ds.KEY] = key2; refs = [ [{ path: 'ref', select: ['*'] }], // level 0 [{ path: 'ref.ref', select: ['*'] }], // level 1 ]; entities = [entity]; const stub = sinon.stub(ds, 'get'); stub.onCall(0).returns(Promise.resolve([fetchData1])); stub.onCall(1).returns(Promise.resolve([fetchData2])); }); afterEach(() => { ds.get.restore(); }); test('should recursively fetch the keys at each level of the entityData tree', () => GstoreModel.__populate(refs)(entities).then(({ 0: { entityData } }: any) => { expect(entityData.ref.id).equal(456); expect(entityData.ref.name).equal('Level1'); expect(entityData.ref.ref.id).equal(789); expect(entityData.ref.ref.name).equal('Level2'); expect(ds.get.getCalls().length).equal(2); })); describe('when cache is active', () => { beforeEach(() => { gstore.cache = gstoreWithCache.cache; }); afterEach(() => { // empty the cache gstore.cache!.reset(); delete gstore.cache; }); test('should get the keys from the cache and not fetch from the Datastore', () => gstore.cache!.keys.mset(key1, fetchData1, key2, fetchData2).then(() => GstoreModel.__populate(refs)(entities).then(() => { expect(ds.get.getCalls().length).equal(0); }), )); }); }); });
the_stack
import { flatbuffers } from 'flatbuffers'; // automatically generated by the FlatBuffers compiler, do not modify /** * @enum {number} */ export enum HttpCommand{ NONE= 0, HttpQuery= 1, HttpResultSet= 2, HttpError= 3 }; /** * @constructor */ export class HttpMessage { bb: flatbuffers.ByteBuffer|null = null; bb_pos:number = 0; /** * @param number i * @param flatbuffers.ByteBuffer bb * @returns HttpMessage */ __init(i:number, bb:flatbuffers.ByteBuffer):HttpMessage { this.bb_pos = i; this.bb = bb; return this; }; /** * @param flatbuffers.ByteBuffer bb * @param HttpMessage= obj * @returns HttpMessage */ static getRootAsHttpMessage(bb:flatbuffers.ByteBuffer, obj?:HttpMessage):HttpMessage { return (obj || new HttpMessage()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param flatbuffers.ByteBuffer bb * @param HttpMessage= obj * @returns HttpMessage */ static getSizePrefixedRootAsHttpMessage(bb:flatbuffers.ByteBuffer, obj?:HttpMessage):HttpMessage { bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); return (obj || new HttpMessage()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @returns number */ messageId():number { var offset = this.bb!.__offset(this.bb_pos, 4); return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0; }; /** * @returns HttpCommand */ commandType():HttpCommand { var offset = this.bb!.__offset(this.bb_pos, 6); return offset ? /** */ (this.bb!.readUint8(this.bb_pos + offset)) : HttpCommand.NONE; }; /** * @param flatbuffers.Table obj * @returns ?flatbuffers.Table */ command<T extends flatbuffers.Table>(obj:T):T|null { var offset = this.bb!.__offset(this.bb_pos, 8); return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null; }; /** * @param flatbuffers.Builder builder */ static startHttpMessage(builder:flatbuffers.Builder) { builder.startObject(3); }; /** * @param flatbuffers.Builder builder * @param number messageId */ static addMessageId(builder:flatbuffers.Builder, messageId:number) { builder.addFieldInt32(0, messageId, 0); }; /** * @param flatbuffers.Builder builder * @param HttpCommand commandType */ static addCommandType(builder:flatbuffers.Builder, commandType:HttpCommand) { builder.addFieldInt8(1, commandType, HttpCommand.NONE); }; /** * @param flatbuffers.Builder builder * @param flatbuffers.Offset commandOffset */ static addCommand(builder:flatbuffers.Builder, commandOffset:flatbuffers.Offset) { builder.addFieldOffset(2, commandOffset, 0); }; /** * @param flatbuffers.Builder builder * @returns flatbuffers.Offset */ static endHttpMessage(builder:flatbuffers.Builder):flatbuffers.Offset { var offset = builder.endObject(); return offset; }; /** * @param flatbuffers.Builder builder * @param flatbuffers.Offset offset */ static finishHttpMessageBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { builder.finish(offset); }; /** * @param flatbuffers.Builder builder * @param flatbuffers.Offset offset */ static finishSizePrefixedHttpMessageBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { builder.finish(offset, undefined, true); }; static createHttpMessage(builder:flatbuffers.Builder, messageId:number, commandType:HttpCommand, commandOffset:flatbuffers.Offset):flatbuffers.Offset { HttpMessage.startHttpMessage(builder); HttpMessage.addMessageId(builder, messageId); HttpMessage.addCommandType(builder, commandType); HttpMessage.addCommand(builder, commandOffset); return HttpMessage.endHttpMessage(builder); } } /** * @constructor */ export class HttpQuery { bb: flatbuffers.ByteBuffer|null = null; bb_pos:number = 0; /** * @param number i * @param flatbuffers.ByteBuffer bb * @returns HttpQuery */ __init(i:number, bb:flatbuffers.ByteBuffer):HttpQuery { this.bb_pos = i; this.bb = bb; return this; }; /** * @param flatbuffers.ByteBuffer bb * @param HttpQuery= obj * @returns HttpQuery */ static getRootAsHttpQuery(bb:flatbuffers.ByteBuffer, obj?:HttpQuery):HttpQuery { return (obj || new HttpQuery()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param flatbuffers.ByteBuffer bb * @param HttpQuery= obj * @returns HttpQuery */ static getSizePrefixedRootAsHttpQuery(bb:flatbuffers.ByteBuffer, obj?:HttpQuery):HttpQuery { bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); return (obj || new HttpQuery()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param flatbuffers.Encoding= optionalEncoding * @returns string|Uint8Array|null */ query():string|null query(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null query(optionalEncoding?:any):string|Uint8Array|null { var offset = this.bb!.__offset(this.bb_pos, 4); return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; }; /** * @param flatbuffers.Builder builder */ static startHttpQuery(builder:flatbuffers.Builder) { builder.startObject(1); }; /** * @param flatbuffers.Builder builder * @param flatbuffers.Offset queryOffset */ static addQuery(builder:flatbuffers.Builder, queryOffset:flatbuffers.Offset) { builder.addFieldOffset(0, queryOffset, 0); }; /** * @param flatbuffers.Builder builder * @returns flatbuffers.Offset */ static endHttpQuery(builder:flatbuffers.Builder):flatbuffers.Offset { var offset = builder.endObject(); return offset; }; static createHttpQuery(builder:flatbuffers.Builder, queryOffset:flatbuffers.Offset):flatbuffers.Offset { HttpQuery.startHttpQuery(builder); HttpQuery.addQuery(builder, queryOffset); return HttpQuery.endHttpQuery(builder); } } /** * @constructor */ export class HttpError { bb: flatbuffers.ByteBuffer|null = null; bb_pos:number = 0; /** * @param number i * @param flatbuffers.ByteBuffer bb * @returns HttpError */ __init(i:number, bb:flatbuffers.ByteBuffer):HttpError { this.bb_pos = i; this.bb = bb; return this; }; /** * @param flatbuffers.ByteBuffer bb * @param HttpError= obj * @returns HttpError */ static getRootAsHttpError(bb:flatbuffers.ByteBuffer, obj?:HttpError):HttpError { return (obj || new HttpError()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param flatbuffers.ByteBuffer bb * @param HttpError= obj * @returns HttpError */ static getSizePrefixedRootAsHttpError(bb:flatbuffers.ByteBuffer, obj?:HttpError):HttpError { bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); return (obj || new HttpError()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param flatbuffers.Encoding= optionalEncoding * @returns string|Uint8Array|null */ error():string|null error(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null error(optionalEncoding?:any):string|Uint8Array|null { var offset = this.bb!.__offset(this.bb_pos, 4); return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; }; /** * @param flatbuffers.Builder builder */ static startHttpError(builder:flatbuffers.Builder) { builder.startObject(1); }; /** * @param flatbuffers.Builder builder * @param flatbuffers.Offset errorOffset */ static addError(builder:flatbuffers.Builder, errorOffset:flatbuffers.Offset) { builder.addFieldOffset(0, errorOffset, 0); }; /** * @param flatbuffers.Builder builder * @returns flatbuffers.Offset */ static endHttpError(builder:flatbuffers.Builder):flatbuffers.Offset { var offset = builder.endObject(); return offset; }; static createHttpError(builder:flatbuffers.Builder, errorOffset:flatbuffers.Offset):flatbuffers.Offset { HttpError.startHttpError(builder); HttpError.addError(builder, errorOffset); return HttpError.endHttpError(builder); } } /** * @constructor */ export class HttpResultSet { bb: flatbuffers.ByteBuffer|null = null; bb_pos:number = 0; /** * @param number i * @param flatbuffers.ByteBuffer bb * @returns HttpResultSet */ __init(i:number, bb:flatbuffers.ByteBuffer):HttpResultSet { this.bb_pos = i; this.bb = bb; return this; }; /** * @param flatbuffers.ByteBuffer bb * @param HttpResultSet= obj * @returns HttpResultSet */ static getRootAsHttpResultSet(bb:flatbuffers.ByteBuffer, obj?:HttpResultSet):HttpResultSet { return (obj || new HttpResultSet()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param flatbuffers.ByteBuffer bb * @param HttpResultSet= obj * @returns HttpResultSet */ static getSizePrefixedRootAsHttpResultSet(bb:flatbuffers.ByteBuffer, obj?:HttpResultSet):HttpResultSet { bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); return (obj || new HttpResultSet()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param number index * @param flatbuffers.Encoding= optionalEncoding * @returns string|Uint8Array */ columns(index: number):string columns(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array columns(index: number,optionalEncoding?:any):string|Uint8Array|null { var offset = this.bb!.__offset(this.bb_pos, 4); return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; }; /** * @returns number */ columnsLength():number { var offset = this.bb!.__offset(this.bb_pos, 4); return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; }; /** * @param number index * @param HttpRow= obj * @returns HttpRow */ rows(index: number, obj?:HttpRow):HttpRow|null { var offset = this.bb!.__offset(this.bb_pos, 6); return offset ? (obj || new HttpRow()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; }; /** * @returns number */ rowsLength():number { var offset = this.bb!.__offset(this.bb_pos, 6); return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; }; /** * @param flatbuffers.Builder builder */ static startHttpResultSet(builder:flatbuffers.Builder) { builder.startObject(2); }; /** * @param flatbuffers.Builder builder * @param flatbuffers.Offset columnsOffset */ static addColumns(builder:flatbuffers.Builder, columnsOffset:flatbuffers.Offset) { builder.addFieldOffset(0, columnsOffset, 0); }; /** * @param flatbuffers.Builder builder * @param Array.<flatbuffers.Offset> data * @returns flatbuffers.Offset */ static createColumnsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { builder.startVector(4, data.length, 4); for (var i = data.length - 1; i >= 0; i--) { builder.addOffset(data[i]); } return builder.endVector(); }; /** * @param flatbuffers.Builder builder * @param number numElems */ static startColumnsVector(builder:flatbuffers.Builder, numElems:number) { builder.startVector(4, numElems, 4); }; /** * @param flatbuffers.Builder builder * @param flatbuffers.Offset rowsOffset */ static addRows(builder:flatbuffers.Builder, rowsOffset:flatbuffers.Offset) { builder.addFieldOffset(1, rowsOffset, 0); }; /** * @param flatbuffers.Builder builder * @param Array.<flatbuffers.Offset> data * @returns flatbuffers.Offset */ static createRowsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { builder.startVector(4, data.length, 4); for (var i = data.length - 1; i >= 0; i--) { builder.addOffset(data[i]); } return builder.endVector(); }; /** * @param flatbuffers.Builder builder * @param number numElems */ static startRowsVector(builder:flatbuffers.Builder, numElems:number) { builder.startVector(4, numElems, 4); }; /** * @param flatbuffers.Builder builder * @returns flatbuffers.Offset */ static endHttpResultSet(builder:flatbuffers.Builder):flatbuffers.Offset { var offset = builder.endObject(); return offset; }; static createHttpResultSet(builder:flatbuffers.Builder, columnsOffset:flatbuffers.Offset, rowsOffset:flatbuffers.Offset):flatbuffers.Offset { HttpResultSet.startHttpResultSet(builder); HttpResultSet.addColumns(builder, columnsOffset); HttpResultSet.addRows(builder, rowsOffset); return HttpResultSet.endHttpResultSet(builder); } } /** * @constructor */ export class HttpRow { bb: flatbuffers.ByteBuffer|null = null; bb_pos:number = 0; /** * @param number i * @param flatbuffers.ByteBuffer bb * @returns HttpRow */ __init(i:number, bb:flatbuffers.ByteBuffer):HttpRow { this.bb_pos = i; this.bb = bb; return this; }; /** * @param flatbuffers.ByteBuffer bb * @param HttpRow= obj * @returns HttpRow */ static getRootAsHttpRow(bb:flatbuffers.ByteBuffer, obj?:HttpRow):HttpRow { return (obj || new HttpRow()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param flatbuffers.ByteBuffer bb * @param HttpRow= obj * @returns HttpRow */ static getSizePrefixedRootAsHttpRow(bb:flatbuffers.ByteBuffer, obj?:HttpRow):HttpRow { bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); return (obj || new HttpRow()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param number index * @param HttpColumnValue= obj * @returns HttpColumnValue */ values(index: number, obj?:HttpColumnValue):HttpColumnValue|null { var offset = this.bb!.__offset(this.bb_pos, 4); return offset ? (obj || new HttpColumnValue()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; }; /** * @returns number */ valuesLength():number { var offset = this.bb!.__offset(this.bb_pos, 4); return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; }; /** * @param flatbuffers.Builder builder */ static startHttpRow(builder:flatbuffers.Builder) { builder.startObject(1); }; /** * @param flatbuffers.Builder builder * @param flatbuffers.Offset valuesOffset */ static addValues(builder:flatbuffers.Builder, valuesOffset:flatbuffers.Offset) { builder.addFieldOffset(0, valuesOffset, 0); }; /** * @param flatbuffers.Builder builder * @param Array.<flatbuffers.Offset> data * @returns flatbuffers.Offset */ static createValuesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { builder.startVector(4, data.length, 4); for (var i = data.length - 1; i >= 0; i--) { builder.addOffset(data[i]); } return builder.endVector(); }; /** * @param flatbuffers.Builder builder * @param number numElems */ static startValuesVector(builder:flatbuffers.Builder, numElems:number) { builder.startVector(4, numElems, 4); }; /** * @param flatbuffers.Builder builder * @returns flatbuffers.Offset */ static endHttpRow(builder:flatbuffers.Builder):flatbuffers.Offset { var offset = builder.endObject(); return offset; }; static createHttpRow(builder:flatbuffers.Builder, valuesOffset:flatbuffers.Offset):flatbuffers.Offset { HttpRow.startHttpRow(builder); HttpRow.addValues(builder, valuesOffset); return HttpRow.endHttpRow(builder); } } /** * @constructor */ export class HttpColumnValue { bb: flatbuffers.ByteBuffer|null = null; bb_pos:number = 0; /** * @param number i * @param flatbuffers.ByteBuffer bb * @returns HttpColumnValue */ __init(i:number, bb:flatbuffers.ByteBuffer):HttpColumnValue { this.bb_pos = i; this.bb = bb; return this; }; /** * @param flatbuffers.ByteBuffer bb * @param HttpColumnValue= obj * @returns HttpColumnValue */ static getRootAsHttpColumnValue(bb:flatbuffers.ByteBuffer, obj?:HttpColumnValue):HttpColumnValue { return (obj || new HttpColumnValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param flatbuffers.ByteBuffer bb * @param HttpColumnValue= obj * @returns HttpColumnValue */ static getSizePrefixedRootAsHttpColumnValue(bb:flatbuffers.ByteBuffer, obj?:HttpColumnValue):HttpColumnValue { bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); return (obj || new HttpColumnValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); }; /** * @param flatbuffers.Encoding= optionalEncoding * @returns string|Uint8Array|null */ stringValue():string|null stringValue(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null stringValue(optionalEncoding?:any):string|Uint8Array|null { var offset = this.bb!.__offset(this.bb_pos, 4); return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; }; /** * @param flatbuffers.Builder builder */ static startHttpColumnValue(builder:flatbuffers.Builder) { builder.startObject(1); }; /** * @param flatbuffers.Builder builder * @param flatbuffers.Offset stringValueOffset */ static addStringValue(builder:flatbuffers.Builder, stringValueOffset:flatbuffers.Offset) { builder.addFieldOffset(0, stringValueOffset, 0); }; /** * @param flatbuffers.Builder builder * @returns flatbuffers.Offset */ static endHttpColumnValue(builder:flatbuffers.Builder):flatbuffers.Offset { var offset = builder.endObject(); return offset; }; static createHttpColumnValue(builder:flatbuffers.Builder, stringValueOffset:flatbuffers.Offset):flatbuffers.Offset { HttpColumnValue.startHttpColumnValue(builder); HttpColumnValue.addStringValue(builder, stringValueOffset); return HttpColumnValue.endHttpColumnValue(builder); } }
the_stack
import { CSSObject } from '@emotion/react'; import { identityType } from '../utils'; import { palette as basePalette } from './colors'; /** * Global Tokens */ const typography = { fontFamily: { monospace: 'Consolas, Menlo, Monaco, "Andale Mono", "Ubuntu Mono", monospace', body: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif', heading: 'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif', }, fontSize: { xxxsmall: '0.5rem', xxsmall: '0.6rem', xsmall: '0.75rem', small: '0.875rem', medium: '1rem', large: '1.125rem', xlarge: '1.25rem', xxlarge: '1.5rem', xxxlarge: '1.875rem', xxxxlarge: '2.25rem', xxxxxlarge: '3rem', xxxxxxlarge: '4rem', }, fontWeight: { light: 300, regular: 400, medium: 500, semibold: 600, bold: 700, heavy: 800, }, leading: { tighter: 1, tight: 1.2, base: 1.4, loose: 1.6, looser: 1.8, }, tracking: { tighter: '-0.02em', tight: '-0.01em', base: '0em', loose: '0.01em', looser: '0.02em', }, }; const palette = { black: '#000000', white: '#ffffff', current: 'currentColor', transparent: 'transparent', neutral100: '#fafbfc', neutral200: '#eff3f6', neutral300: '#e1e5e9', neutral400: '#ccd1d5', neutral500: '#b1b5b9', neutral600: '#9ca3af', neutral700: '#6b7280', neutral800: '#374151', neutral900: '#111827', ...basePalette, }; const breakpoints = { small: 576, medium: 768, large: 992, xlarge: 1200, }; const elevation = { e100: 100, // Cards e200: 200, // Inline dialogs (popover) e300: 300, // Tooltip e400: 400, // Modals e500: 500, // Toasts (notifications) }; const radii = { none: 0, xsmall: 4, small: 6, medium: 8, large: 12, full: 9999, }; const sizing = { xxsmall: 16, xsmall: 20, small: 24, medium: 32, large: 38, xlarge: 42, xxlarge: 48, }; const spacing = { none: 0, xxsmall: 2, xsmall: 4, small: 8, medium: 12, large: 16, xlarge: 24, xxlarge: 32, }; const shadow = { s100: `0px 1px 2px rgba(0, 0, 0, 0.2)`, // Cards s200: `0px 2px 4px rgba(0, 0, 0, 0.2)`, // Inline dialogs (popover) s300: `0px 2px 8px rgba(0, 0, 0, 0.2)`, // Tooltip s400: `0px 4px 16px rgba(0, 0, 0, 0.2)`, // Modals s500: `-8px 8px 32px rgba(0, 0, 0, 0.2)`, // Toasts (notifications) }; const animation = { duration0: '0ms', duration50: '40ms', duration100: '130ms', duration200: '160ms', duration300: '190ms', duration400: '220ms', duration500: '250ms', duration600: '300ms', duration700: '350ms', duration800: '400ms', duration900: '450ms', duration1000: '500ms', spring: `cubic-bezier(0.2, 0, 0, 1.6)`, easeInOut: 'cubic-bezier(.45, 0, .40, 1)', easeIn: `cubic-bezier(0.2, 0, 0, 1)`, easeOut: `cubic-bezier(0.165, 0.840, 0.440, 1)`, linear: 'cubic-bezier(0, 0, 1, 1)', }; const opacity = { full: 1, none: 0, disabled: 0.65, }; /** * Alias Tokens */ type HeadingStyle = { color: string; family: string; size: string; transform: Extract<CSSObject['textTransform'], string>; weight: number; }; const headingStyles: { [key: string]: HeadingStyle } = { h1: { color: palette.neutral900, family: typography.fontFamily.heading, size: typography.fontSize.xxxlarge, transform: 'none', weight: typography.fontWeight.heavy, }, h2: { color: palette.neutral900, family: typography.fontFamily.heading, size: typography.fontSize.xxlarge, transform: 'none', weight: typography.fontWeight.bold, }, h3: { color: palette.neutral900, family: typography.fontFamily.heading, size: typography.fontSize.xlarge, transform: 'none', weight: typography.fontWeight.bold, }, h4: { color: palette.neutral900, family: typography.fontFamily.heading, size: typography.fontSize.large, transform: 'none', weight: typography.fontWeight.bold, }, h5: { color: palette.neutral900, family: typography.fontFamily.heading, size: typography.fontSize.medium, transform: 'none', weight: typography.fontWeight.bold, }, h6: { color: palette.neutral900, family: typography.fontFamily.heading, size: typography.fontSize.small, transform: 'uppercase', weight: typography.fontWeight.bold, }, }; type ControlSize = { borderRadius: number; borderWidth: number; gutter: number; paddingX: number; paddingY: number; height: number; gap: number; fontSize: number | string; indicatorBoxSize: number | string; indicatorFontSize: number | string; }; const controlSizes: { [key: string]: ControlSize } = { small: { borderRadius: radii.xsmall, borderWidth: 1, gutter: spacing.xsmall, paddingX: spacing.medium, paddingY: spacing.xsmall, height: sizing.medium, gap: spacing.small, fontSize: typography.fontSize.small, indicatorBoxSize: sizing.xsmall, indicatorFontSize: typography.fontSize.xxxsmall, }, medium: { borderRadius: radii.small, borderWidth: 1, gutter: spacing.xsmall, paddingX: spacing.large, paddingY: spacing.xsmall, height: sizing.large, gap: spacing.medium, fontSize: typography.fontSize.medium, indicatorBoxSize: sizing.small, indicatorFontSize: typography.fontSize.xxsmall, }, large: { borderRadius: radii.medium, borderWidth: 1, gutter: spacing.small, paddingX: spacing.large, paddingY: spacing.small, height: sizing.xxlarge, gap: spacing.medium, fontSize: typography.fontSize.large, indicatorBoxSize: sizing.medium, indicatorFontSize: typography.fontSize.small, }, }; const colors = { background: 'white', backgroundMuted: palette.neutral100, backgroundDim: palette.neutral200, backgroundHover: palette.blue50, border: palette.neutral300, borderCritical: palette.red400, borderFocus: palette.blue400, focusRing: palette.blue200, foreground: palette.neutral800, foregroundMuted: palette.neutral900, foregroundDim: palette.neutral700, foregroundDisabled: palette.neutral500, linkColor: palette.blue500, linkHoverColor: palette.blue600, overlayBackground: 'rgba(18,18,18, 0.3)', // blanket behind modal dialogs loaderDark: palette.neutral500, loaderLight: palette.neutral200, }; /** Tones have 3 backgrounds: - pass-through (colors.background or colors.backgroundMuted) - tint (tone.tint) - fill (tone.fill) Tones have 2 foregrounds that should work on these backgrounds: - foreground (should work on pass-through and tint) - fillForeground (should work on fill) */ type ToneColor = [string, string, string]; type Tone = { focusRing: string; border: ToneColor; fill: ToneColor; tint: ToneColor; foreground: ToneColor; fillForeground: ToneColor; }; const tones = identityType<{ [key: string]: Tone }>()({ active: { focusRing: palette.blue200, border: [palette.blue300, palette.blue400, palette.blue500], fill: [palette.blue600, palette.blue700, palette.blue800], tint: [palette.blue50, palette.blue100, palette.blue200], foreground: [palette.blue600, palette.blue700, palette.blue800], fillForeground: [palette.white, palette.white, palette.white], }, passive: { focusRing: palette.neutral300, border: [palette.neutral300, palette.neutral400, palette.neutral500], fill: [palette.neutral600, palette.neutral700, palette.neutral800], tint: [palette.neutral200, palette.neutral300, palette.neutral400], foreground: [palette.neutral700, palette.neutral800, palette.neutral900], fillForeground: [palette.white, palette.white, palette.white], }, positive: { focusRing: palette.green200, border: [palette.green300, palette.green400, palette.green500], fill: [palette.green600, palette.green700, palette.green800], tint: [palette.green50, palette.green100, palette.green200], foreground: [palette.green600, palette.green700, palette.green800], fillForeground: [palette.white, palette.white, palette.white], }, warning: { focusRing: palette.yellow200, border: [palette.yellow300, palette.yellow400, palette.yellow500], fill: [palette.yellow400, palette.yellow500, palette.yellow600], tint: [palette.yellow50, palette.yellow100, palette.yellow200], foreground: [palette.yellow600, palette.yellow700, palette.yellow900], fillForeground: [palette.black, palette.black, palette.black], }, negative: { focusRing: palette.red200, border: [palette.red300, palette.red400, palette.red500], fill: [palette.red500, palette.red600, palette.red700], tint: [palette.red50, palette.red100, palette.red200], foreground: [palette.red600, palette.red700, palette.red800], fillForeground: [palette.white, palette.white, palette.white], }, help: { focusRing: palette.purple200, border: [palette.purple300, palette.purple400, palette.purple500], fill: [palette.purple500, palette.purple600, palette.purple700], tint: [palette.purple50, palette.purple100, palette.purple200], foreground: [palette.purple600, palette.purple700, palette.purple800], fillForeground: [palette.white, palette.white, palette.white], }, }); type SelectableColor = { border: string; fill: string; fillForeground: string; foreground: string; tint: string; }; const selectableColors = identityType<{ [key: string]: SelectableColor }>()({ silver: { border: palette.neutral400, fill: palette.neutral500, fillForeground: 'white', foreground: palette.neutral600, tint: palette.neutral200, }, grey: { border: palette.neutral600, fill: palette.neutral700, fillForeground: 'white', foreground: palette.neutral700, tint: palette.neutral300, }, blue: { border: palette.blue400, fill: palette.blue500, fillForeground: 'white', foreground: palette.blue600, tint: palette.blue200, }, pink: { border: palette.pink400, fill: palette.pink500, fillForeground: 'white', foreground: palette.pink600, tint: palette.pink200, }, green: { border: palette.green400, fill: palette.green500, fillForeground: 'white', foreground: palette.green600, tint: palette.green200, }, purple: { border: palette.purple400, fill: palette.purple500, fillForeground: 'white', foreground: palette.purple600, tint: palette.purple200, }, }); type SharedFieldStateTokens = { labelColor?: string; legendColor?: string; shadow?: string; }; type ControlFieldStateTokens = { controlBackground?: string; controlBorderColor?: string; controlBorderRadius?: number | string; controlForeground?: string; }; type InputFieldStateTokens = { inputBackground?: string; inputBorderColor?: string; inputBorderRadius?: number | string; inputForeground?: string; iconColor?: string; }; type FieldStateTokens = SharedFieldStateTokens & ControlFieldStateTokens & InputFieldStateTokens; type FieldTokens = FieldStateTokens & { controlBorderWidth?: number | string; inputBorderWidth?: number | string; inputPlaceholder?: string; switchForeground?: string; disabled: FieldStateTokens; focus: FieldStateTokens; hover: FieldStateTokens; invalid: FieldStateTokens; selected: SharedFieldStateTokens & ControlFieldStateTokens; }; const fields: FieldTokens = { controlBackground: 'white', controlBorderColor: palette.neutral300, controlBorderRadius: radii.small, controlBorderWidth: 2, controlForeground: palette.blue500, // iconColor: palette.neutral500, // TODO inputBackground: palette.neutral100, inputBorderColor: palette.neutral300, inputBorderRadius: radii.small, inputBorderWidth: 1, inputForeground: palette.neutral800, inputPlaceholder: palette.neutral500, labelColor: palette.neutral800, legendColor: palette.neutral600, switchForeground: 'white', hover: { inputBorderColor: palette.neutral400, controlBorderColor: palette.blue500, }, focus: { controlBorderColor: palette.blue500, inputBorderColor: palette.blue500, inputBackground: 'white', shadow: `0 0 0 2px ${colors.focusRing}`, }, disabled: { inputBackground: palette.neutral100, inputForeground: palette.neutral800, inputBorderColor: palette.transparent, controlBackground: palette.neutral100, controlBorderColor: palette.neutral200, controlForeground: palette.neutral500, }, invalid: { inputBackground: palette.red100, inputForeground: palette.neutral700, labelColor: palette.red600, }, selected: { controlBackground: palette.blue500, controlBorderColor: palette.blue500, controlForeground: 'white', }, }; /** * Export */ export const theme = { name: 'Keystone: Light', // Global Tokens typography, palette, breakpoints, elevation, radii, sizing, spacing, shadow, animation, opacity, // Alias Tokens headingStyles, controlSizes, colors, tones, selectableColors, fields, };
the_stack
import React, { useState, useContext, useEffect } from 'react'; import DisplayTableWithEmptyMessage from '../../../../components/DisplayTableWithEmptyMessage/DisplayTableWithEmptyMessage'; import moment from 'moment'; import { IGroup } from 'office-ui-fabric-react/lib/components/GroupedList/GroupedList.types'; import { DeploymentCenterCodeLogsProps, DeploymentStatus, DeploymentProperties, GitHubActionsCodeDeploymentsRow, GitHubActionRunConclusion, GitHubActionsRun, } from '../DeploymentCenter.types'; import { ProgressIndicator, PanelType, IColumn, Link, PrimaryButton, Icon } from 'office-ui-fabric-react'; import { useTranslation } from 'react-i18next'; import { deploymentCenterLogsError, deploymentCenterCodeLogsNotConfigured, deploymentCenterCodeLogsBox } from '../DeploymentCenter.styles'; import { ArmObj } from '../../../../models/arm-obj'; import CustomPanel from '../../../../components/CustomPanel/CustomPanel'; import DeploymentCenterCommitLogs from './DeploymentCenterCommitLogs'; import { ReactComponent as DeploymentCenterIcon } from '../../../../images/Common/deployment-center.svg'; import { ScmType } from '../../../../models/site/config'; import { DeploymentCenterContext } from '../DeploymentCenterContext'; import { getSourceControlsWorkflowFileName, getTelemetryInfo, getWorkflowFileName } from '../utility/DeploymentCenterUtility'; import { SiteStateContext } from '../../../../SiteState'; import DeploymentCenterData from '../DeploymentCenter.data'; import { dateTimeComparatorReverse } from './DeploymentCenterCodeLogs'; import { PortalContext } from '../../../../PortalContext'; import DeploymentCenterCodeLogsTimer from './DeploymentCenterCodeLogsTimer'; import { getErrorMessage } from '../../../../ApiHelpers/ArmHelper'; import ConfirmDialog from '../../../../components/ConfirmDialog/ConfirmDialog'; const DeploymentCenterGitHubActionsCodeLogs: React.FC<DeploymentCenterCodeLogsProps> = props => { const { deployments, deploymentsError, isLogsDataRefreshing, goToSettings, refreshLogs } = props; const { t } = useTranslation(); const [isLogPanelOpen, setIsLogPanelOpen] = useState<boolean>(false); const [currentCommitId, setCurrentCommitId] = useState<string | undefined>(undefined); const [isLogsLoading, setIsLogsLoading] = useState<boolean>(false); const [isSourceControlsLoading, setIsSourcecontrolsLoading] = useState<boolean>(true); const [org, setOrg] = useState<string | undefined>(undefined); const [repo, setRepo] = useState<string | undefined>(undefined); const [branch, setBranch] = useState<string | undefined>(undefined); const [runs, setRuns] = useState<GitHubActionsRun[] | undefined>(undefined); const [gitHubActionLogsErrorMessage, setGitHubActionLogsErrorMessage] = useState<string | undefined>(undefined); const [isCancelWorkflowRunConfirmDialogHidden, setIsCancelWorkflowRunConfirmDialogHidden] = useState(true); const deploymentCenterContext = useContext(DeploymentCenterContext); const siteStateContext = useContext(SiteStateContext); const portalContext = useContext(PortalContext); const deploymentCenterData = new DeploymentCenterData(); const getStatusString = (status: DeploymentStatus, progressString: string) => { switch (status) { case DeploymentStatus.Building: case DeploymentStatus.Deploying: return progressString; case DeploymentStatus.Pending: return t('pending'); case DeploymentStatus.Failed: return t('failed'); case DeploymentStatus.Success: return t('success'); default: return ''; } }; const getConclusionDisplayName = (status: string): string => { switch (status) { case GitHubActionRunConclusion.Success: return t('success'); case GitHubActionRunConclusion.Failure: return t('failed'); case GitHubActionRunConclusion.Cancelled: return t('GitHubActionsRunCancelled'); case GitHubActionRunConclusion.Skipped: return t('GitHubActionsRunSkipped'); case GitHubActionRunConclusion.TimedOut: return t('GitHubActionsRunTimedOut'); case GitHubActionRunConclusion.ActionRequired: return t('GitHubActionsRunActionRequired'); default: return ''; } }; const showLogPanel = (deployment: ArmObj<DeploymentProperties>) => { setIsLogPanelOpen(true); setCurrentCommitId(deployment.id); }; const dismissLogPanel = () => { setIsLogPanelOpen(false); setCurrentCommitId(undefined); }; const hideCancelWorkflowRunConfirmDialog = () => { setIsCancelWorkflowRunConfirmDialogHidden(true); }; const goToSettingsOnClick = () => { if (goToSettings) { goToSettings(); } }; const refreshGitHubActionsLogs = () => { refreshLogs(); fetchWorkflowRuns(); }; const setSourceControlDetails = async () => { setGitHubActionLogsErrorMessage(undefined); setIsLogsLoading(true); setIsSourcecontrolsLoading(true); setBranch(deploymentCenterContext.configMetadata ? deploymentCenterContext.configMetadata.properties.branch : ''); const repoUrlSplit = deploymentCenterContext.configMetadata ? deploymentCenterContext.configMetadata.properties.RepoUrl.split('/') : []; if (repoUrlSplit.length >= 2) { setOrg(repoUrlSplit[repoUrlSplit.length - 2]); setRepo(repoUrlSplit[repoUrlSplit.length - 1]); } else { setGitHubActionLogsErrorMessage(t('deploymentCenterCodeDeploymentsFailed')); setIsLogsLoading(false); } setIsSourcecontrolsLoading(false); }; const fetchWorkflowRuns = async () => { setGitHubActionLogsErrorMessage(undefined); const siteName = siteStateContext.site ? siteStateContext.site.properties.name : ''; if (org && repo && branch && siteName) { const workflowFileName = getWorkflowFileName(branch, siteName); const sourceControlsWorkflowFileName = getSourceControlsWorkflowFileName(branch, siteName, 'production'); const [gitHubActionsWorkflowRunsResponse, gitHubActionsFromCreateWorkflowRunsResponse] = await Promise.all([ deploymentCenterData.listWorkflowRuns(deploymentCenterContext.gitHubToken, org, repo, workflowFileName), deploymentCenterData.listWorkflowRuns(deploymentCenterContext.gitHubToken, org, repo, sourceControlsWorkflowFileName), ]); if (gitHubActionsWorkflowRunsResponse.metadata.success && gitHubActionsWorkflowRunsResponse.data) { setRuns(gitHubActionsWorkflowRunsResponse.data.workflow_runs); } else if (gitHubActionsFromCreateWorkflowRunsResponse.metadata.success && gitHubActionsFromCreateWorkflowRunsResponse.data) { setRuns(gitHubActionsFromCreateWorkflowRunsResponse.data.workflow_runs); } else { setRuns([]); const errorMessage = getErrorMessage(gitHubActionsWorkflowRunsResponse.metadata.error); setGitHubActionLogsErrorMessage( errorMessage ? t('deploymentCenterCodeDeploymentsFailedWithError').format(errorMessage) : t('deploymentCenterCodeDeploymentsFailed') ); portalContext.log( getTelemetryInfo('error', 'getWorkflowRuns', 'failed', { error: gitHubActionsWorkflowRunsResponse.metadata.error, }) ); } } setIsLogsLoading(false); }; const cancelWorkflowRunOnClick = async (url: string) => { portalContext.log(getTelemetryInfo('verbose', 'cancelWorkflow', 'clicked')); const cancelWorkflowResponse = await deploymentCenterData.cancelWorkflowRun(deploymentCenterContext.gitHubToken, url); if (cancelWorkflowResponse.metadata.success) { setIsLogsLoading(true); await fetchWorkflowRuns(); //NOTE(stpelleg): It takes a while for the run to show as cancelled, but users would be confused if //it did not show as cancelled right after clicking cancel if (runs && runs.length > 0) { const curRuns = runs; curRuns[0].conclusion = t(GitHubActionRunConclusion.Cancelled); setRuns(curRuns); } } else { portalContext.log( getTelemetryInfo('error', 'cancelWorkflow', 'failed', { error: cancelWorkflowResponse.metadata.error, }) ); } }; const getGitHubActionsRunStatus = (run: GitHubActionsRun): JSX.Element => { return run.conclusion ? ( <>{getConclusionDisplayName(run.conclusion)}</> ) : ( <> {t('In Progress... ')} { <> <Link onClick={() => { setIsCancelWorkflowRunConfirmDialogHidden(false); }}> {t('deploymentCenterGitHubActionsCancelRunMessage')} </Link> <ConfirmDialog primaryActionButton={{ title: t('ok'), onClick: () => { cancelWorkflowRunOnClick(run.cancel_url); hideCancelWorkflowRunConfirmDialog(); }, }} defaultActionButton={{ title: t('cancel'), onClick: hideCancelWorkflowRunConfirmDialog, }} title={t('deploymentCenterCancelWorkflowRunConfirmTitle')} content={t('deploymentCenterCancelWorkflowRunConfirmMessage')} hidden={isCancelWorkflowRunConfirmDialogHidden} onDismiss={hideCancelWorkflowRunConfirmDialog} /> </> } </> ); }; const getZipDeployRow = (deployment: ArmObj<DeploymentProperties>, index: number): GitHubActionsCodeDeploymentsRow => { return { index: index, group: -1, commitId: deployment.properties.id.substr(0, 7), rawTime: moment(deployment.properties.received_time), // NOTE (t-kakan): A is AM/PM and Z is offset from GMT: -07:00 -06:00 ... +06:00 +07:00 displayTime: moment(deployment.properties.received_time).format('MM/D YYYY, h:mm:ss A Z'), commit: deployment.properties.id.substr(0, 7), logSource: ( <Link href={`#${deployment.properties.id}`} onClick={() => showLogPanel(deployment)}> {t('deploymentCenterAppLogSource')} </Link> ), author: deployment.properties.author, message: deployment.properties.message, status: deployment.properties.active ? ( <>{`${getStatusString(deployment.properties.status, deployment.properties.progress)} (${t('active')})`}</> ) : ( <>{getStatusString(deployment.properties.status, deployment.properties.progress)}</> ), }; }; const getGitHubActionsRunRow = (run: GitHubActionsRun, index: number): GitHubActionsCodeDeploymentsRow => { return { index: deployments && deployments.value.length ? deployments.value.length + index : index, group: -1, commitId: run.head_commit.id.substr(0, 7), rawTime: moment(run.created_at), // NOTE (stpelleg): A is AM/PM and Z is offset from GMT: -07:00 -06:00 ... +06:00 +07:00 displayTime: moment(run.created_at).format('MM/D YYYY, h:mm:ss A Z'), author: run.head_commit.author.name, message: run.head_commit.message, commit: run.head_commit.id.substr(0, 7), logSource: ( <Link key="github-actions-logs-link" onClick={() => window.open(run.html_url, '_blank')}> {t('deploymentCenterBuildDeployLogSource')} <Icon id={`ga-logs`} iconName={'NavigateExternalInline'} /> </Link> ), status: getGitHubActionsRunStatus(run), }; }; const getItemCommitGroups = (items: GitHubActionsCodeDeploymentsRow[]): IGroup[] => { const groups: IGroup[] = []; items.forEach((item, index) => { if (index === 0 || !item.rawTime.isSame(groups[groups.length - 1].data.startIndexRawTime, 'day')) { groups.push({ key: `Group${groups.length}`, name: item.rawTime.format('dddd, MMMM D, YYYY'), startIndex: index, count: 1, data: { startIndexRawTime: item.rawTime }, }); } else { groups[groups.length - 1].count += 1; } }); return groups; }; const getZeroDayContent = () => { if (deploymentCenterContext.siteConfig && deploymentCenterContext.siteConfig.properties.scmType === ScmType.None) { return ( <> <div className={deploymentCenterCodeLogsNotConfigured}> <DeploymentCenterIcon filter="grayscale(100%)" /> <h3>{t('deploymentCenterCodeLogsCICDNotConfiguredHeader')}</h3> <p>{t('deploymentCenterCodeLogsCICDNotConfiguredDescription')}</p> <PrimaryButton text={t('deploymentCenterCodeLogsCICDNotConfiguredGoToSettings')} onClick={() => goToSettingsOnClick()} /> </div> </> ); } else { return ( <> <div className={deploymentCenterCodeLogsNotConfigured}> <h3>{t('deploymentCenterCodeLogsNoDeployments')}</h3>; </div> </> ); } }; const getProgressIndicator = () => { return ( <ProgressIndicator description={t('deploymentCenterCodeDeploymentsLoading')} ariaValueText={t('deploymentCenterCodeDeploymentsLoadingAriaValue')} /> ); }; const getDeploymentErrorMessage = () => { return `${deploymentsError} ${gitHubActionLogsErrorMessage}`; }; const gitHubActionsRows: GitHubActionsCodeDeploymentsRow[] = runs ? runs.map((run, index) => getGitHubActionsRunRow(run, index)) : []; const zipDeployRows: GitHubActionsCodeDeploymentsRow[] = deployments ? deployments.value.map((deployment, index) => getZipDeployRow(deployment, index)) : []; const newItems = zipDeployRows.concat(gitHubActionsRows); const items: GitHubActionsCodeDeploymentsRow[] = newItems.sort(dateTimeComparatorReverse); const groups: IGroup[] = getItemCommitGroups(items); const columns: IColumn[] = [ { key: 'displayTime', name: t('time'), fieldName: 'displayTime', minWidth: 100, maxWidth: 200 }, { key: 'commit', name: t('commitId'), fieldName: 'commit', minWidth: 50, maxWidth: 100 }, { key: 'logSource', name: t('deploymentCenterLogSource'), fieldName: 'logSource', minWidth: 100, maxWidth: 150 }, { key: 'author', name: t('commitAuthor'), fieldName: 'author', minWidth: 100, maxWidth: 150 }, { key: 'status', name: t('status'), fieldName: 'status', minWidth: 125, maxWidth: 200 }, { key: 'message', name: t('message'), fieldName: 'message', minWidth: 200 }, ]; useEffect(() => { if (deploymentCenterContext.configMetadata) { setSourceControlDetails(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [deploymentCenterContext.configMetadata]); useEffect(() => { if (!isSourceControlsLoading) { fetchWorkflowRuns(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isSourceControlsLoading]); return ( <> <DeploymentCenterCodeLogsTimer refreshLogs={refreshGitHubActionsLogs} /> {isLogsDataRefreshing || isLogsLoading ? ( getProgressIndicator() ) : deploymentsError && gitHubActionLogsErrorMessage ? ( <div className={deploymentCenterLogsError}>{getDeploymentErrorMessage()}</div> ) : deployments || runs ? ( <div className={deploymentCenterCodeLogsBox}> <DisplayTableWithEmptyMessage columns={columns} items={items} selectionMode={0} groups={groups} /> {items.length === 0 && getZeroDayContent()} </div> ) : ( getProgressIndicator() )} <CustomPanel isOpen={isLogPanelOpen} onDismiss={dismissLogPanel} type={PanelType.medium}> <DeploymentCenterCommitLogs commitId={currentCommitId} dismissLogPanel={dismissLogPanel} /> </CustomPanel> </> ); }; export default DeploymentCenterGitHubActionsCodeLogs;
the_stack
import { expect } from 'chai' import { Redis } from 'ioredis' import sinon from 'sinon' import LostLockError from '../../src/errors/LostLockError' import MultiSemaphore from '../../src/RedisMultiSemaphore' import Semaphore from '../../src/RedisSemaphore' import { TimeoutOptions } from '../../src/types' import { delay } from '../../src/utils/index' import { client1 as client } from '../redisClient' import { downRedisServer, upRedisServer } from '../shell' import { catchUnhandledRejection, throwUnhandledRejection, unhandledRejectionSpy } from '../unhandledRejection' const timeoutOptions: TimeoutOptions = { lockTimeout: 300, acquireTimeout: 100, refreshInterval: 80, retryInterval: 10 } describe('MultiSemaphore', () => { it('should fail on invalid arguments', () => { expect( () => new MultiSemaphore((null as unknown) as Redis, 'key', 5, 2) ).to.throw('"client" is required') expect( () => new MultiSemaphore(({} as unknown) as Redis, 'key', 5, 2) ).to.throw('"client" must be instance of ioredis client') expect(() => new MultiSemaphore(client, '', 5, 2)).to.throw( '"key" is required' ) expect( () => new MultiSemaphore(client, (1 as unknown) as string, 5, 2) ).to.throw('"key" must be a string') expect(() => new MultiSemaphore(client, 'key', 0, 2)).to.throw( '"limit" is required' ) expect( () => new MultiSemaphore(client, 'key', ('10' as unknown) as number, 2) ).to.throw('"limit" must be a number') expect(() => new MultiSemaphore(client, 'key', 5, 0)).to.throw( '"permits" is required' ) expect( () => new MultiSemaphore(client, 'key', 5, ('2' as unknown) as number) ).to.throw('"permits" must be a number') }) it('should acquire and release semaphore', async () => { const semaphore1 = new MultiSemaphore(client, 'key', 3, 2) const semaphore2 = new MultiSemaphore(client, 'key', 3, 1) expect(semaphore1.isAcquired).to.be.false expect(semaphore2.isAcquired).to.be.false await semaphore1.acquire() expect(semaphore1.isAcquired).to.be.true await semaphore2.acquire() expect(semaphore2.isAcquired).to.be.true expect(await client.zrange('semaphore:key', 0, -1)).to.have.members([ semaphore1.identifier + '_0', semaphore1.identifier + '_1', semaphore2.identifier + '_0' ]) await semaphore1.release() expect(semaphore1.isAcquired).to.be.false expect(await client.zrange('semaphore:key', 0, -1)).to.be.eql([ semaphore2.identifier + '_0' ]) await semaphore2.release() expect(semaphore2.isAcquired).to.be.false expect(await client.zcard('semaphore:key')).to.be.eql(0) }) it('should reject after timeout', async () => { const semaphore1 = new MultiSemaphore(client, 'key', 3, 3, timeoutOptions) const semaphore2 = new MultiSemaphore(client, 'key', 3, 1, timeoutOptions) await semaphore1.acquire() await expect(semaphore2.acquire()).to.be.rejectedWith( 'Acquire multi-semaphore semaphore:key timeout' ) await semaphore1.release() expect(await client.get('semaphore:key')).to.be.eql(null) }) it('should refresh lock every refreshInterval ms until release', async () => { const semaphore1 = new MultiSemaphore(client, 'key', 3, 2, timeoutOptions) const semaphore2 = new MultiSemaphore(client, 'key', 3, 1, timeoutOptions) await semaphore1.acquire() await semaphore2.acquire() await delay(100) expect(await client.zrange('semaphore:key', 0, -1)).to.have.members([ semaphore1.identifier + '_0', semaphore1.identifier + '_1', semaphore2.identifier + '_0' ]) await semaphore1.release() expect(await client.zrange('semaphore:key', 0, -1)).to.be.eql([ semaphore2.identifier + '_0' ]) await semaphore2.release() expect(await client.zcard('semaphore:key')).to.be.eql(0) }) it('should acquire maximum LIMIT semaphores', async () => { const s = () => new MultiSemaphore(client, 'key', 3, 1, { acquireTimeout: 1000, lockTimeout: 50, retryInterval: 10, refreshInterval: 0 // disable refresh }) const pr1 = Promise.all([s().acquire(), s().acquire(), s().acquire()]) await delay(5) const pr2 = Promise.all([s().acquire(), s().acquire(), s().acquire()]) await pr1 const ids1 = await client.zrange('semaphore:key', 0, -1) expect(ids1.length).to.be.eql(3) await pr2 const ids2 = await client.zrange('semaphore:key', 0, -1) expect(ids2.length).to.be.eql(3) expect(ids2) .to.not.include(ids1[0]) .and.not.include(ids1[1]) .and.not.include(ids1[2]) }) describe('lost lock case', () => { beforeEach(() => { catchUnhandledRejection() }) afterEach(() => { throwUnhandledRejection() }) it('should throw unhandled error if lock is lost between refreshes', async () => { const semaphore = new MultiSemaphore(client, 'key', 3, 2, timeoutOptions) await semaphore.acquire() await client.del('semaphore:key') await client.zadd( 'semaphore:key', Date.now(), 'aaa', Date.now(), 'bbb', Date.now(), 'ccc' ) await delay(200) expect(unhandledRejectionSpy).to.be.called expect(unhandledRejectionSpy.firstCall.firstArg instanceof LostLockError) .to.be.true }) it('should call onLockLost callback if provided', async () => { const onLockLostCallback = sinon.spy(function (this: MultiSemaphore) { expect(this.isAcquired).to.be.false }) const semaphore = new MultiSemaphore(client, 'key', 3, 2, { ...timeoutOptions, onLockLost: onLockLostCallback }) await semaphore.acquire() expect(semaphore.isAcquired).to.be.true await client.del('semaphore:key') await client.zadd( 'semaphore:key', Date.now(), 'aaa', Date.now(), 'bbb', Date.now(), 'ccc' ) await delay(200) expect(semaphore.isAcquired).to.be.false expect(unhandledRejectionSpy).to.not.called expect(onLockLostCallback).to.be.called expect(onLockLostCallback.firstCall.firstArg instanceof LostLockError).to .be.true }) }) describe('reusable', () => { it('autorefresh enabled', async function () { this.timeout(10000) const semaphore1 = new MultiSemaphore(client, 'key', 4, 2, timeoutOptions) const semaphore2 = new MultiSemaphore(client, 'key', 4, 2, timeoutOptions) await semaphore1.acquire() await semaphore2.acquire() await delay(300) await semaphore1.release() await semaphore2.release() await delay(300) await semaphore1.acquire() await semaphore2.acquire() await delay(300) await semaphore1.release() await semaphore2.release() await delay(300) await semaphore1.acquire() await semaphore2.acquire() await delay(300) await semaphore1.release() await semaphore2.release() }) it('autorefresh disabled', async () => { const noRefreshOptions = { ...timeoutOptions, refreshInterval: 0, acquireTimeout: 10 } const semaphore1 = new MultiSemaphore( client, 'key', 4, 2, noRefreshOptions ) const semaphore2 = new MultiSemaphore( client, 'key', 4, 2, noRefreshOptions ) const semaphore3 = new MultiSemaphore( client, 'key', 4, 2, noRefreshOptions ) await semaphore1.acquire() await semaphore2.acquire() await delay(300) await semaphore1.release() await semaphore2.release() await delay(300) // [0/2] await semaphore1.acquire() // [1/2] await delay(80) await semaphore2.acquire() // [2/2] await expect(semaphore3.acquire()).to.be.rejectedWith( 'Acquire multi-semaphore semaphore:key timeout' ) // rejectes after 10ms // since semaphore1.acquire() elapsed 80ms (delay) + 10ms (semaphore3 timeout) // semaphore1 will expire after 300 - 90 = 210ms await delay(210) // [1/2] await semaphore3.acquire() }) }) describe('Compatibility with Semaphore', () => { it('should work with Semaphore', async () => { const multiSemaphore1 = new MultiSemaphore( client, 'key', 3, 2, timeoutOptions ) const multiSemaphore2 = new MultiSemaphore( client, 'key', 3, 2, timeoutOptions ) const semaphore1 = new Semaphore(client, 'key', 3, timeoutOptions) const semaphore2 = new Semaphore(client, 'key', 3, timeoutOptions) await multiSemaphore1.acquire() await semaphore1.acquire() expect(await client.zrange('semaphore:key', 0, -1)).to.have.members([ multiSemaphore1.identifier + '_0', multiSemaphore1.identifier + '_1', semaphore1.identifier ]) await expect(multiSemaphore2.acquire()).to.be.rejectedWith( 'Acquire multi-semaphore semaphore:key timeout' ) await expect(semaphore2.acquire()).to.be.rejectedWith( 'Acquire semaphore semaphore:key timeout' ) await multiSemaphore1.release() expect(await client.zrange('semaphore:key', 0, -1)).to.be.eql([ semaphore1.identifier ]) await semaphore1.release() expect(await client.zcard('semaphore:key')).to.be.eql(0) }) }) describe('[Node shutdown]', () => { beforeEach(() => { catchUnhandledRejection() }) afterEach(async () => { throwUnhandledRejection() await upRedisServer(1) }) it('should work again if node become alive', async function () { this.timeout(60000) const semaphore1 = new MultiSemaphore(client, 'key', 3, 2, timeoutOptions) await semaphore1.acquire() await downRedisServer(1) console.log('SHUT DOWN') await delay(1000) await upRedisServer(1) console.log('ONLINE') // semaphore was expired, key was deleted in redis // give refresh mechanism time to reacquire the lock // (includes reconnection time) await delay(1000) const data = await client.zrange('semaphore:key', 0, -1, 'WITHSCORES') // console.log(data) expect(data).to.include(semaphore1.identifier + '_0') expect(data).to.include(semaphore1.identifier + '_1') // now lock reacquired by semaphore1, so semaphore2 cant acquire the lock const semaphore2 = new MultiSemaphore(client, 'key', 3, 2, timeoutOptions) await expect(semaphore2.acquire()).to.be.rejectedWith( 'Acquire multi-semaphore semaphore:key timeout' ) await semaphore1.release() }) }) })
the_stack
declare module cheetahGrid { namespace columns { namespace action { interface BaseActionOption { disabled?: boolean } export class BaseAction { constructor(option?: BaseActionOption) disabled: boolean; clone(): BaseAction; bindGridEvent(grid: core.DrawGrid, col: number, util: any): any[]; onChangeDisabledInternal(): void; } interface EditorOption extends BaseActionOption { readOnly?: boolean } export class Editor extends BaseAction { constructor(option?: EditorOption); readOnly: boolean; clone(): Editor; onChangeReadOnlyInternal(): void; } interface ActionOption<T> extends BaseActionOption { action?: (record: T) => void; } export class Action<T> extends BaseAction { constructor(option?: ActionOption<T>); action: (record: T) => void; clone(): Action<T>; getState(grid: core.DrawGrid): any; } export class CheckEditor extends Editor { clone(): CheckEditor; } export class ButtonAction<T> extends Action<T> { } interface BaseInputEditorOption extends EditorOption { } class BaseInputEditor extends Editor { constructor(option?: BaseInputEditorOption); clone(): BaseInputEditor; onInputCellInternal(grid: core.DrawGrid, cell, inputValue: any): void; onOpenCellInternal(grid: core.DrawGrid, cell): void; onChangeSelectCellInternal(grid: core.DrawGrid, cell, selected: boolean): void; onSetInputAttrsInternal(grid: core.DrawGrid, cell, input: HTMLInputElement): void; onGridScrollInternal(grid: core.DrawGrid): void; } interface SmallDialogInputEditorOption extends BaseInputEditorOption { helperText?: (value: string) => string; inputValidator?: (value: string) => string | null; validator?: (value: string) => string | null; classList?: string[]; type?: string; } export class SmallDialogInputEditor extends BaseInputEditor { constructor(option?: SmallDialogInputEditorOption); helperText: (value: string) => string; inputValidator: (value: string) => string | null; validator: (value: string) => string | null; classList: string[]; type: string; } interface InlineInputEditorOption extends BaseInputEditorOption { classList?: string[]; type?: string; } export class InlineInputEditor extends BaseInputEditor { constructor(option?: InlineInputEditorOption) classList: string[]; type: string; } export class InlineMenuEditor extends Editor { constructor(option?: { classList?: string[]; }); classList: string[]; options: { value: any, caption: string }[] | object | string; clone(): InlineMenuEditor; } function of(columnAction: string | BaseAction): BaseAction; } namespace style { export const EVENT_TYPE: { CHANGE_STYLE: "change_style" }; interface BaseStyleOption { bgColor?: string } export class BaseStyle extends EventTarget { constructor(style?: BaseStyleOption); bgColor: string; doChangeStyle(): void; clone(): BaseStyle; } interface BranchGraphStyleOption extends BaseStyleOption { branchColors?: string[]; margin?: number; circleSize?: number; branchLineWidth?: number; mergeStyle?: string; } class BranchGraphStyle extends BaseStyle { DEFAULT(): BranchGraphStyle; constructor(style?: BranchGraphStyleOption); branchColors?: string[]; margin?: number; circleSize?: number; branchLineWidth?: number; mergeStyle?: string; } interface StdBaseStyleOption extends BaseStyleOption { textAlign?: string; textBaseline?: string; } class StdBaseStyle extends BaseStyle { constructor(style?: StdBaseStyleOption) textAlign: string; textBaseline: string; clone(): StdBaseStyle; } interface StyleOption extends StdBaseStyleOption { color?: string; font?: string; padding?: number; textOverflow?: string; } export class Style extends StdBaseStyle { constructor(style?: StyleOption); static DEFAULT(): Style; color: string; font: string; padding: number; textOverflow: string; clone(): Style; } export class NumberStyle extends Style { static DEFAULT(): NumberStyle; clone(): NumberStyle; } interface CheckStyleOption extends StdBaseStyleOption { uncheckBgColor?: string; checkBgColor?: string; borderColor?: string; } export class CheckStyle extends StdBaseStyle { constructor(style?: CheckStyleOption); static DEFAULT(): CheckStyle; clone(): CheckStyle; } interface ButtonStyleOption extends StyleOption { buttonBgColor?: string; } export class ButtonStyle extends Style { constructor(style?: ButtonStyleOption); static DEFAULT(): ButtonStyle; buttonBgColor: string; clone(): ButtonStyle; } interface ImageStyleOption extends StdBaseStyleOption { imageSizing?: string; margin?: number; } export class ImageStyle extends StdBaseStyle { constructor(style?: ImageStyleOption); static DEFAULT(): ImageStyle; imageSizing: string; margin: number; clone(): ImageStyle; } export class IconStyle extends Style { static DEFAULT(): IconStyle; clone(): IconStyle; } interface PercentCompleteBarStyleOption extends StyleOption { barColor?: string; barBgColor?: string; barheight?: number; } export class PercentCompleteBarStyle extends Style { static DEFAULT(): PercentCompleteBarStyle; constructor(style?: PercentCompleteBarStyleOption); barColor: string; barBgColor: string; barheight: number; clone(): PercentCompleteBarStyle; } interface MultilineTextStyleOption extends StyleOption { lineHeight?: string; lineClamp?: string; autoWrapText?: boolean; } export class MultilineTextStyle extends Style { static DEFAULT(): MultilineTextStyle; constructor(style?: MultilineTextStyleOption); lineHeight: string; lineClamp: string; autoWrapText: boolean; clone(): MultilineTextStyle; } interface MenuStyleOption extends StyleOption { appearance?: string; } export class MenuStyle extends Style { static DEFAULT(): MenuStyle; constructor(option?: MenuStyleOption); appearance: string; clone(): MenuStyle; } export function of<T>( columnStyle: style.BaseStyle | BaseStyleOption | ((record: T) => any) | keyof T, record: T[], StyleClass: typeof style.BaseStyle ): style.BaseStyle; } namespace type { class BaseColumn { constructor(option?: { fadeinWhenCallbackInPromise?: boolean; }); StyleClass: style.BaseStyle; onDrawCell(cellValue: any, info, context: DrawCellContext, grid: core.DrawGrid): Promise<any> | null; clone(): BaseColumn; convertInternal(value: any): any; drawInternal(value: any, context: DrawCellContext, style: style.BaseStyle, helper, grid: core.DrawGrid, info): void; drawMessageInternal(message: string, context: DrawCellContext, style: style.BaseStyle, helper, grid: core.DrawGrid, info): void; bindGridEvent(grid: core.DrawGrid, col, util): void; } export class Column extends BaseColumn { StyleClass: style.Style; clone(): Column; } export class NumberColumn extends Column { static defaultFotmat: any; constructor(option?: { format?: Intl.NumberFormat; }); StyleClass: style.NumberStyle; clone(): NumberColumn; format: Intl.NumberFormat; withFormat(format: Intl.NumberFormat): NumberColumn; } export class CheckColumn extends BaseColumn { StyleClass: style.Style; clone(): ImageColumn; } export class ButtonColumn extends Column { StyleClass: style.ButtonStyle; constructor(option?: { caption?: string; }); withCaption(caption: string): ButtonColumn; clone(): ButtonColumn; } export class ImageColumn extends BaseColumn { StyleClass: style.ImageStyle; clone(): ImageColumn; } export class PercentCompleteBarColumn extends Column { constructor(option: { min?: number; max?: number; formatter?: (value: any) => any; }); StyleClass: style.PercentCompleteBarStyle; clone(): PercentCompleteBarColumn; } export class IconColumn extends Column { constructor(option?: { tagName?: string; className?: string; content?: any; name?: string; iconWidth?: number; }); StyleClass: style.IconStyle; clone(): IconColumn; } export class BranchGraphColumn extends BaseColumn { constructor(option?: { start?: string; cache?: boolean; }); StyleClass: style.BranchGraphStyle; clearCache(grid: core.DrawGrid): void; clone(): BranchGraphColumn; } export class MenuColumn extends BaseColumn { constructor(option?: { options?: { value: any, caption: string }[] | object | string; }); StyleClass: style.MenuStyle; clone(): MenuColumn; options: { value: any, caption: string }[] | object | string; withOptions(options: { value: any, caption: string }[] | object | string): MenuColumn; } export class MultilineTextColumn extends BaseColumn { StyleClass: style.MultilineTextStyle; clone(): MultilineTextColumn; } function of(columnType: string | BaseColumn): Column; } } namespace core { export interface DrawGridEvents { CLICK_CELL: 'click_cell', DBLCLICK_CELL: 'dblclick_cell', DBLTAP_CELL: 'dbltap_cell', MOUSEDOWN_CELL: 'mousedown_cell', MOUSEUP_CELL: 'mouseup_cell', SELECTED_CELL: 'selected_cell', KEYDOWN: 'keydown', MOUSEMOVE_CELL: 'mousemove_cell', MOUSEENTER_CELL: 'mouseenter_cell', MOUSELEAVE_CELL: 'mouseleave_cell', MOUSEOVER_CELL: 'mouseover_cell', MOUSEOUT_CELL: 'mouseout_cell', INPUT_CELL: 'input_cell', EDITABLEINPUT_CELL: 'editableinput_cell', MODIFY_STATUS_EDITABLEINPUT_CELL: 'modify_status_editableinput_cell', RESIZE_COLUMN: 'resize_column', SCROLL: 'scroll', } export class DrawGrid extends EventTarget { static EVENT_TYPE: DrawGridEvents; constructor(options: { rowCount?: number; colCount?: number; frozenColCount?: number; frozenRowCount?: number; defaultRowHeight?: number; defaultColWidth?: number; parentElement?: Element; font?: string; underlayBackgroundColor?: string; }); /** * Get root element. * @returns root element */ getElement(): HTMLElement; /** * Get canvas element. */ canvas: HTMLCanvasElement; /** * Focus the grid. */ focus(): void; selection: Selection; rowCount: number; colCount: number; frozenColCount: number; frozenRowCount: number; defaultRowHeight: number; defaultColWidth: number; font: string; /** * The background color of the underlay. * @param underlayBackgroundColor the background color of the underlay to set */ underlayBackgroundColor: any; /** * Apply the changed size. */ updateSize(): void; /** * Apply the changed scroll size. */ updateScroll(): boolean; /** * Get the row height of the given the row index. * @param row The row index */ getRowHeight(row: number): number; /** * Set the row height of the given the row index. * @param row The row index * @param height The row height */ setRowHeight(row: number, height: number): void; /** * Get the column width of the given the column index. * @param col The column index */ getColWidth(col: number): number; /** * Set the column widtht of the given the column index. * @param col The column index * @param width The column width */ setColWidth(col: number, width: number): void; /** * Get the column max width of the given the column index. * @param col The column index */ getMaxColWidth(col: number): number; /** * Set the column max widtht of the given the column index. * @param col The column index * @param maxwidth The column max width */ setMaxColWidth(col: number, maxwidth: number): void; /** * Get the column min width of the given the column index. * @param col The column index */ getMinColWidth(col: number): number; /** * Set the column min widtht of the given the column index. * @param col The column index * @param minwidth The column min width */ setMinColWidth(col: number, minwidth: number): void; /** * Get the rect of the cell. * @param col index of column, of the cell * @param row index of row, of the cell * @returns the rect of the cell. */ getCellRect(col: number, row: number): Rect; /** * Get the relative rectangle of the cell. * @param col index of column, of the cell * @param row index of row, of the cell * @returns the rect of the cell. */ getCellRelativeRect(col: number, row: number): Rect; /** * Get the rectangle of the cells area. * @param startCol index of the starting column, of the cell * @param startRow index of the starting row, of the cell * @param endCol index of the ending column, of the cell * @param endRow index of the ending row, of the cell * @returns the rect of the cells. */ getCellsRect(startCol: number, startRow: number, endCol: number, endRow: number): Rect; /** * Scroll to where cell is visible. * @param col The column index. * @param row The row index */ makeVisibleCell(col: number, row: number): void; /** * Focus the cell. * @param col The column index. * @param row The row index */ focusCell(col: number, row: number): void; /** * Redraws the range of the given cell. * @param col The column index of cell. * @param row The row index of cell. */ invalidateCell(col: number, row: number): void; /** * Redraws the range of the given cells. * @param startCol index of the starting column, of the cell * @param startRow index of the starting row, of the cell * @param endCol index of the ending column, of the cell * @param endRow index of the ending row, of the cell */ invalidateGridRect(startCol: number, startRow: number, endCol: number, endRow: number): void; /** * Redraws the whole grid. */ invalidate(): void; /** * Get the value of cell with the copy action. * <p> * Please implement * </p> * @param col Column index of cell. * @param row Row index of cell. */ protected getCopyCellValue(col: number, row: number): string; /** * Draw a cell * <p> * Please implement cell drawing. * </p> * @param col Column index of cell. * @param row Row index of cell. * @param context context of cell drawing. */ protected onDrawCell(col: number, row: number, context: DrawCellContext): void; /** * Get the overflowed text in the cell rectangle, from the given cell. * @param col The column index. * @param row The row index */ getCellOverflowText(col: number, row: number): string | null; /** * Set the overflowed text in the cell rectangle, to the given cell. * @param col The column index. * @param row The row index * @param overflowText The overflowed text in the cell rectangle. */ setCellOverflowText(col: number, row: number, overflowText: boolean): void; /** * Dispose the grid instance. * @returns */ dispose(): void; } } namespace data { interface IDataSourceParam<T> { get: (index: number) => T; length: number; } export class DataSource<T> extends EventTarget { constructor(param: IDataSourceParam<T>); } export class FilterDataSource<T> extends DataSource<T> { constructor(dataSource: DataSource<T>, filter?: (record: T) => boolean | null); filter?: (record: T) => boolean | null; } interface ICachedDataSourceParam<T> { get: (index: number) => Promise<T> | T; length: number; } export class CachedDataSource<T> extends DataSource<T> { constructor(param: ICachedDataSourceParam<T>); } } interface FontIcon<T> { font: string; content: keyof T; className: string; width?: number; color?: string; } interface ImageIcon<T> { src: keyof T; className: string; width?: number; color?: string; } export interface Columnoptions<T> { caption?: string; field?: keyof T; width?: number; minWidth?: number; maxWidth?: number; icon?: FontIcon<T> | ImageIcon<T>; message?: string; columnType?: columns.type.BaseColumn | "default" | "number" | "check" | "button" | "image" | "multilinetext"; action?: columns.action.BaseAction | "check" | "input"; style?: columns.style.BaseStyle | columns.style.BaseStyleOption | ((record: T) => any) | keyof T; sort?: boolean | ((order: "asc" | "desc", col: number, grid: ListGrid<T>) => void); columns?: Columnoptions<T>[]; } export class ListGrid<T> extends cheetahGrid.core.DrawGrid { static EVENT_TYPE: cheetahGrid.core.DrawGridEvents & { CHANGED_VALUE: 'changed_value' }; constructor(options: { header?: Columnoptions<T>[], records?: T[]; dataSource?: data.DataSource<T>; frozenColCount?: number; defaultRowHeight?: number; defaultColWidth?: number; borderColor?: string; parentElement?: Element; theme?: object; }); dispose(): void; header: Columnoptions<T>[]; /** * Get the records. */ records: T[]; /** * The data source. */ dataSource: data.DataSource<T>; /** * The theme. */ theme: object; /** * Sort state. * If `null` to set, the sort state is initialized. */ sortState: object; /** * Get the field of the given column index. * @param col The column index. */ getField(col: number): any; /** * Get the record of the given row index. * @param row The row index. */ getRowRecord(row: number): T; /** * Get the column index of the given field. * @param field The field. */ getColumnIndexByField(field: any): number; /** * Focus the cell. * @param field The field. * @param index The record index */ focusGridCell(field: any, index: number): void; /** * Scroll to where cell is visible. * @param field The field. * @param index The record index */ makeVisibleGridCell(field: any, index: number): void; } namespace themes { namespace choices { /** * basic theme */ var BASIC: Object; /** * material design theme */ var MATERIAL_DESIGN: Object; } namespace theme { } } namespace tools { namespace canvashelper { function strokeColorsRect(ctx: CanvasRenderingContext2D, borderColors: any[], left: number, top: number, width: number, height: number): void; function roundRect(ctx: CanvasRenderingContext2D, left: number, top: number, width: number, height: number, radius: number): void; function fillRoundRect(ctx: CanvasRenderingContext2D, left: number, top: number, width: number, height: number, radius: number): void; function strokeRoundRect(ctx: CanvasRenderingContext2D, left: number, top: number, width: number, height: number, radius: number): void; /** * draw Checkbox * @param ctx canvas context * @param x The x coordinate where to start drawing the checkbox (relative to the canvas) * @param y The y coordinate where to start drawing the checkbox (relative to the canvas) * @param check checkbox check status * @param option option */ function drawCheckbox(ctx: CanvasRenderingContext2D, x: number, y: number, check: boolean | number, option: object): void; /** * Returns an object containing the width of the checkbox. * @param ctx canvas context */ function measureCheckbox(ctx: CanvasRenderingContext2D): { width: number }; function drawButton(ctx: CanvasRenderingContext2D, left: number, top: number, width: number, height: number, option?: any): void; function fillTextRect(ctx: CanvasRenderingContext2D, text, left: number, top: number, width: number, height: number, { offset, padding, }): void; function drawInlineImageRect(ctx: CanvasRenderingContext2D, image, srcLeft, srcTop, srcWidth, srcHeight, destWidth, destHeight, left, top, width, height, { offset, padding, }): void; } } /** * Selected area management */ class Selection extends EventTarget { /** * Selected area management */ constructor(); } /** * This class manages the drawing process for each layer */ class DrawLayers { /** * This class manages the drawing process for each layer */ constructor(); } /** * Context of cell drawing */ class DrawCellContext { /** * Context of cell drawing */ constructor(col: number, row: number, ctx: CanvasRenderingContext2D, rect: Rect, drawRect: Rect, drawing: boolean, selection: object, drawLayers: DrawLayers[]); /** * select status. */ getSelectState(): object; /** * Canvas context. */ getContext(): CanvasRenderingContext2D; /** * Rectangle of cell. */ getRect(): Rect; /** * Rectangle of Drawing range. */ getDrawRect(): Rect; /** * get Context of current state */ toCurrentContext(): DrawCellContext; /** * terminate */ terminate(): void; } class Rect { top: number; left: number; bottom: number; right: number; offsetLeft(offset: number): void; offsetTop(offset: number): void; copy(): Rect; intersection(rect: Rect): void; contains(another: Rect): void; inPoint(x: number, y: number): boolean; } class EventTarget { /** * Adds an event listener. * @param type The event type id. * @param listener Callback method. */ listen(type: string, listener: Function): number; /** * Removes an event listener which was added with listen() by the id returned by listen(). * @param id the id returned by listen(). */ unlisten(id: number): void; /** * Fires all registered listeners * @param type The type of the listeners to fire. * @param args fire arguments */ fireListeners(type: string, ...args: any): any; } } export = cheetahGrid;
the_stack
import {Midi_file, Midi_track, Midi_event, parse_midi} from "./midifmt" import { ACCIDENTAL, ORDER_OF_ACCIDENTALS, CLEF, Time_signature,Key_signature, Note_itf, Rest_itf, Slur_itf, Measure_itf, Score_itf, get_median_staff_pos, note_name_to_staff_pos, get_note_name_accidental, get_existing_voices, short_id, chord_and_beam_staff, BARLINE, BRACKET, ARTICULATION, } from "./common" const MAX_VOICES = 2; const NOTE_LENGTH : Record<string,number> = { WHOLE : 32, HALF : 16, QUARTER : 8, EIGHTH : 4, SIXTEENTH : 2, THIRTYSECOND : 1, }; const NOTE_LENGTH_QUANT = 2; const NOTE_LENGTH_MODIFIER = 1.5; const NAME2PITCH : Record<string,number> = { Ab_0:8, Ab_1:20, Ab_2:32, Ab_3:44, Ab_4:56, Ab_5:68, Ab_6:80, Ab_7:92, Ab_8:104, Ab_9:116, F_3:41, Ds_8:99, Ds_9:111, F_8:101, F_9:113, Gs_3:44, Gs_2:32, Gs_1:20, Gs_0:8, Gs_7:92, Gs_6:80, Gs_5:68, Gs_4:56, G_10:127, Gs_9:116, Gs_8:104, E_3:40, E_2:28, E_1:16, E_0:4, E_7:88, E_6:76, E_5:64, E_4:52, E_9:112, E_8:100, As_9:118, As_8:106, Ds_0:3, Ds_1:15, Ds_6:75, Ds_7:87, Ds_4:51, Ds_5:63, As_1:22, As_0:10, As_3:46, As_2:34, As_5:70, As_4:58, As_7:94, As_6:82, Cs_7:85, Cs_6:73, Cs_5:61, Cs_4:49, Bb_9:118, Cs_2:25, Cs_1:13, Cs_0:1, Bb_5:70, Bb_4:58, Bb_7:94, Bb_6:82, Bb_1:22, Bb_0:10, Cs_9:109, Cs_8:97, Bb_8:106, Bb_3:46, Bb_2:34, A_7:93, A_6:81, A_5:69, A_4:57, A_3:45, A_2:33, A_1:21, A_0:9, F_4:53, A_9:117, A_8:105, B_8:107, B_9:119, F_10:125, B_0:11, B_1:23, B_2:35, B_3:47, B_4:59, B_5:71, B_6:83, B_7:95, Fs_0:6, Fs_1:18, Fs_2:30, Fs_3:42, Fs_4:54, Fs_5:66, F_5:65, Fs_7:90, Fs_8:102, Fs_9:114, Gb_8:102, Gb_9:114, Gb_2:30, Gb_3:42, Gb_0:6, Gb_1:18, Gb_6:78, Gb_7:90, Gb_4:54, Gb_5:66, F_6:77, Fs_6:78, Eb_8:99, Eb_9:111, E_10:124, Eb_4:51, Eb_5:63, Eb_6:75, Eb_7:87, Eb_0:3, Eb_1:15, Eb_2:27, Eb_3:39, D_8:98, D_9:110, D_2:26, D_3:38, D_0:2, D_1:14, D_6:74, D_7:86, D_4:50, D_5:62, F_2:29, G_9:115, G_8:103, G_5:67, G_4:55, G_7:91, G_6:79, G_1:19, G_0:7, G_3:43, G_2:31, Cs_3:37, Db_9:109, Db_8:97, Db_3:37, Db_2:25, Db_1:13, Db_0:1, Db_7:85, Db_6:73, Db_5:61, Db_4:49, C_1:12, C_0:0, C_3:36, C_2:24, C_5:60, C_4:48, C_7:84, C_6:72, C_9:108, C_8:96, Ds_2:27, Ds_3:39, D_10:122, C_10:120, F_7:89, F_0:5, F_1:17 }; for (let i = 0; i <= 10; i++){ NAME2PITCH['Es_'+i] = NAME2PITCH['F_'+i]; NAME2PITCH['Fb_'+i] = NAME2PITCH['E_'+i]; NAME2PITCH['Bs_'+i] = NAME2PITCH['C_'+(i+1)]; NAME2PITCH['Cb_'+i] = NAME2PITCH['B_'+(i-1)]; } interface _Note_impl{ id?:string; begin: number; duration: number; pitch: number; channel: number; } interface _Measure_impl{ duration: number; time_signature: Time_signature; key_signature: Key_signature; notes: _Note_impl[]; cross_ties:Cross_tie[]; } interface Cross_tie{ left: _Note_impl; right: _Note_impl; } interface Tick_table { time_signature:Time_signature; key_signature:Key_signature; resolution:number; duration: number; notes:_Note_impl[]; }; function classify_key_signature(key_sig:number[]):Key_signature{ let [num_acc, is_minor] = key_sig; let acc = ACCIDENTAL.NATURAL if (num_acc < 0){ acc = ACCIDENTAL.FLAT num_acc = - num_acc }else if (num_acc){ acc = ACCIDENTAL.SHARP } return [acc, num_acc]; } function note_duration_overlap(a:_Note_impl,b:_Note_impl):boolean{ let x1 = a.begin; let x2 = a.begin+a.duration; let y1 = b.begin; let y2 = b.begin+b.duration; return x1 < y2 && y1 < x2; } let _pitch2name_cache : Record<string,string> = {}; function infer_name_from_pitch(pitch:number,key_signature:Key_signature){ let candidates : string[] = []; let key = pitch | (key_signature[0]<<24) | (key_signature[1]<<16); let val = _pitch2name_cache[key]; if (val !== undefined){return val;} for (let name in NAME2PITCH){ if (NAME2PITCH[name] == pitch){ candidates.push(name); } } if (candidates.length == 0){ return null; } if (candidates.length == 1){ _pitch2name_cache[key] = candidates[0]; return candidates[0]; } let [acc, num_acc] = key_signature; let acc_notes : string[] = ORDER_OF_ACCIDENTALS[acc].slice(0,num_acc).split(''); for (let n of acc_notes){ for (let i = 0; i < candidates.length; i++){ if (acc == ACCIDENTAL.SHARP && candidates[i].startsWith(n+"s")){ _pitch2name_cache[key] = candidates[i]; return candidates[i]; }else if (acc == ACCIDENTAL.FLAT && candidates[i].startsWith(n+"b")){ _pitch2name_cache[key] = candidates[i]; return candidates[i]; } } } _pitch2name_cache[key] = candidates[0]; return candidates[0]; } function pitch_to_staff(pitch:number, clef:number, key_signature:Key_signature){ pitch = ~~pitch; let name : string = infer_name_from_pitch(pitch,key_signature=key_signature); let i0 = (clef == CLEF.TREBLE) ? (6*7+3) : (5*7-2); let idx = i0-("CDEFGAB".indexOf(name[0])+Number(name.split("_")[1])*7); return idx; } function compare_wholeness(a:number,b:number){ for (let i = 5; i >= 0; i--){ let p : number = Math.pow(2,i); let ap : number = a/p; let bp : number = b/p; ap -= ~~(ap); bp -= ~~(bp); if (ap == 0 && bp == 0){ return 0; }else if (ap > 0 && bp == 0){ return -1; }else if (ap == 0 && bp > 0){ return 1; } } return 0; } function factor_rest_duration(begin:number,dur:number,channel:number):Rest_itf[]{ let l = dur; let b = begin; let rests : Rest_itf[] = []; while (l > 0){ let ll = 0; for (let p = 0; p <= 5; p++){ let d = Math.pow(2,p); if (l < d){ break; } // console.log(b,d,compare_wholeness(b + d, b)) if (compare_wholeness(b + d, b)>0){ ll = d; break; } } if (!ll){ for (let p = 5; p >= 0; p--){ let d = Math.pow(2,p); if (l >= d){ ll = d; break; } } } rests.push({ begin:b, duration:ll, voice:channel, tuplet:null }); l -= ll; b += ll; } return rests; } function find_rests(measure:Measure_itf,staff_idx:number,channels:number[]):Rest_itf[]{ // find & merge rests let measure_length = measure.duration; let staff = measure.staves[staff_idx]; let rests : Rest_itf[] = []; // console.log(staff,channels); let did : boolean = false; for (let c of channels){ let channel_notes = staff.notes.filter(x=>x.voice==c); if (!channel_notes.length){ continue; } did = true; let bins = new Array(measure_length).fill(true); for (let i= 0; i < measure_length; i++){ for (let m of channel_notes){ if (m.voice == c){ if (m.begin <= i && i < m.begin + m.duration){ bins[i] = false; break; } } } } let last_length : number = 0; for (let i = 0; i < bins.length+1; i++){ if (i < bins.length && bins[i]){ last_length ++; }else{ if (last_length > 0){ rests.push(...factor_rest_duration(i-last_length,last_length,c)); } last_length = 0; } } } if (!did){ rests.push(...factor_rest_duration(0,measure_length,channels[0])); } return rests; } function get_piece_title(pattern:Midi_file):string[]{ let title : string[] = []; // let found : boolean = false; for (let track of pattern.tracks){ for (let event of track.events){ // console.log(event.type) if (event.type == 'SEQUENCE_OR_TRACK_NAME'){ // console.log(event); title.push(...event.data['text'].split('\n')); // found = true; } } // if (found) break; } // if (!title) return []; return title; } function get_piece_instruments(pattern:Midi_file):string[]{ let instruments = [] for (let track of pattern.tracks){ for (let event of track.events){ if (event.type == 'INSTRUMENT_NAME'){ instruments.push(event.data['text']); } } } return instruments; } function is_note_on_event(evt:Midi_event):boolean{ return evt.type == 'NOTE_ON' && evt.data['velocity'] != 0; } function is_note_off_event(evt:Midi_event):boolean{ return evt.type == 'NOTE_OFF' || (evt.type == 'NOTE_ON' && evt.data['velocity'] == 0); } function pattern_to_tick_tables(pattern:Midi_file):Tick_table[]{ // change relative tick into absolute tick // duration in ticks, pitch 0-127, channel: 16*track + origin channel let res = pattern.ticks_per_quarter_note; let sections : Array<[ number, [Time_signature,Key_signature], Array<Record<string,any>> ]> = []; // console.dir(pattern,{depth:null,maxArrayLength:null}); let track_id = -1; let end_of_track = 0; let last_time_sig = null; let last_key_sig = null; for (let track of pattern.tracks){ track_id += 1 let t : number = 0; for (let event of track.events){ t += event.delta_time; if (event.type == 'TIME_SIGNATURE' && track_id == 0){ let ts : Time_signature = [event.data['numerator'],2**event.data['denominator_exp']]; if (sections.length == 0 || (sections[sections.length-1][1][0] != null)){ sections.push([t,[ts,last_key_sig], []]); }else{ sections[sections.length-1][1][0] = ts; } last_time_sig = ts; }else if (event.type == 'KEY_SIGNATURE' && track_id == 0){ let ks : Key_signature = classify_key_signature([event.data['num_sharps_or_flats'], event.data['is_minor']]); if (sections.length == 0 || (sections[sections.length-1][1][1] != null)){ sections.push([t,[last_time_sig,ks], []]); }else{ sections[sections.length-1][1][1] = ks; } last_key_sig = ks; }else if (event.type == 'END_OF_TRACK'){ end_of_track = Math.max(t,end_of_track); }else{ for (let i = 0; i < sections.length; i++){ let idx = sections.length-i-1; if (t >= sections[idx][0]){ if (event.type == 'NOTE_ON' || event.type == 'NOTE_OFF'){ let name : string; if (is_note_on_event(event)){ name = 'NOTE_ON'; }else if (is_note_off_event(event)){ name = 'NOTE_OFF'; } sections[idx][2].push({name,abs_tick:t-sections[idx][0],pitch:event.data['key'],channel:(track_id*16+event.data['channel'])*100}); } break; } } } } } // console.dir(sections,{depth:null,maxArrayLength:null}); let unpaired : Array<[boolean,number,number,Record<string,any>]>= []; for (let i = 0; i < sections.length; i++){ for (let j = 0; j < sections[i][2].length; j++){ let note = sections[i][2][j]; if (note.name == 'NOTE_ON'){ unpaired.unshift([true, i, j, note]); }else if (note.name == 'NOTE_OFF'){ for (let k = 0; k < unpaired.length; k++){ let up = unpaired[k]; if (up[0] && up[3].channel == note.channel && up[3].pitch == note.pitch){ unpaired[k][0] = false; sections[up[1]][2][up[2]].duration = note.abs_tick-up[3].abs_tick; break; } } } } } let tick_tables : Tick_table[] = []; for (let i = 0; i < sections.length; i++){ let end_tick : number = (i+1 < sections.length) ? sections[i+1][0] : end_of_track; tick_tables.push({ time_signature:sections[i][1][0], key_signature:sections[i][1][1] ?? [0,0], resolution:res, duration:end_tick-sections[i][0], notes:[], }); for (let j = 0; j < sections[i][2].length; j++){ let note = sections[i][2][j]; if (sections[i][2][j].name=='NOTE_ON'){ if (note.duration !== undefined){ let dur = note.duration; tick_tables[tick_tables.length-1].notes.push({ begin:note.abs_tick, pitch:note.pitch, duration:dur, channel:note.channel }); }else{ console.warn(`WARNING: Unpaired NOTE_ON event, discarding!`,note); } } } } return tick_tables; } function split_voices(measures:_Measure_impl[]){ function collide(a:_Note_impl,b:_Note_impl){ if (a.begin == b.begin && a.duration == b.duration){ // console.log(a.pitch,b.pitch) return a.pitch == b.pitch; } return note_duration_overlap(a,b); } function collide_with_channel(measure:_Measure_impl,index:number){ let channel = measure.notes[index].channel; for (let i = 0; i < index/*measure.notes.length*/; i++){ // if (i == index){ // continue; // } if (measure.notes[i].channel != channel){ continue; } if (collide(measure.notes[index],measure.notes[i])){ return true; } } return false; } for (let i = 0; i < measures.length; i++){ let notes = measures[i].notes; let cross_ties : Cross_tie[] = measures[i].cross_ties; for (let j = 0; j < notes.length; j++){ let note : _Note_impl = notes[j]; let skip : boolean = false; for (let k = 0; k < cross_ties.length; k++){ if (note == cross_ties[k].right){ skip = true; break; } } if (skip) continue; while (collide_with_channel(measures[i],j)){ note.channel++; } for (let k = 0; k < measures[i].cross_ties.length; k++){ if (measures[i].cross_ties[k].left == note){ measures[i].cross_ties[k].right.channel = note.channel; } } } } } function classify_note_length(length:number):[number,boolean]{ let d0 = 1024; let l0 = -1; let mod = false; for (let k in NOTE_LENGTH){ let l = NOTE_LENGTH[k]; let d = Math.abs(length-l); if (d < d0){ l0 = l; d0 = d; } } for (let k in NOTE_LENGTH){ let l = ~~(NOTE_LENGTH[k]*NOTE_LENGTH_MODIFIER); let d = Math.abs(length-l) if (d < d0){ mod = true; l0 = l; d0 = d; } } return [l0,mod]; } function has_modifier(length:number):boolean{ if (length == NOTE_LENGTH.THIRTYSECOND * NOTE_LENGTH_MODIFIER) return true; if (length == NOTE_LENGTH.SIXTEENTH * NOTE_LENGTH_MODIFIER) return true; if (length == NOTE_LENGTH.EIGHTH * NOTE_LENGTH_MODIFIER) return true; if (length == NOTE_LENGTH.QUARTER * NOTE_LENGTH_MODIFIER) return true; if (length == NOTE_LENGTH.HALF * NOTE_LENGTH_MODIFIER) return true; if (length == NOTE_LENGTH.WHOLE * NOTE_LENGTH_MODIFIER) return true; return false; } function tick2length(tick:number,resolution:number):number{ let ticks_per_quarter_note = resolution; let num_quarter_notes = tick/ticks_per_quarter_note; let num_32nd_notes = num_quarter_notes * (NOTE_LENGTH.QUARTER/NOTE_LENGTH.THIRTYSECOND); return num_32nd_notes; } function length2tick(length:number,resolution:number):number{ let num_32nd_notes = length; let num_quarter_notes = num_32nd_notes * (NOTE_LENGTH.THIRTYSECOND*1.0/NOTE_LENGTH.QUARTER); let ticks_per_quarter_note = resolution; let num_ticks = num_quarter_notes * ticks_per_quarter_note; return ~~num_ticks } function tick_table_to_measures(tick_table:Tick_table):_Measure_impl[]{ let time_sig = tick_table.time_signature; let key_sig = tick_table.key_signature; let resolution = tick_table.resolution; let notes = tick_table.notes; let measures : _Measure_impl[] = []; function getmeasurelength(){ let ticks_per_quarter_note = resolution; let num_beats = time_sig[0]; let num_32nd_notes_per_beat = ~~(NOTE_LENGTH.WHOLE/time_sig[1]); let num_32nd_notes = num_32nd_notes_per_beat * num_beats; return num_32nd_notes; } function getmeasureticks(){ let num_32nd_notes = getmeasurelength(); return length2tick(num_32nd_notes,resolution); } let measure_duration = getmeasureticks(); let measure_length = getmeasurelength(); function getlength(tick:number):number{ return ~~(tick2length(tick,resolution)); } function empty_measure():_Measure_impl{ return {time_signature:time_sig,key_signature:key_sig, duration: getlength(measure_duration), notes:[], cross_ties:[], }; } while (tick_table.duration > measure_duration * measures.length){ measures.push(empty_measure()) } for (let i = 0; i < notes.length; i++){ let note : _Note_impl = notes[i]; let measure_id = ~~(note.begin/measure_duration); while (measure_id >= measures.length){ measures.push(empty_measure()) } let begin = getlength(note.begin-measure_id*measure_duration); let [length,modifier] = classify_note_length(tick2length(note.duration,resolution)); let channel = note.channel; let pitch = note.pitch; let nnote = {begin,channel,pitch, duration: Math.min(length,measure_length-begin), }; measures[measure_id].notes.push(nnote); let carry_cnt = 1; let left : _Note_impl = nnote; while (begin + length > measure_length){ if (measure_id+carry_cnt >= measures.length){ measures.push(empty_measure()) } let right : _Note_impl = { begin: 0, duration: Math.min(measure_length, begin + length - measure_length), channel, pitch } measures[measure_id+carry_cnt].notes.push(right); measures[measure_id+carry_cnt-1].cross_ties.push({left,right}); measures[measure_id+carry_cnt].cross_ties.push({left,right}); length = (begin + length) - measure_length; begin = 0; carry_cnt += 1; left = right; } } return measures; } function compile_staff( measure:Measure_itf, staff_idx:number ){ let staff = measure.staves[staff_idx]; let [measure_acc, num_acc] = staff.key_signature; let acc_names : string[] = ORDER_OF_ACCIDENTALS[measure_acc].slice(0,num_acc).split(''); let acc_history : Record<string,number> = {}; function get_beat_length(time_sig:Time_signature){ let beat_length = ~~(NOTE_LENGTH.WHOLE/time_sig[1]); if (time_sig[1] == 4 && time_sig[0] >= 4){ beat_length *= 2; } return beat_length; } let beat_length = get_beat_length(staff.time_signature); let channels = get_existing_voices(staff.notes.concat(staff.rests as Note_itf[]),[]); staff.voices = channels.length; function get_beat_idx(note:Note_itf) : number{ return ~~(note.begin/beat_length); } function get_notes_in_beat(beat_idx:number) : Note_itf[]{ let notes : Note_itf[] = []; for (let m of staff.notes){ if (get_beat_idx(m) == beat_idx){ notes.push(m); } } return notes; } function calc_stem_dir(note:Note_itf){ let beat_idx : number = get_beat_idx(note); let notes_in_beat : Note_itf[] = get_notes_in_beat(beat_idx); // console.log(notes_in_beat); let avg_line : number = notes_in_beat.reduce((acc:number,x:Note_itf):number=>(acc+x.staff_pos),0)/notes_in_beat.length; if (avg_line < 4){ return 1; }else{ return -1; } } for (let i = 0; i < staff.notes.length; i++){ let note : Note_itf = staff.notes[i]; // console.log(note); let note_name = note.name; let note_oct = Number(note_name.split('_')[1]); let note_staff = note_name_to_staff_pos(note_name, staff.clef); note.octave = note_oct; note.staff_pos = note_staff; let modifier = has_modifier(note.duration); note.modifier = modifier; } for (let i = 0; i < staff.notes.length; i++){ let accidental : number = null; let note = staff.notes[i]; let note_name = note.name; let note_bname = note_name[0]; let note_acc = get_note_name_accidental(note_name); let key = note_bname + '_' + note.octave; if (acc_names.includes(note_bname)){ if (note_acc == measure_acc){ if (acc_history[key] === undefined || acc_history[key] === note_acc){ // ok... }else{ accidental = note_acc; acc_history[key] = note_acc; } }else{ accidental = note_acc; acc_history[key] = note_acc; } }else{ if (note_acc == ACCIDENTAL.NATURAL){ if (acc_history[key]){ accidental = note_acc; acc_history[key] = note_acc; } }else{ if (acc_history[key] !== note_acc){ accidental = note_acc; acc_history[key] = note_acc; } } } note.accidental = accidental; } let channel_median_staff_pos = get_median_staff_pos(staff.notes); let channel_to_voice : Record<number,number> = {}; let voice_median_staff_pos : Record<number,number> = {}; let channels_sorted = Object.entries(channel_median_staff_pos).sort((a,b)=>a[1]-b[1]); for (let i = 0; i < channels_sorted.length; i++){ channel_to_voice[channels_sorted[i][0]] = i; voice_median_staff_pos[i] = channel_median_staff_pos[channels_sorted[i][0]]; } for (let i = 0; i < staff.notes.length; i++){ staff.notes[i].voice = channel_to_voice[staff.notes[i].voice]??0; } for (let i = 0; i < staff.rests.length; i++){ staff.rests[i].voice = channel_to_voice[staff.rests[i].voice]??0; } for (let i = 0; i < staff.notes.length; i++){ let note = staff.notes[i]; let stem_dir :number; if (staff.voices == 1){ stem_dir = calc_stem_dir(note); }else{ stem_dir = note.voice % 2 ? 1 : -1; } note.stem_dir = stem_dir; } chord_and_beam_staff(staff,beat_length); for (let i = 0; i < staff.notes.length; i++){ staff.notes[i].duration *= NOTE_LENGTH_QUANT; staff.notes[i].begin *= NOTE_LENGTH_QUANT; } for (let i = 0; i < staff.rests.length; i++){ staff.rests[i].duration *= NOTE_LENGTH_QUANT; staff.rests[i].begin *= NOTE_LENGTH_QUANT; } } function get_channel_average_pitch(measures:_Measure_impl[]):Record<number,number>{ let c2p : Record<number,[number,number]> = {} for (let m of measures){ for (let n of m.notes){ if (!c2p[n.channel]){ c2p[n.channel] = [0,0]; } c2p[n.channel][0] += n.pitch; c2p[n.channel][1] ++; } } let c2p2 : Record<number,number> = {}; for (let k in c2p){ c2p2[k] = c2p[k][1]?(c2p[k][0]/c2p[k][1]):0; } return c2p2; } function assign_clef_from_pitch(pitch:number):number{ if (pitch > NAME2PITCH["C_5"]){ return CLEF.TREBLE; }else{ return CLEF.BASS; } } export function score_from_midi(pattern:Midi_file):Score_itf{ let tick_tables : Tick_table[]= pattern_to_tick_tables(pattern); // console.dir(tick_tables,{depth:null,maxArrayLength:10000}); let measures_ : _Measure_impl[] = []; for (let i = 0; i < tick_tables.length; i++){ let ms = tick_table_to_measures(tick_tables[i]); for (let j = 0; j < ms.length; j++){ measures_.push(ms[j]); } } split_voices(measures_); let channel2pitch : Record<number,number> = get_channel_average_pitch(measures_); let channel2clef : Record<number,number> = {}; for (let k in channel2pitch){ channel2clef[k] = assign_clef_from_pitch(channel2pitch[k]); } let channels = Object.keys(channel2pitch).map(Number).sort((a,b)=>a-b); let channel_groups_ : Record<number,number[]> = {} for (let i = 0; i < channels.length; i++){ let g = ~~(channels[i]/100); let g0 = channels[i] - g*100; let g1 = ~~(g0/MAX_VOICES); // let g1 = g0 % RENDER.MAX_VOICES; let gg = g * 100 + g1; // console.log(channels[i],g,g0,g1,gg) if (!channel_groups_[gg]) channel_groups_[gg] = []; channel_groups_[gg].push(channels[i]); } let channel_groups : number[][] = Object.values(channel_groups_); let score : Score_itf = { title:get_piece_title(pattern), instruments:[],//get_piece_instruments(pattern).map(x=>({names:[x],connect_barlines:[false],bracket:BRACKET.NONE})), composer:[], slurs:[], measures:[], crescs:[], }; for (let i = 0; i< measures_.length; i++){ let ties : Cross_tie[] = measures_[i].cross_ties; for (let j = 0; j < ties.length; j++){ let slur = {left:ties[j].left.id??short_id(),right:ties[j].right.id??short_id(),is_tie:true}; ties[j].left.id = slur.left; ties[j].right.id = slur.right; score.slurs.push(slur); } } for (let i = 0; i < measures_.length; i++){ let measure : Measure_itf = { duration: measures_[i].duration, barline: (i==measures_.length)?BARLINE.END:BARLINE.SINGLE, staves: [], }; for (let j = 0; j < channel_groups.length; j++){ let ch_group = channel_groups[j]; measure.staves.push({ clef:channel2clef[ch_group[0]], time_signature: measures_[i].time_signature, key_signature: measures_[i].key_signature, notes:[], rests:[], grace:[], voices:null, beams:[], }); for (let k = 0; k < measures_[i].notes.length; k++){ if (ch_group.includes(measures_[i].notes[k].channel)){ let name = infer_name_from_pitch(measures_[i].notes[k].pitch, measures_[i].key_signature); let note : Note_itf = { begin:measures_[i].notes[k].begin, duration:measures_[i].notes[k].duration, accidental:null, modifier:null, octave:null, name, voice:measures_[i].notes[k].channel, staff_pos:null, stem_dir:null, prev_in_chord:null, next_in_chord:null, tuplet:null, } if (measures_[i].notes[k].id){ note.id = measures_[i].notes[k].id; } measure.staves[j].notes.push(note); } } measure.staves[j].rests.push(...find_rests(measure,j,ch_group)); compile_staff(measure,j); // console.dir(measures[i],{depth:null}); } measure.duration*=2; score.measures.push(measure); } return score; } export function score_to_midi(score : Score_itf) : Midi_file{ let meta_track : Midi_track = {events:[]}; let tracks : Midi_track[] = []; let tied_lefts : Record<string,boolean> = {}; let tied_rights : Record<string,boolean> = {}; for (let i = 0; i < score.slurs.length; i++){ if (score.slurs[i].is_tie){ tied_lefts[score.slurs[i].left] = true; tied_rights[score.slurs[i].right] = true; } } meta_track.events.push({type:"SEQUENCE_OR_TRACK_NAME",delta_time:0,data:{text:score.title.concat(score.composer).join('\n')}}); let instruments = []; for (let i = 0; i < score.instruments.length; i++){ instruments.push(...score.instruments[i].names); } for (let j = 0; j < score.measures[0].staves.length; j++){ let T : number = 0; for (let i = 0; i < score.measures.length; i++){ if (!tracks[j]){ tracks[j] = {events:[]}; if (instruments[j]){ tracks[j].events.push({type:'INSTRUMENT_NAME',delta_time:0,data:{text:instruments[j]}}) } } if (j == 0){ if (i == 0 || score.measures[i].staves[j].key_signature.toString() != score.measures[i-1].staves[j].key_signature.toString()){ let [acc, num_acc] = score.measures[i].staves[j].key_signature; meta_track.events.push({type:'KEY_SIGNATURE',delta_time:T,data:{num_sharps_or_flats:acc*num_acc,is_minor:0}}); } if (i == 0 || score.measures[i].staves[j].time_signature.toString() != score.measures[i-1].staves[j].time_signature.toString()){ let [numerator, denominator] = score.measures[i].staves[j].time_signature; let denominator_exp = Math.log2(denominator); meta_track.events.push({type:'TIME_SIGNATURE',delta_time:T,data:{numerator,denominator_exp,clocks_per_metronome_click:24,notated_32nd_per_quarter_note:8}}); } } for (let k = 0; k < score.measures[i].staves[j].notes.length; k++){ let note = score.measures[i].staves[j].notes[k]; let t0 = note.begin; let d = note.duration; let v = 100; if (note.articulation == ARTICULATION.STACCATO){ d /= 2; } if (note.articulation == ARTICULATION.SPICCATO){ d /= 4; } if (note.articulation == ARTICULATION.ACCENT){ v = 125; } let t1 = t0+d; if (note.prev_in_chord != null || note.next_in_chord != null ){ let first = note; let last = note; let count_prev = 0; let count_next = 0; let is_arp = note.articulation == ARTICULATION.ARPEGGIATED; while (first.prev_in_chord != null){ first = score.measures[i].staves[j].notes[first.prev_in_chord]; is_arp = is_arp || (first.articulation == ARTICULATION.ARPEGGIATED) count_prev ++; } while (last.next_in_chord != null){ last = score.measures[i].staves[j].notes[last.next_in_chord]; is_arp = is_arp || (last.articulation == ARTICULATION.ARPEGGIATED) count_next ++; } if (is_arp){ let idx : number; if (first.staff_pos < last.staff_pos){ idx = count_next; }else{ idx = count_prev; } t0 += Math.min(2,note.duration/(count_next+count_prev+1))*idx; } } if (score.measures[i].staves[j].grace[note.begin]){ t0 = Math.min(t1-1,Math.max(t0,note.begin+score.measures[i].staves[j].grace[note.begin].duration/4)); } if (note.articulation != ARTICULATION.TRILL && note.articulation != ARTICULATION.TREMBLEMENT){ if (!tied_rights[note.id]){ tracks[j].events.push({type:'NOTE_ON', delta_time:T+t0,data:{key:NAME2PITCH[note.name],velocity: v,channel:0}}); } if (!tied_lefts[note.id]){ tracks[j].events.push({type:'NOTE_OFF',delta_time:T+t1,data:{key:NAME2PITCH[note.name],velocity: 0,channel:0}}); } }else{ let above = String.fromCharCode(note.name[0].charCodeAt(0)+1); if (above == 'H'){ above = 'A' + note.name.slice(1);; }else if (above == 'C'){ above += note.name.slice(1); above = above.split('_')[0]+'_'+(note.octave+1); }else{ above += note.name.slice(1); } let flip = false; for (let i = t0; i < t1; i++){ tracks[j].events.push({type:'NOTE_ON', delta_time:T+i, data:{key:NAME2PITCH[flip?above:note.name],velocity: v,channel:0}}); tracks[j].events.push({type:'NOTE_OFF',delta_time:T+i+1,data:{key:NAME2PITCH[flip?above:note.name],velocity: 0,channel:0}}); flip = !flip; } } } for (let k = 0; k < score.measures[i].staves[j].grace.length; k++){ if (!score.measures[i].staves[j].grace[k]) continue; for (let l = 0; l < score.measures[i].staves[j].grace[k].staves[0].notes.length; l++){ let note = score.measures[i].staves[j].grace[k].staves[0].notes[l]; tracks[j].events.push({type:'NOTE_ON', delta_time:T+k+note.begin/4, data:{key:NAME2PITCH[note.name],velocity:100,channel:0}}); tracks[j].events.push({type:'NOTE_OFF',delta_time:T+k+(note.begin+note.duration)/4,data:{key:NAME2PITCH[note.name],velocity: 0,channel:0}}); } } T += score.measures[i].duration; } } tracks.unshift(meta_track); for (let j = 0; j < tracks.length; j++){ tracks[j].events.sort((a,b)=>(a.delta_time-b.delta_time)); for (let k = tracks[j].events.length-1; k > 0; k--){ tracks[j].events[k].delta_time -= tracks[j].events[k-1].delta_time; } } for (let j = 0; j < tracks.length; j++){ for (let k = 0; k < tracks[j].events.length; k++){ tracks[j].events[k].delta_time = ~~(tracks[j].events[k].delta_time*6); } tracks[j].events.push({ type: 'END_OF_TRACK', delta_time: 0, data: {} }) } let pattern : Midi_file = { magic:'MThd', tracks, num_tracks:tracks.length, format:1, time_format:"METRIC", ticks_per_quarter_note: 96, }; return pattern; }
the_stack
import * as React from 'react' import { RouteComponentProps } from 'react-router' import { Form, Field } from 'react-final-form' import arrayMutators from 'final-form-arrays' import TEMPLATE from './Template' import { UploadedFile } from 'src/pages/common/UploadedFile/UploadedFile' import { InputField, DatePickerField } from 'src/components/Form/Fields' import { Button } from 'src/components/Button' import { EventStore } from 'src/stores/Events/events.store' import Heading from 'src/components/Heading' import Text from 'src/components/Text' import Flex from 'src/components/Flex' import { TagsSelectField } from 'src/components/Form/TagsSelect.field' import { inject } from 'mobx-react' import { PostingGuidelines } from './PostingGuidelines' import { IEventFormInput } from 'src/models/events.models' import { LocationSearchField } from 'src/components/Form/LocationSearch.field' import styled from 'styled-components' import theme from 'src/themes/styled.theme' import { validateUrl, addProtocolMutator, required } from 'src/utils/validators' import { Box } from 'rebass' import ElWithBeforeIcon from 'src/components/ElWithBeforeIcon' import IconHeaderEvents from 'src/assets/images/header-section/events-header-icon.svg' interface IState { formValues: IEventFormInput formSaved: boolean showSubmitModal?: boolean selectedDate: any isLocationSelected?: boolean } type IProps = RouteComponentProps<any> interface IInjectedProps extends IProps { eventStore: EventStore } const FormContainer = styled.form` width: 100%; ` const Label = styled.label` font-size: ${theme.fontSizes[2] + 'px'}; margin-bottom: ${theme.space[2] + 'px'}; ` @inject('eventStore') export class EventsCreate extends React.Component<IProps, IState> { uploadRefs: { [key: string]: UploadedFile | null } = {} constructor(props: any) { super(props) // generate unique id for db and storage references and assign to state this.state = { formValues: { ...TEMPLATE.INITIAL_VALUES }, formSaved: false, selectedDate: null, } } get injected() { return this.props as IInjectedProps } get store() { return this.injected.eventStore } public onSubmit = async (formValues: IEventFormInput) => { console.log('form values', formValues) await this.store.uploadEvent(formValues) this.props.history.push('/events') } public handleChange = (date: any) => { this.setState({ selectedDate: date, }) } public render() { const { formValues, isLocationSelected } = this.state return ( <Form onSubmit={v => { const datepickerDate = this.state.selectedDate // convert from Date type to yyyy/mm/dd string and back into local timezone const convert = new Date( datepickerDate.getTime() - datepickerDate.getTimezoneOffset() * 60000, ) .toISOString() .substring(0, 10) v.date = convert this.onSubmit(v as IEventFormInput) }} initialValues={formValues} mutators={{ ...arrayMutators, addProtocolMutator, }} validateOnBlur render={({ form: { mutators }, submitting, handleSubmit }) => { return ( <Flex mx={-2} bg={'inherit'} flexWrap="wrap"> <Flex bg="inherit" px={2} width={[1, 1, 2 / 3]} mt={4}> <FormContainer onSubmit={e => e.preventDefault()}> {/* How To Info */} <Flex flexDirection={'column'}> <Flex card mediumRadius bg={theme.colors.softblue} px={3} py={2} alignItems="center" > <Heading medium>Create an event</Heading> <Box ml="15px"> <ElWithBeforeIcon IconUrl={IconHeaderEvents} height="20px" /> </Box> </Flex> <Box sx={{ mt: '20px', display: ['block', 'block', 'none'] }} > <PostingGuidelines /> </Box> <Flex card mediumRadius bg={'white'} mt={5} p={4} flexWrap="wrap" flexDirection="column" > <Flex flexDirection={'column'} mb={3} width={[1, 1, 2 / 3]} > <Label htmlFor="title">Title of the event *</Label> <Field id="title" name="title" data-cy="title" validate={required} validateFields={[]} modifiers={{ capitalize: true }} component={InputField} maxLength="140" placeholder="Title of your event (max 140 characters)" /> </Flex> <Flex mx={-2} width={1} flexDirection={['column', 'column', 'row']} > <Flex flexDirection={'column'} mb={3} px={2} width={1} data-cy="date" > <Label htmlFor="location"> When is your event taking place? * </Label> <Field className="datepicker" component={DatePickerField} name="date" type="date" dateFormat="yyyy/MM/dd" validate={required} selected={this.state.selectedDate} customChange={date => this.handleChange(date)} placeholderText="yyyy/mm/dd" /> </Flex> <Flex flexDirection={'column'} mb={3} px={2} width={1}> <Label htmlFor="location"> In which city is the event taking place? * </Label> <Field id="location" name="location" className="location-search-create" validateFields={[]} validate={required} customChange={() => { this.setState({ isLocationSelected: true, }) }} component={LocationSearchField} /> {isLocationSelected !== undefined && !isLocationSelected && ( <Text small color={theme.colors.red} mb="5px"> Select a location for your event </Text> )} </Flex> </Flex> <Flex mx={-2} width={1} flexDirection={['column', 'column', 'row']} > <Flex flexDirection={'column'} mb={3} px={2} width={1}> <Label htmlFor="location"> Select tags for your event * </Label> <Field name="tags" component={TagsSelectField} category="event" /> </Flex> <Flex flexDirection={'column'} mb={3} px={2} width={1}> <Label htmlFor="location">Link to your event *</Label> <Field name="url" data-cy="url" validateFields={[]} validate={value => validateUrl(value)} component={InputField} placeholder="URL to offsite link (Facebook, Meetup, etc)" customOnBlur={e => mutators.addProtocolMutator(e.target.name) } /> </Flex> </Flex> </Flex> </Flex> </FormContainer> </Flex> {/* post guidelines container */} <Flex flexDirection={'column'} width={[1, 1, 1 / 3]} height={'100%'} bg="inherit" px={2} mt={4} > <Box sx={{ display: ['none', 'none', 'block'] }}> <PostingGuidelines /> </Box> <Button onClick={() => { if (isLocationSelected) { handleSubmit() } else { this.setState({ isLocationSelected: false }) } }} width={1} mt={3} variant={'primary'} disabled={submitting} data-cy="submit" sx={{ mb: ['40px', '40px', 0] }} > Publish </Button> </Flex> </Flex> ) }} /> ) } }
the_stack
import {Token, TokenFormat, TokenMeta, Tokens} from './types'; const BASE_SPACING_UNIT_REM = 0.25; const NUMBER_OF_ITEMS_IN_100_SCALES = 10; const FRAMES_PER_SECOND = 60; const ONE_FRAME = 1000 / FRAMES_PER_SECOND; interface DefaultColors { [hueName: string]: { name: string; hue: number; }; } const defaultColors: DefaultColors = { azure: { name: 'Azure', hue: 209, }, blue: { name: 'Blue', hue: 247, }, cyan: { name: 'Cyan', hue: 194, }, gray: { name: 'Cyan', hue: 210, }, green: { name: 'Green', hue: 157, }, lime: { name: 'Lime', hue: 112, }, magenta: { name: 'Magenta', hue: 323, }, orange: { name: 'Orange', hue: 39, }, rose: { name: 'Rose', hue: 347, }, teal: { name: 'Teal', hue: 187, }, violet: { name: 'Violet', hue: 280, }, yellow: { name: 'Yellow', hue: 65, }, }; // Copy pasta from https://stackoverflow.com/a/44134328/6488971 function hslToHex(hue: number, saturation: number, lightness: number): string { const decimalLightness = lightness / 100; const someMagicalValue = (saturation * Math.min(decimalLightness, 1 - decimalLightness)) / 100; const _f = (someNumber: number) => { const anotherMagicalValue = (someNumber + hue / 30) % 12; const color = decimalLightness - someMagicalValue * Math.max( Math.min(anotherMagicalValue - 3, 9 - anotherMagicalValue, 1), -1, ); return Math.round(255 * color) .toString(16) .padStart(2, '0'); }; return `#${_f(0)}${_f(8)}${_f(4)}`; } const createTokenNameForFormat = ( format: TokenFormat | 'figma', tokenName: string, ) => { switch (format) { case 'figma': return tokenName.replace(/-/g, '/'); case 'sass': return `$${tokenName}`; case 'css': return `--p-${tokenName}`; } }; /** * Creates an "extension" object for each token. * * @param tokenName * @returns A Token metadata object */ const createTokenMeta = (tokenName: string): TokenMeta => { return { figmaName: createTokenNameForFormat('figma', tokenName), SassName: createTokenNameForFormat('sass', tokenName), CSSName: createTokenNameForFormat('css', tokenName), }; }; const formatCSSTokens = (tokens: Tokens) => { const tab = ` `; const lines: string[] = []; lines.push(':root {'); Object.entries(tokens).forEach(([_, token]) => { const varName = token.meta.CSSName; if (varName && token.value) { lines.push(`${tab}${varName}: ${token.value};`); } else if (token.aliasOf) { const alias = createTokenNameForFormat('css', token.aliasOf); lines.push(`${tab}${varName}: var(${alias});`); } }); lines.push('}'); return lines.join('\n'); }; const formatSassTokens = (tokens: Tokens) => { const lines: string[] = []; Object.entries(tokens).forEach(([_, token]) => { const varName = token.meta.SassName; if (varName) { if (token.value) { lines.push(`${varName}: ${token.value};`); } else if (token.aliasOf) { const alias = createTokenNameForFormat('sass', token.aliasOf); lines.push(`${varName}: ${alias};`); } } }); return lines.join('\n'); }; type Formats = {[T in TokenFormat]: (tokens: Tokens) => string}; const formats: Formats = { css: formatCSSTokens, sass: formatSassTokens, }; interface FormatTokensOptions { tokens: Tokens; format: TokenFormat; } /** * Transforms tokens into various formats like CSS and Sass. * * @param tokens - The tokens to transform * @param format - The output format * @returns - A string with the tokens in the right format */ export const formatTokens = (options: FormatTokensOptions): string => { const {format, tokens} = options; return formats[format](tokens); }; /** * Generates a Tokens containing all the available tokens * * @returns A Tokens object */ export const getAllTokens = (): Tokens => { return { ...getSpacingTokens(), ...getTypographyTokens(), ...getBreakpointTokens(), ...getColorTokens(), ...getMotionTokens(), }; }; /** * Generates color tokens * * @param levers - Configuration for the colors * @returns A Tokens */ export const getColorTokens = (): Tokens => { const tokens: Tokens = {}; const saturation = 80; // Loop through our colors (hues) Object.entries(defaultColors).forEach(([hueName, color]) => { const numOfShades = 20; const steps = numOfShades + 1; const hue = color.hue; // Create 21 tokens for each hue, each with a higher lightness for (let i = 0; i < steps; i++) { const lightness = Math.round((i / (steps - 1)) * 100); const tokenName = `${hueName}-${i * 50}`; tokens[tokenName] = { value: hslToHex(hue, saturation, lightness), description: `A ${hueName} color with a lightness of ${lightness}%`, meta: createTokenMeta(tokenName), }; } }); tokens.negative = { aliasOf: 'magenta-500', description: 'Used for errors etc', meta: createTokenMeta('negative'), }; tokens.positive = { aliasOf: 'green-500', description: 'Used for success messages etc', meta: createTokenMeta('positive'), }; return tokens; }; const getSpaceTokenName = (index: number) => `space-${index * 100}`; /** * Generates spacing tokens * * @param {Object} levers - Configuration for the spacing * @returns A Tokens */ export const getSpacingTokens = (): Tokens => { const tokens: Tokens = {}; for (let i = 1; i <= NUMBER_OF_ITEMS_IN_100_SCALES; i++) { const tokenName = getSpaceTokenName(i); const value = `${BASE_SPACING_UNIT_REM * i}rem`; tokens[tokenName] = { value, description: `A spacing with a value of ${value}`, meta: createTokenMeta(tokenName), }; } for (let i = 1; i <= NUMBER_OF_ITEMS_IN_100_SCALES; i++) { const tokenName = `margin-${i * 100}`; const aliasTokenName = getSpaceTokenName(i); tokens[tokenName] = { aliasOf: aliasTokenName, description: `A margin equal to ${aliasTokenName}`, meta: createTokenMeta(tokenName), }; } for (let i = 1; i <= NUMBER_OF_ITEMS_IN_100_SCALES; i++) { const tokenName = `padding-${i * 100}`; const aliasTokenName = getSpaceTokenName(i); tokens[tokenName] = { aliasOf: aliasTokenName, description: `A padding equal to ${aliasTokenName}`, meta: createTokenMeta(tokenName), }; } return tokens; }; /** * Generates typography tokens * * @returns A typography Tokens object */ export const getTypographyTokens = (): Tokens => { const typeRatio = 1.2; const lineHeight = 1.25; const values = { 'font-size-heading-1': typeRatio ** 7, 'font-size-heading-2': typeRatio ** 6, 'font-size-heading-3': typeRatio ** 5, 'font-size-heading-4': typeRatio ** 4, 'font-size-heading-5': typeRatio ** 3, 'font-size-heading-6': typeRatio ** 2, 'font-size-heading-7': typeRatio ** 1, 'font-size-body-large': typeRatio ** 1.05, 'font-size-body': 1, 'font-size-small': 1 * 0.9, 'line-height-heading-1': typeRatio ** 7 * lineHeight, 'line-height-heading-2': typeRatio ** 6 * lineHeight, 'line-height-heading-3': typeRatio ** 5 * lineHeight, 'line-height-heading-4': typeRatio ** 4 * lineHeight, 'line-height-heading-5': typeRatio ** 3 * lineHeight, 'line-height-heading-6': typeRatio ** 2 * lineHeight, 'line-height-heading-7': typeRatio ** 1 * lineHeight, 'line-height-body-large': typeRatio ** 7 * lineHeight, 'line-height-body': typeRatio ** 7 * lineHeight, 'line-height-small': typeRatio ** 7 * lineHeight, }; const tokens: Tokens = {}; Object.entries(values).forEach(([tokenName, value]) => { const roundedValue = Math.round(value * 10) / 10; tokens[tokenName] = { value: `${roundedValue}rem`, description: tokenName.startsWith('font-size') ? `A font size with a value of ${roundedValue}rem` : `The corresponding line height for the token ${tokenName.replace( 'line-height', 'font-size', )}`, meta: createTokenMeta(tokenName), }; }); return tokens; }; /** * Generates motion tokens * * @returns A Tokens */ export const getMotionTokens = (): Tokens => { let values: {[key: string]: Omit<Token, 'meta'>} = {}; for (let i = 1; i <= FRAMES_PER_SECOND; i++) { const ms = Math.round(ONE_FRAME * i); values[`ms-${ms}`] = { value: `${ms}ms`, description: `A duration or delay equal to ${i} ${ i === 1 ? 'frame' : 'frames' } (assuming 60 FPS)`, }; } for (let i = 1; i <= FRAMES_PER_SECOND; i++) { const ms = Math.round(ONE_FRAME * i); values[`frames-${i}`] = { aliasOf: `ms-${ms}`, description: `The number of milliseconds it takes to render ${i} ${ i === 1 ? 'frame' : 'frames' } (assuming 60 FPS)`, }; } values = { ...values, 'duration-immediate': { aliasOf: 'ms-0', description: 'Used when the element needs to appear right away, without any motion', }, 'duration-swift-exit': { aliasOf: 'ms-100', description: 'Used when the element should disappear quickly', }, 'duration-swift-enter': { aliasOf: 'ms-150', description: 'Used when the element needs to appear quickly but smoothly', }, 'duration-default': { aliasOf: 'ms-200', description: 'The default duration for elements', }, 'duration-clear-exit': { aliasOf: 'ms-250', description: 'Used for elements that needs to be removed in a clear and visible manner', }, 'duration-clear-enter': { aliasOf: 'ms-300', description: 'USed for elements that need to draw attention to themselves as they enter', }, }; const tokens: Tokens = {}; Object.entries(values).forEach(([tokenName, value]) => { tokens[tokenName] = { value: value.value, aliasOf: value.aliasOf, description: value.description, meta: createTokenMeta(tokenName), }; }); return tokens; }; /** * Generates breakpoint tokens * * @returns A Tokens */ export const getBreakpointTokens = (): Tokens => { return { 'breakpoint-xs': { value: '0', description: 'Small devices, like wearables and smartphones', meta: createTokenMeta('breakpoint-xs'), }, 'breakpoint-sm': { value: '600px', description: 'Mostly tablets', meta: createTokenMeta('breakpoint-sm'), }, 'breakpoint-md': { value: '960px', description: 'Mostly tablets', meta: createTokenMeta('breakpoint-md'), }, 'breakpoint-lg': { value: '1280px', description: 'Computers', meta: createTokenMeta('breakpoint-lg'), }, 'breakpoint-xl': { value: '1920px', description: 'Computers', meta: createTokenMeta('breakpoint-xl'), }, }; };
the_stack
import { EventQueue } from "../event_queue"; import { BMLCSS2Properties } from "./BMLCSS2Properties"; import { CachedFileMetadata, Resources } from "../resource"; import { aribPNGToPNG } from "../arib_png"; import { readCLUT } from "../clut"; import { defaultCLUT } from "../default_clut"; import { parseCSSValue } from "../transpile_css"; import { Buffer } from "buffer"; import { Interpreter } from "../interpreter/interpreter"; import { AudioNodeProvider, BMLBrowserEventTarget, InputApplication, inputCharacters, InputCharacterType } from "../bml_browser"; import { convertJPEG } from "../arib_jpeg"; import { aribMNGToCSSAnimation } from "../arib_mng"; import { playAIFF } from "../arib_aiff"; import { unicodeToJISMap } from "../unicode_to_jis_map"; import { decodeEUCJP, encodeEUCJP } from "../euc_jp"; import { ModuleListEntry } from "../../server/ws_api"; export namespace BML { type DOMString = string; export function nodeToBMLNode(node: globalThis.HTMLInputElement, ownerDocument: BMLDocument): BMLInputElement; export function nodeToBMLNode(node: globalThis.HTMLBRElement, ownerDocument: BMLDocument): BMLBRElement; export function nodeToBMLNode(node: globalThis.HTMLAnchorElement, ownerDocument: BMLDocument): BMLAnchorElement; export function nodeToBMLNode(node: globalThis.HTMLHtmlElement, ownerDocument: BMLDocument): BMLBmlElement; export function nodeToBMLNode(node: globalThis.HTMLScriptElement, ownerDocument: BMLDocument): HTMLScriptElement; export function nodeToBMLNode(node: globalThis.HTMLObjectElement, ownerDocument: BMLDocument): BMLObjectElement; export function nodeToBMLNode(node: globalThis.HTMLHeadElement, ownerDocument: BMLDocument): HTMLHeadElement; export function nodeToBMLNode(node: globalThis.HTMLTitleElement, ownerDocument: BMLDocument): HTMLTitleElement; export function nodeToBMLNode(node: globalThis.HTMLSpanElement, ownerDocument: BMLDocument): BMLSpanElement; export function nodeToBMLNode(node: globalThis.HTMLMetaElement, ownerDocument: BMLDocument): HTMLMetaElement; export function nodeToBMLNode(node: globalThis.HTMLStyleElement, ownerDocument: BMLDocument): HTMLStyleElement; export function nodeToBMLNode(node: globalThis.HTMLElement, ownerDocument: BMLDocument): HTMLElement | BMLBeventElement | BMLBeitemElement; export function nodeToBMLNode(node: globalThis.HTMLBodyElement, ownerDocument: BMLDocument): BMLBodyElement; export function nodeToBMLNode(node: globalThis.HTMLParagraphElement, ownerDocument: BMLDocument): BMLParagraphElement; export function nodeToBMLNode(node: globalThis.HTMLDivElement, ownerDocument: BMLDocument): BMLDivElement; export function nodeToBMLNode(node: globalThis.HTMLHtmlElement, ownerDocument: BMLDocument): BMLBmlElement; export function nodeToBMLNode(node: globalThis.HTMLElement, ownerDocument: BMLDocument): HTMLElement; export function nodeToBMLNode(node: globalThis.Element, ownerDocument: BMLDocument): Element; export function nodeToBMLNode(node: globalThis.CDATASection, ownerDocument: BMLDocument): CDATASection; export function nodeToBMLNode(node: globalThis.Text, ownerDocument: BMLDocument): Text; export function nodeToBMLNode(node: globalThis.CharacterData, ownerDocument: BMLDocument): CharacterData; export function nodeToBMLNode(node: globalThis.HTMLAnchorElement, ownerDocument: BMLDocument): BMLAnchorElement; export function nodeToBMLNode(node: globalThis.Node, ownerDocument: BMLDocument): Node; export function nodeToBMLNode(node: null, ownerDocument: BMLDocument): null; export function nodeToBMLNode(node: globalThis.Node | null, ownerDocument: BMLDocument): Node | null { return node == null ? null : wrapNodeNonNull(node, ownerDocument); } export function bmlNodeToNode(node: Node | null): globalThis.Node | null { return node == null ? null : node["node"]; } export function htmlElementToBMLHTMLElement(node: globalThis.HTMLElement | null, ownerDocument: BMLDocument): HTMLElement | null { if (node == null) { return null; } const result = wrapNodeNonNull(node, ownerDocument); if (!(result instanceof HTMLElement)) { throw new TypeError("failed to cast to BML.HTMLElement"); } return result; } function wrapNode(node: globalThis.Node | null, ownerDocument: BMLDocument): Node | null { return node == null ? null : wrapNodeNonNull(node, ownerDocument); } function wrapNodeNonNull(node: globalThis.Node, ownerDocument: BMLDocument): Node { const a: any = node; const klass = getNodeClass(node); if (a.__klass) { if (a.__klass !== klass) { console.error("??", a); } else { return a.__bmlInstance; } } a.__klass = klass; const inst = new klass(node, ownerDocument); a.__bmlInstance = inst; return inst; } function getNodeClass(node: globalThis.Node): typeof Node { if (node instanceof globalThis.HTMLInputElement) { return BMLInputElement; } else if (node instanceof globalThis.HTMLBRElement) { return BMLBRElement; } else if (node instanceof globalThis.HTMLAnchorElement) { return BMLAnchorElement; } else if (node instanceof globalThis.HTMLHtmlElement) { return BMLBmlElement; } else if (node instanceof globalThis.HTMLScriptElement) { return HTMLScriptElement; } else if (node instanceof globalThis.HTMLObjectElement) { return BMLObjectElement; } else if (node instanceof globalThis.HTMLHeadElement) { return HTMLHeadElement; } else if (node instanceof globalThis.HTMLTitleElement) { return HTMLTitleElement; } else if (node instanceof globalThis.HTMLSpanElement) { return BMLSpanElement; } else if (node instanceof globalThis.HTMLMetaElement) { return HTMLMetaElement; } else if (node instanceof globalThis.HTMLStyleElement) { return HTMLStyleElement; } else if (node instanceof globalThis.HTMLElement && node.nodeName.toLowerCase() === "bevent") { return BMLBeventElement; } else if (node instanceof globalThis.HTMLElement && node.nodeName.toLowerCase() === "beitem") { return BMLBeitemElement; } else if (node instanceof globalThis.HTMLElement && node.nodeName.toLowerCase() === "arib-cdata") { return CDATASection; } else if (node instanceof globalThis.HTMLElement && node.nodeName.toLowerCase() === "arib-text") { return Text; } else if (node instanceof globalThis.HTMLBodyElement) { return BMLBodyElement; } else if (node instanceof globalThis.HTMLParagraphElement) { return BMLParagraphElement; } else if (node instanceof globalThis.HTMLDivElement) { return BMLDivElement; } else if (node instanceof globalThis.HTMLHtmlElement) { return BMLBmlElement; } else if (node instanceof globalThis.HTMLElement) { console.error(node); return HTMLElement; } else if (node instanceof globalThis.Element) { return Element; } else if (node instanceof globalThis.CDATASection) { return CDATASection; } else if (node instanceof globalThis.Text) { return Text; // CharcterDataは誤植 } else if (node instanceof globalThis.CharacterData) { return CharacterData; } else if (node instanceof globalThis.Node) { console.error(node); return Node; } return Node; } function getNormalStyle(node: globalThis.HTMLElement, eventTarget: BMLBrowserEventTarget): BMLCSS2Properties { return new BMLCSS2Properties(window.getComputedStyle(node), node.style, node, eventTarget); } function getFocusStyle(node: globalThis.HTMLElement, eventTarget: BMLBrowserEventTarget): BMLCSS2Properties { console.error("focusStyle is halfplemented"); const prevFocus = node.getAttribute("arib-focus"); const prevActive = node.getAttribute("arib-active"); node.setAttribute("arib-focus", "arib-focus"); node.removeAttribute("arib-active"); const comuptedStyle = window.getComputedStyle(node); if (prevFocus != null) { node.setAttribute("arib-focus", prevFocus); } else { node.removeAttribute("arib-focus"); } if (prevActive != null) { node.setAttribute("arib-active", prevActive); } return new BMLCSS2Properties(comuptedStyle, node.style, node, eventTarget); } function getActiveStyle(node: globalThis.HTMLElement, eventTarget: BMLBrowserEventTarget): BMLCSS2Properties { console.error("activeStyle is halfplemented"); const prevFocus = node.getAttribute("arib-focus"); const prevActive = node.getAttribute("arib-active"); node.removeAttribute("arib-focus"); node.setAttribute("arib-active", "arib-active"); const comuptedStyle = window.getComputedStyle(node); if (prevFocus != null) { node.setAttribute("arib-focus", prevFocus); } if (prevActive != null) { node.setAttribute("arib-active", prevActive); } else { node.removeAttribute("arib-active"); } return new BMLCSS2Properties(comuptedStyle, node.style, node, eventTarget); } export function isFocusable(elem: globalThis.Element) { if (elem instanceof globalThis.HTMLInputElement) { if (elem.disabled) { return false; } } const style = window.getComputedStyle(elem); if (style.visibility === "hidden") { return false; } return true; } function focus(node: HTMLElement, ownerDocument: BMLDocument) { const prevFocus = ownerDocument.currentFocus; if (prevFocus === node) { return; } if (!isFocusable(node["node"])) { return; } if (prevFocus != null) { prevFocus["node"].removeAttribute("arib-focus"); prevFocus["node"].removeAttribute("arib-active"); if (prevFocus instanceof HTMLInputElement) { // changeイベントはblurイベントに先立って実行される ownerDocument.inputApplication?.cancel("blur"); } } ownerDocument._currentFocus = node; if (prevFocus != null) { ownerDocument.eventQueue.queueSyncEvent({ type: "blur", target: prevFocus["node"] }); } node["node"].setAttribute("arib-focus", "arib-focus"); ownerDocument.eventQueue.queueSyncEvent({ type: "focus", target: node["node"] }); } function blur(node: HTMLElement, ownerDocument: BMLDocument) { console.error("blur: not implmeneted"); } // impl export class Node { protected node: globalThis.Node; protected ownerDocument: BMLDocument; constructor(node: globalThis.Node, ownerDocument: BMLDocument) { this.node = node; this.ownerDocument = ownerDocument; } public get parentNode(): Node | null { return wrapNode(this.node.parentNode, this.ownerDocument); } public get firstChild(): Node | null { let firstChild = this.node.firstChild; if (firstChild != null && firstChild.nodeName.toLowerCase() === "arib-bg") { firstChild = firstChild.nextSibling; } return wrapNode(firstChild, this.ownerDocument); } public get lastChild(): Node | null { let lastChild = this.node.lastChild; if (lastChild != null && lastChild.nodeName.toLowerCase() === "arib-bg") { lastChild = null; } return wrapNode(lastChild, this.ownerDocument); } public get previousSibling(): Node | null { let previousSibling = this.node.previousSibling; if (previousSibling != null && previousSibling.nodeName.toLowerCase() === "arib-bg") { previousSibling = null; } return wrapNode(previousSibling, this.ownerDocument); } get nextSibling(): Node | null { return wrapNode(this.node.nextSibling, this.ownerDocument); } } // impl export class CharacterData extends Node { protected node: globalThis.CharacterData; protected textNode: globalThis.HTMLElement; protected parentBlock: globalThis.HTMLElement; protected root: ShadowRoot; protected textNodeInRoot?: globalThis.CharacterData; protected textData: string; constructor(node: globalThis.CharacterData, ownerDocument: BMLDocument) { super(node, ownerDocument); // strictTextRenderingが有効の場合 if (node.nodeName.toLowerCase() === "arib-text" || node.nodeName.toLowerCase() === "arib-cdata") { this.textNode = node as unknown as globalThis.HTMLElement; this.textData = this.textNode.textContent ?? ""; this.textNode.replaceChildren(); this.root = this.textNode.attachShadow({ mode: "closed" }); this.parentBlock = this.getParentBlock()!; } else { this.textNode = undefined!; this.root = undefined!; this.textData = undefined!; this.parentBlock = undefined!; } this.node = node; } private getParentBlock() { let parent: globalThis.HTMLElement | null = this.textNode.parentElement; while (parent != null) { if (window.getComputedStyle(parent).display !== "inline") { return parent; } parent = parent.parentElement; } return null; } private flowText(text: string) { const nextElement = this.textNode.nextElementSibling; const computedStyle = window.getComputedStyle(this.textNode); if (computedStyle.letterSpacing === "normal" || computedStyle.letterSpacing === "0px") { if (this.textNodeInRoot == null) { // shadow DOMの中なので外の* {}のようなCSSは適用されない一方プロパティは継承される this.textNodeInRoot = document.createTextNode(text); this.root.replaceChildren(this.textNodeInRoot); } return; } if (this.textNodeInRoot != null) { this.textNodeInRoot = undefined; } const left = this.textNode.clientLeft; const top = this.textNode.clientTop; const parent = this.parentBlock; const width = parent.clientWidth; let fontSize = Number.parseInt(computedStyle.fontSize); if (Number.isNaN(fontSize)) { fontSize = 16; } let letterSpacing = Number.parseInt(computedStyle.letterSpacing); if (Number.isNaN(letterSpacing)) { letterSpacing = 0; } let lineHeight = Number.parseInt(computedStyle.lineHeight); if (Number.isNaN(lineHeight)) { lineHeight = fontSize * 1; } let x = left; let y = top; const children: globalThis.Node[] = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); const isLast = nextElement == null && i === text.length - 1; if (c === "\r") { continue; } if (c === "\n") { const char = document.createTextNode("\n"); children.push(char); x = 0; y += lineHeight; continue; } const isFull = c.charCodeAt(0) in unicodeToJISMap; const char = document.createElement("span"); char.textContent = c; char.style.display = "inline-block"; char.style.textAlign = "center"; const fontWidth = isFull ? fontSize : fontSize / 2; char.style.width = `${fontWidth}px`; char.style.lineHeight = `${lineHeight}px`; if (x + fontWidth > width) { x = 0; y += lineHeight; } // レタースペーシングは折り返し前と最後には付かない (STD-B24 第二分冊 (2/2) 第二編 付属1 6.3.2参照) if (!isLast && x + fontWidth + letterSpacing <= width) { char.style.marginRight = `${letterSpacing}px`; x += letterSpacing; } children.push(char); x += fontWidth; } this.root.replaceChildren(...children); } public internalReflow() { this.flowText(this.data); } public get data(): string { if (this.textNode) { return this.textData; } return this.node.data; } public set data(value: string) { value = String(value); if (this.textNode) { this.textData = value; if (this.textNodeInRoot != null) { this.textNodeInRoot.data = value; } else { this.flowText(value); } return; } this.node.data = value; } public get length(): number { return this.node.length; } } // impl export class Text extends CharacterData { } // impl export class CDATASection extends Text { } // impl export class Document extends Node { protected node: globalThis.Document; protected _implementation: DOMImplementation; constructor(node: globalThis.Document, ownerDocument: BMLDocument) { super(node, ownerDocument); this.node = node; this._implementation = new DOMImplementation(); } public get implementation(): DOMImplementation { return this._implementation; } public get documentElement(): HTMLElement { return wrapNodeNonNull(this.node.documentElement, this.ownerDocument) as HTMLElement; } } // impl export abstract class HTMLDocument extends Document { protected node: globalThis.HTMLDocument; constructor(node: globalThis.HTMLDocument, ownerDocument: BMLDocument) { super(node, ownerDocument); this.node = node; } public getElementById(id: string | null | undefined): HTMLElement | null { const stringId = String(id); if (stringId === "") { return null; } return wrapNode(this.node.querySelector("#" + CSS.escape(stringId)), this.ownerDocument) as (HTMLElement | null); } } // impl export class BMLDocument extends HTMLDocument { _currentFocus: HTMLElement | null = null; _currentEvent: BMLEvent | null = null; public readonly interpreter: Interpreter; public readonly eventQueue: EventQueue; public readonly resources: Resources; public readonly browserEventTarget: BMLBrowserEventTarget; public readonly audioNodeProvider: AudioNodeProvider; public readonly inputApplication?: InputApplication; public constructor(node: globalThis.HTMLElement, interpreter: Interpreter, eventQueue: EventQueue, resources: Resources, browserEventTarget: BMLBrowserEventTarget, audioNodeProvider: AudioNodeProvider, inputApplication: InputApplication | undefined) { super(node as any, null!); // ! this.ownerDocument = this; // !! this.interpreter = interpreter; this.eventQueue = eventQueue; this.resources = resources; this.browserEventTarget = browserEventTarget; this.audioNodeProvider = audioNodeProvider; this.inputApplication = inputApplication; } public get documentElement(): HTMLElement { return wrapNodeNonNull(this.node, this.ownerDocument) as HTMLElement; } public get currentFocus(): HTMLElement | null { return this._currentFocus; } public get currentEvent(): BMLEvent | null { return this._currentEvent; } } // impl export class Element extends Node { protected node: globalThis.Element; constructor(node: globalThis.Element, ownerDocument: BMLDocument) { super(node, ownerDocument); this.node = node; } public get tagName(): string { const tagName = this.node.tagName.toLowerCase(); if (tagName.startsWith("arib-")) { return tagName.substring("arib-".length); } return tagName; } } // impl export class HTMLElement extends Element { protected node: globalThis.HTMLElement; constructor(node: globalThis.HTMLElement, ownerDocument: BMLDocument) { super(node, ownerDocument); this.node = node; } public get id(): string { return this.node.id; } public get className(): string { return this.node.className; } } // impl export class HTMLBRElement extends HTMLElement { } // impl export class BMLBRElement extends HTMLBRElement { public get normalStyle(): BMLCSS2Properties { return getNormalStyle(this.node, this.ownerDocument.browserEventTarget); } } // impl export class HTMLHtmlElement extends HTMLElement { } // impl export class BMLBmlElement extends HTMLHtmlElement { } // impl export class HTMLAnchorElement extends HTMLElement { protected node: globalThis.HTMLAnchorElement; constructor(node: globalThis.HTMLAnchorElement, ownerDocument: BMLDocument) { super(node, ownerDocument); this.node = node; } public get accessKey(): string { return this.node.accessKey; } public get href(): string { return this.node.href; } public set href(value: string) { this.node.href = value; } } // impl export class BMLAnchorElement extends HTMLAnchorElement { public get normalStyle(): BMLCSS2Properties { return getNormalStyle(this.node, this.ownerDocument.browserEventTarget); } public get focusStyle(): BMLCSS2Properties { return getFocusStyle(this.node, this.ownerDocument.browserEventTarget); } public get activeStyle(): BMLCSS2Properties { return getActiveStyle(this.node, this.ownerDocument.browserEventTarget); } } // impl export class HTMLInputElement extends HTMLElement { protected node: globalThis.HTMLInputElement; constructor(node: globalThis.HTMLInputElement, ownerDocument: BMLDocument) { super(node, ownerDocument); this.node = node; } public get defaultValue(): string { return this.node.defaultValue; } public get accessKey(): string { return this.node.accessKey; } public get disabled(): boolean { return this.node.disabled; } public set disabled(value: boolean) { this.node.disabled = value; } public get maxLength(): number { return this.node.maxLength === -1 ? 40 : this.node.maxLength; } public get readOnly(): boolean { return this.node.readOnly; } public set readOnly(value: boolean) { if (this.ownerDocument.currentFocus === this && value && !this.node.readOnly) { this.ownerDocument.inputApplication?.cancel("readonly"); } this.node.readOnly = value; } public get type(): string { return this.node.type; } public get value(): string { return this.node.value; } public set value(value: string) { this.node.value = value; } public blur(): void { blur(this, this.ownerDocument); } public focus(): void { focus(this, this.ownerDocument); } public internalLaunchInputApplication(): void { const ctype = this.node.getAttribute("charactertype")?.toLowerCase() as InputCharacterType ?? "all"; const allowed = inputCharacters.get(ctype); this.ownerDocument.inputApplication?.launch({ characterType: ctype, allowedCharacters: allowed, maxLength: this.maxLength, value: this.value, inputMode: this.type === "password" ? "password" : "text", callback: (value) => { value = decodeEUCJP(encodeEUCJP(value)); value = value.substring(0, this.maxLength); if (allowed != null) { value = value.split("").filter(x => { return allowed.includes(x); }).join(""); } if (this.value !== value) { this.value = value; this.ownerDocument.eventQueue.queueSyncEvent({ type: "change", target: this.node, }); this.ownerDocument.eventQueue.processEventQueue(); } } }); } } // impl export class BMLInputElement extends HTMLInputElement { public get normalStyle(): BMLCSS2Properties { return getNormalStyle(this.node, this.ownerDocument.browserEventTarget); } public get focusStyle(): BMLCSS2Properties { return getFocusStyle(this.node, this.ownerDocument.browserEventTarget); } public get activeStyle(): BMLCSS2Properties { return getActiveStyle(this.node, this.ownerDocument.browserEventTarget); } } // STD B-24 第二分冊 (2/2) 第二編 付属2 表5-3参照 // 画像の大きさは固定 function fixImageSize(resolution: string, width: number, height: number, type: string): { width?: number, height?: number } { type = type.toLowerCase(); // 表5-4参照 //const scaleNumerator = [256, 192, 160, 128, 96, 80, 64, 48, 32]; //const scaleDenominator = 128; const is720x480 = resolution.trim() === "720x480"; if (type === "image/jpeg") { if (is720x480) { if (width % 2 != 0) { return { width: width - 1, height }; } return { width, height }; } if (width === 960 && height === 540) { return { width, height }; } return { width: Math.floor(width / 2), height: Math.floor(height / 2) }; } else if (type === "image/x-arib-png" || type === "image/x-arib-mng") { return { width, height }; } return {}; } // impl export class HTMLObjectElement extends HTMLElement { protected node: globalThis.HTMLObjectElement; constructor(node: globalThis.HTMLObjectElement, ownerDocument: BMLDocument) { super(node, ownerDocument); this.node = node; } public get data(): string { return this.node.data; } public set data(value: string) { this.node.data = value; } public get type(): string { return this.node.type; } } // impl export class BMLObjectElement extends HTMLObjectElement { public get data(): string { const aribData = this.node.getAttribute("arib-data"); if (aribData == null || aribData == "") { return this.node.getAttribute("data") ?? ""; } return aribData; } private __version: number = 0; protected animation: Animation | undefined; protected effect: KeyframeEffect | undefined; protected delete() { if (this.animation != null) { this.animation.cancel(); this.effect = undefined; this.animation = undefined; } // Chromeではdataが未設定でtypeが設定されている場合枠線が表示されてしまうためtypeも消す this.node.removeAttribute("type"); this.node.removeAttribute("data"); } protected updateAnimation() { if (this.animation == null) { return; } const streamStatus = this.node.getAttribute("streamstatus"); if (streamStatus === "play") { this.animation.play(); } else if (streamStatus === "pause") { this.animation.pause(); } else if (streamStatus === "stop") { this.animation.cancel(); } } public set data(value: string) { (async () => { if (value == null) { this.delete(); this.node.removeAttribute("arib-data"); return; } const aribType = this.node.getAttribute("arib-type"); this.node.setAttribute("arib-data", value); if (value == "") { this.delete(); return; } // 順序が逆転するのを防止 this.__version = this.__version + 1; const version: number = (this as any).__version; const fetched = await this.ownerDocument.resources.fetchResourceAsync(value); if (this.__version !== version) { return; } if (!fetched) { this.delete(); return; } let imageUrl: CachedFileMetadata | undefined; const isPNG = aribType?.toLowerCase() === "image/x-arib-png"; const isMNG = aribType?.toLowerCase() === "image/x-arib-mng"; let imageType: string | undefined; if (isPNG || isMNG) { const clutCss = window.getComputedStyle(this.node).getPropertyValue("--clut"); const clutUrl = clutCss == null ? null : parseCSSValue(clutCss); const fetchedClut = clutUrl == null ? null : (await this.ownerDocument.resources.fetchResourceAsync(clutUrl))?.data; if (this.__version !== version) { return; } if (isMNG) { const clut = fetchedClut == null ? defaultCLUT : readCLUT(Buffer.from(fetchedClut?.buffer)); const keyframes = aribMNGToCSSAnimation(Buffer.from(fetched.data), clut); this.node.removeAttribute("data"); if (this.animation != null) { this.animation.cancel(); this.animation = undefined; this.effect = undefined; } if (keyframes == null) { return; } this.effect = new KeyframeEffect(this.node, keyframes.keyframes, keyframes.options); this.animation = new Animation(this.effect); for (const blob of keyframes.blobs) { fetched.blobUrl.set(blob, { blobUrl: blob }); } const { width, height } = fixImageSize(window.getComputedStyle((bmlNodeToNode(this.ownerDocument.documentElement) as globalThis.HTMLElement).querySelector("body")!).getPropertyValue("resolution"), keyframes.width, keyframes.height, (aribType ?? this.type)); if (width != null && height != null) { this.node.style.maxWidth = width + "px"; this.node.style.minWidth = width + "px"; this.node.style.maxHeight = height + "px"; this.node.style.minHeight = height + "px"; } // streamloopingは1固定で運用されるため考慮しない // streamstatus=playのときstreampositionで指定されたフレームから再生開始 // streamstatus=stopのとき非表示 streampositionは0にリセットされる // streamstatus=pauseのとき streampositionで指定されたフレームを表示 if (this.streamStatus !== "stop") { console.error("unexpected streamStatus", this.streamStatus, this.data); } this.updateAnimation(); return; } else { imageUrl = fetched.blobUrl.get(fetchedClut); if (imageUrl == null) { const clut = fetchedClut == null ? defaultCLUT : readCLUT(Buffer.from(fetchedClut?.buffer)); const png = aribPNGToPNG(Buffer.from(fetched.data), clut); const blob = new Blob([png.data], { type: "image/png" }); imageUrl = { blobUrl: URL.createObjectURL(blob), width: png.width, height: png.height }; fetched.blobUrl.set(fetchedClut, imageUrl); } imageType = "image/png"; } } else if (aribType?.toLowerCase() === "image/jpeg") { imageUrl = fetched.blobUrl.get("BT.709"); if (imageUrl == null) { try { imageUrl = await convertJPEG(this.ownerDocument.resources.getCachedFileBlobUrl(fetched)); if (this.__version !== version) { return; } } catch { this.delete(); return; } fetched.blobUrl.set("BT.709", imageUrl); } imageType = "image/jpeg"; } else { this.delete(); return; } if (imageUrl == null) { this.delete(); return; } if (imageUrl.width != null && imageUrl.height != null) { const { width, height } = fixImageSize(window.getComputedStyle((bmlNodeToNode(this.ownerDocument.documentElement) as globalThis.HTMLElement).querySelector("body")!).getPropertyValue("--resolution"), imageUrl.width, imageUrl.height, (aribType ?? this.type)); if (width != null && height != null) { this.node.style.maxWidth = width + "px"; this.node.style.minWidth = width + "px"; this.node.style.maxHeight = height + "px"; this.node.style.minHeight = height + "px"; } } this.node.type = imageType; this.node.data = imageUrl.blobUrl; })(); } public get type() { const aribType = this.node.getAttribute("arib-type"); if (aribType != null) { return aribType; } return this.node.type; } public get normalStyle(): BMLCSS2Properties { return getNormalStyle(this.node, this.ownerDocument.browserEventTarget); } public get focusStyle(): BMLCSS2Properties { return getFocusStyle(this.node, this.ownerDocument.browserEventTarget); } public get activeStyle(): BMLCSS2Properties { return getActiveStyle(this.node, this.ownerDocument.browserEventTarget); } public get accessKey(): string { return this.node.accessKey; } // 同じidであれば遷移時にも状態を保持する public get remain(): boolean { return this.node.getAttribute("remain") === "remain"; } public set remain(value: boolean) { if (value) { this.node.setAttribute("remain", "remain"); } else { this.node.removeAttribute("remain"); } } // MNG // streamstatus=playのときstreamPositionは運用しない // streamstatus=stopのときstreamPositionは0 // streamstatus=pauseのとき現在表示設定されているフレームの番号 public get streamPosition(): number { const v = Number.parseInt(this.node.getAttribute("streamposition") ?? "0"); if (Number.isFinite(v)) { return v; } else { return 0; } } // MNG // streamstatus=playのときstreamPositionは運用しない // streamstatus=stopのときstreamPositionは0以外を設定しても無視される // streamstatus=pauseのとき指定されたフレームを表示 フレーム数より大きければ受信機依存 public set streamPosition(value: number) { if (this.streamStatus === "pause") { value = Number(value); if (Number.isFinite(value)) { this.node.setAttribute("streamposition", value.toString()); if (this.effect != null) { const timing = this.effect.getTiming(); const duration = Number(timing.duration); const keyframes = this.effect.getKeyframes(); const keyframe = keyframes[Math.max(0, Math.min(value, keyframes.length - 1))]; timing.delay = -(keyframe.computedOffset * duration); this.effect.updateTiming(timing); } } } else { if (this.effect != null) { const timing = this.effect.getTiming(); timing.delay = 0; this.effect.updateTiming(timing); } this.node.setAttribute("streamposition", "0"); } } static offsetToFrame(keyframes: ComputedKeyframe[], offset: number): number { // offset順でソートされていると仮定 for (let i = 0; i < keyframes.length; i++) { if (keyframes[i].computedOffset <= offset) { return i; } } return 0; } public get streamStatus(): DOMString { if (this.animation != null) { if (this.animation.playState === "finished" && this.streamStatus !== "pause") { this.streamStatus = "pause"; } } const value = this.node.getAttribute("streamstatus"); if (value == null) { const type = this.type.toLowerCase(); // stopを取りうる場合初期値はstop (STD-B24 第二分冊 (2/2) 付属2 4.8.5.2 注2) if (type === "audio/x-arib-mpeg2-aac" || type === "audio/x-arib-aiff" || type === "image/gif" || type === "image/x-arib-mng") { return "stop"; } return "play"; } return value; // "stop" | "play" | "pause" } private audioBufferSourceNode?: AudioBufferSourceNode; // STD-B24 第二分冊 (2/2) 付属2 4.8.5.3 // MNG // stop以外の時にdataを変更できない // 再生が終了したときはpauseに設定される public set streamStatus(value: DOMString) { const type = this.type.toLowerCase(); if (type === "audio/x-arib-aiff") { if (value === "play") { this.audioBufferSourceNode?.stop(); this.ownerDocument.resources.fetchResourceAsync(this.data).then(x => { const data = x?.data; if (data == null) { return; } this.audioBufferSourceNode = playAIFF(this.ownerDocument.audioNodeProvider.getAudioDestinationNode(), Buffer.from(data)) ?? undefined; this.node.setAttribute("streamstatus", "play"); if (this.audioBufferSourceNode != null) { const sourceNode = this.audioBufferSourceNode; sourceNode.onended = () => { if (sourceNode === this.audioBufferSourceNode) { this.node.setAttribute("streamstatus", "stop"); } }; } }); } else if (value === "stop") { this.audioBufferSourceNode?.stop(); this.audioBufferSourceNode = undefined; this.node.setAttribute("streamstatus", "stop"); } return; } if (this.animation == null || this.effect == null) { this.node.setAttribute("streamstatus", value); return; } if (this.streamStatus === value) { return; } const prevStatus = this.streamStatus; if (value === "play") { this.node.setAttribute("streamstatus", "play"); if (prevStatus === "pause") { // pause=>play streampositionに設定されているフレームから再生開始 this.animation.play(); } else if (prevStatus === "stop") { // stop=>play 0フレームから再生開始 this.streamPosition = 0; this.animation.play(); } } else if (value === "pause") { this.node.setAttribute("streamstatus", "pause"); if (prevStatus === "play") { // play=>pause どのフレームを表示するかは受信機依存 streampositionはそのフレームに設定される 繰り返し回数はリセット this.animation.pause(); const duration = Number(this.effect.getTiming().duration); this.streamPosition = BMLObjectElement.offsetToFrame(this.effect.getKeyframes(), ((this.animation.currentTime! - this.animation.startTime!) % duration) / duration); } else if (prevStatus === "stop") { // stop=>pause 0フレーム目が表示される this.streamPosition = 0; this.animation.play(); this.animation.pause(); } } else if (value === "stop") { // play=>stop streampositionは0 繰り返し回数はリセット // pause=>stop play=>pauseのときと同様 this.animation.cancel(); this.streamPosition = 0; this.node.setAttribute("streamstatus", "stop"); } } public setMainAudioStream(audio_ref: DOMString): boolean { throw new Error("BMLObjectElement.setMainAudioStream()"); } public getMainAudioStream(): DOMString { throw new Error("BMLObjectElement.getMainAudioStream()"); } public blur(): void { blur(this, this.ownerDocument); } public focus(): void { focus(this, this.ownerDocument); } } // impl export class BMLSpanElement extends HTMLElement { public get normalStyle(): BMLCSS2Properties { return getNormalStyle(this.node, this.ownerDocument.browserEventTarget); } public get focusStyle(): BMLCSS2Properties { return getFocusStyle(this.node, this.ownerDocument.browserEventTarget); } public get activeStyle(): BMLCSS2Properties { return getActiveStyle(this.node, this.ownerDocument.browserEventTarget); } public get accessKey(): string { return this.node.accessKey; } public blur(): void { blur(this, this.ownerDocument); } public focus(): void { focus(this, this.ownerDocument); } } // impl export class HTMLBodyElement extends HTMLElement { } // impl export class BMLBodyElement extends HTMLBodyElement { public get invisible(): boolean { return this.node.getAttribute("invisible") === "invisible"; } public set invisible(v: boolean) { v = Boolean(v); if (this.ownerDocument.currentFocus instanceof HTMLInputElement && !v) { this.ownerDocument.inputApplication?.cancel("invisible"); } if (v) { this.node.setAttribute("invisible", "invisible"); } else { this.node.removeAttribute("invisible"); } this.ownerDocument.browserEventTarget.dispatchEvent<"invisible">(new CustomEvent("invisible", { detail: v })); } public get normalStyle(): BMLCSS2Properties { return getNormalStyle(this.node, this.ownerDocument.browserEventTarget); } } // impl export class HTMLDivElement extends HTMLElement { } // impl export class BMLDivElement extends HTMLDivElement { public get normalStyle(): BMLCSS2Properties { return getNormalStyle(this.node, this.ownerDocument.browserEventTarget); } public get focusStyle(): BMLCSS2Properties { return getFocusStyle(this.node, this.ownerDocument.browserEventTarget); } public get activeStyle(): BMLCSS2Properties { return getActiveStyle(this.node, this.ownerDocument.browserEventTarget); } public get accessKey(): string { return this.node.accessKey; } public blur(): void { blur(this, this.ownerDocument); } public focus(): void { focus(this, this.ownerDocument); } } // impl export class HTMLParagraphElement extends HTMLElement { } // impl export class BMLParagraphElement extends HTMLParagraphElement { public get normalStyle(): BMLCSS2Properties { return getNormalStyle(this.node, this.ownerDocument.browserEventTarget); } public get focusStyle(): BMLCSS2Properties { return getFocusStyle(this.node, this.ownerDocument.browserEventTarget); } public get activeStyle(): BMLCSS2Properties { return getActiveStyle(this.node, this.ownerDocument.browserEventTarget); } public get accessKey(): string { return this.node.accessKey; } public blur(): void { blur(this, this.ownerDocument); } public focus(): void { focus(this, this.ownerDocument); } } // impl export class HTMLMetaElement extends HTMLElement { protected node: globalThis.HTMLMetaElement; constructor(node: globalThis.HTMLMetaElement, ownerDocument: BMLDocument) { super(node, ownerDocument); this.node = node; } public get content(): string { return this.node.content; } public get name(): string { return this.node.name; } } // impl export class HTMLTitleElement extends HTMLElement { protected node: globalThis.HTMLTitleElement; constructor(node: globalThis.HTMLTitleElement, ownerDocument: BMLDocument) { super(node, ownerDocument); this.node = node; } public get text(): string { return this.node.text; } } // impl export class HTMLScriptElement extends HTMLElement { } // impl export class HTMLStyleElement extends HTMLElement { } // impl export class HTMLHeadElement extends HTMLElement { } // impl export class BMLBeventElement extends HTMLElement { } function attrToNumber(attr: string | null): number | null { const n = Number.parseInt(attr ?? ""); if (Number.isNaN(n)) { return null; } return n; } // impl export class BMLBeitemElement extends HTMLElement { // とりあえず関連する属性の値が変わったらリセットするようにしているけどこれらの前回発火したときの状態はリセットされることがあるのかは規格を読んでもよくわからない // subscribe=false => subscribe=trueでリセットされるのはほぼ確実 public internalTimerFired: boolean = false; public internalModuleUpdateDataEventId?: number; public internalModuleUpdateVersion?: number; public internalModuleExistsInDII?: boolean; // key: message_id, value: 前回受信したmessage_version public internalMessageVersion?: Map<number, number>; public internalNPTReferred: boolean = false; public get type(): DOMString { return this.node.getAttribute("type") ?? ""; } public get esRef(): DOMString { return this.node.getAttribute("es_ref") ?? ""; } public set esRef(value: DOMString) { if (value !== this.esRef) { this.node.setAttribute("es_ref", value); this.internalMessageVersion = undefined; this.internalNPTReferred = false; } } public get messageId(): number { return attrToNumber(this.node.getAttribute("message_id")) ?? 255; } public set messageId(value: number) { this.node.setAttribute("message_id", String(value)); } public get messageVersion(): number { return attrToNumber(this.node.getAttribute("message_version")) ?? 255; } public set messageVersion(value: number) { this.node.setAttribute("message_version", String(value)); } public get messageGroupId(): number { return attrToNumber(this.node.getAttribute("message_group_id")) ?? 0; } // public set messageGroupId(value: number) { // this.node.setAttribute("message_group_id", String(value)); // } public get moduleRef(): DOMString { return this.node.getAttribute("module_ref") ?? ""; } public set moduleRef(value: DOMString) { if (this.moduleRef !== value) { this.node.setAttribute("module_ref", value); this.internalModuleUpdateDataEventId = undefined; this.internalModuleUpdateVersion = undefined; this.internalModuleExistsInDII = undefined; } } public get languageTag(): number { return attrToNumber(this.node.getAttribute("language_tag")) ?? 0; } public set languageTag(value: number) { this.node.setAttribute("language_tag", String(value)); } /* public get registerId(): number { return attrToNumber(this.node.getAttribute("register_id")) ?? 0; } public set registerId(value: number) { this.node.setAttribute("register_id", String(value)); } public get serviceId(): number { return attrToNumber(this.node.getAttribute("service_id")) ?? 0; } public set serviceId(value: number) { this.node.setAttribute("service_id", String(value)); } public get eventId(): number { return attrToNumber(this.node.getAttribute("event_id")) ?? 0; } public set eventId(value: number) { this.node.setAttribute("event_id", String(value)); }*/ public get peripheralRef(): DOMString { return this.node.getAttribute("peripheral_ref") ?? ""; } public set peripheralRef(value: DOMString) { this.node.setAttribute("peripheral_ref", value); } public get timeMode() { return this.node.getAttribute("time_mode") ?? ""; } // public set timeMode(value: DOMString) { // this.node.setAttribute("time_mode", value); // } public get timeValue() { return this.node.getAttribute("time_value") ?? ""; } public set timeValue(value: DOMString) { if (this.timeValue !== value) { this.node.setAttribute("time_value", value); this.internalTimerFired = false; } } public get objectId() { return this.node.getAttribute("object_id") ?? ""; } public set objectId(value: DOMString) { this.node.setAttribute("object_id", value); } public get segmentId(): DOMString { return this.node.getAttribute("segment_id") ?? ""; } public set segmentId(value: DOMString) { this.node.setAttribute("segment_id", value); } public get subscribe(): boolean { return this.node.getAttribute("subscribe") === "subscribe"; } private dispatchModuleUpdatedEvent(module: string, status: number): void { if (!this.subscribe) { return; } console.log("ModuleUpdated", module, status); const onoccur = this.node.getAttribute("onoccur"); if (!onoccur) { return; } this.ownerDocument.eventQueue.queueAsyncEvent(async () => { this.ownerDocument._currentEvent = new BMLBeventEvent({ type: "ModuleUpdated", target: this, status, moduleRef: module, }); if (await this.ownerDocument.eventQueue.executeEventHandler(onoccur)) { return true; } this.ownerDocument._currentEvent = null; return false; }); this.ownerDocument.eventQueue.processEventQueue(); } private subscribeModuleUpdated(): void { const { componentId, moduleId } = this.ownerDocument.resources.parseURLEx(this.moduleRef); if (!this.subscribe || componentId == null || moduleId == null) { return; } if (!this.ownerDocument.resources.getPMTComponent(componentId)) { this.dispatchModuleUpdatedEvent(this.moduleRef, 1); this.internalModuleExistsInDII = false; this.internalModuleUpdateVersion = undefined; this.internalModuleUpdateDataEventId = undefined; return; } const dii = this.ownerDocument.resources.getDownloadComponentInfo(componentId); if (dii == null) { // DII未受信 return; } const module = dii.modules.get(moduleId); if (module != null) { this.dispatchModuleUpdatedEvent(this.moduleRef, 2); this.internalModuleExistsInDII = true; this.internalModuleUpdateVersion = module.version; this.internalModuleUpdateDataEventId = dii.dataEventId; } else { this.dispatchModuleUpdatedEvent(this.moduleRef, 1); this.internalModuleExistsInDII = false; this.internalModuleUpdateVersion = undefined; this.internalModuleUpdateDataEventId = dii.dataEventId; } } public internalPMTUpdated(components: ReadonlySet<number>): void { const { componentId, moduleId } = this.ownerDocument.resources.parseURLEx(this.moduleRef); if (!this.subscribe || componentId == null || moduleId == null) { return; } if (!components.has(componentId)) { if (this.internalModuleExistsInDII) { // コンポーネント送出->非送出 this.dispatchModuleUpdatedEvent(this.moduleRef, 1); } this.internalModuleExistsInDII = false; this.internalModuleUpdateVersion = undefined; this.internalModuleUpdateDataEventId = undefined; } } public internalDIIUpdated(updatedComponentId: number, modules: ReadonlyMap<number, ModuleListEntry>, dataEventId: number): void { const { componentId, moduleId } = this.ownerDocument.resources.parseURLEx(this.moduleRef); if (!this.subscribe || updatedComponentId !== componentId || moduleId == null) { return; } const module = modules.get(moduleId); if (module == null) { if (this.internalModuleExistsInDII) { // モジュール送出->非送出 this.dispatchModuleUpdatedEvent(this.moduleRef, 1); } // データイベント更新 if (this.internalModuleUpdateDataEventId != null && this.internalModuleUpdateDataEventId !== dataEventId) { if (this.internalModuleExistsInDII) { // モジュール送出->モジュール非送出 this.dispatchModuleUpdatedEvent(this.moduleRef, 5); } } this.internalModuleExistsInDII = false; this.internalModuleUpdateVersion = undefined; this.internalModuleUpdateDataEventId = dataEventId; } else { if (!this.internalModuleExistsInDII) { // モジュール非送出->モジュール送出 this.dispatchModuleUpdatedEvent(this.moduleRef, 2); } else { // 初回DII受信時はイベント発生しないはず if (this.internalModuleUpdateVersion != null) { if (this.internalModuleUpdateVersion !== module.version) { // 更新検出の段階でイベント発生 this.dispatchModuleUpdatedEvent(this.moduleRef, 0); } } this.internalModuleUpdateVersion = module.version; } // データイベント更新 if (this.internalModuleUpdateDataEventId != null && this.internalModuleUpdateDataEventId !== dataEventId) { if (this.internalModuleExistsInDII) { // モジュール送出->モジュール送出 this.dispatchModuleUpdatedEvent(this.moduleRef, 6); } else { // モジュール非送出->モジュール送出 this.dispatchModuleUpdatedEvent(this.moduleRef, 4); } } this.internalModuleExistsInDII = true; const cachedModule = this.ownerDocument.resources.getCachedModule(componentId, moduleId); this.internalModuleUpdateVersion = cachedModule?.version; this.internalModuleUpdateDataEventId = cachedModule?.dataEventId; } } public set subscribe(value: boolean) { if (Boolean(value)) { if (!this.subscribe) { this.internalTimerFired = false; this.internalModuleUpdateDataEventId = undefined; this.internalModuleUpdateVersion = undefined; this.internalModuleExistsInDII = undefined; this.internalMessageVersion = undefined; this.internalNPTReferred = false; } this.node.setAttribute("subscribe", "subscribe"); if (this.type === "ModuleUpdated" && this.internalModuleExistsInDII == null) { this.subscribeModuleUpdated(); } } else { this.node.removeAttribute("subscribe"); } } } interface BMLEventData { type: string; target: HTMLElement | null; } interface BMLIntrinsicEventData extends BMLEventData { keyCode: number; } interface BMLBeventEventData extends BMLEventData { status: number; privateData: string; esRef: string; messageId: number; messageVersion: number; messageGroupId: number; moduleRef: string; languageTag: number; registerId: number; serviceId: number; eventId: number; peripheralRef: string; object: BMLObjectElement | null; segmentId: string | null; } // impl export class BMLEvent { protected _data: BMLEventData; constructor(data: BMLEventData) { this._data = { ...data }; } public get type(): DOMString { return this._data.type; } public get target(): HTMLElement | null { return this._data.target; } } // impl export class BMLIntrinsicEvent extends BMLEvent { protected _keyCode: number; constructor(data: BMLIntrinsicEventData) { super(data); this._keyCode = data.keyCode; } public get keyCode(): number { return this._keyCode; } } // impl export class BMLBeventEvent extends BMLEvent { protected _data: BMLBeventEventData; constructor(partialData: Partial<BMLBeventEventData> & BMLEventData) { const data = { ...{ target: null, status: 0, privateData: "", esRef: "", messageId: 0, messageVersion: 0, messageGroupId: 0, moduleRef: "", languageTag: 0, registerId: 0, serviceId: 0, eventId: 0, peripheralRef: "", object: null, segmentId: null, }, ...partialData, }; super(data); this._data = data; } public get status(): number { return this._data.status; } public get privateData(): string { return this._data.privateData; } public get esRef(): string { return this._data.esRef; } public get messageId(): number { return this._data.messageId; } public get messageVersion(): number { return this._data.messageVersion; } public get messageGroupId(): number { return this._data.messageGroupId; } public get moduleRef(): string { return this._data.moduleRef; } public get languageTag(): number { return this._data.languageTag; } // public get registerId(): number { return this.registerId; } // public get serviceId(): string { return this.serviceId; } // public get eventId(): string { return this.eventId; } public get peripheralRef(): string { return this.peripheralRef; } public get object(): BMLObjectElement | null { return this._data.object; } public get segmentId(): string | null { return this._data.segmentId; } } // impl export class DOMImplementation { public hasFeature(feature: string, version: string) { return feature.toUpperCase() === "BML" && version === "1.0"; } } }
the_stack
import * as path from 'path'; import * as fs from 'fs'; import { IEntity } from '@materia/interfaces'; import { WebsocketInstance } from '../../lib/websocket'; import { App, Entity, MateriaError, loadEntitiesJson, generateActionId } from '../../lib'; export class DatabaseController { constructor(private app: App, websocket: WebsocketInstance) {} tryAuth(req, res) { const conf = req.body; this.app.database.tryDatabase(conf) .then((data) => { res.status(200).json(data); }).catch(err => { res.status(500).send({error: true, message: err.message }); }); } getEntities(req, res) { return res.status(200).send({entities: loadEntitiesJson(this.app)}); } getRelations(req, res) { return res.status(200).send({relations: this.app.entities.findAllRelations({ implicit: true })}); } createEntity(req, res) { const entity: IEntity = req.body; let p: Promise<Entity>; this.app.watcher.disable(); if (entity.virtual) { p = this.app.entities .addVirtual( { name: entity.name, fields: entity.fields }, { apply: true, save: true, history: true } ); } else { p = this.app.entities .add( { name: entity.name, fields: entity.fields }, { apply: true, save: true, history: true } ); } return p.then((ent: Entity) => { this.app.watcher.enable(); res.status(201).json(ent.toJson()); }).catch(err => { this.app.watcher.enable(); res.status(500).send({error: true, message: err.message }); }); } removeEntity(req, res) { const name = req.params.entity; this.app.watcher.disable(); this.app.entities.remove(name, { save: true, apply: true, history: true }).then(() => { this.app.watcher.enable(); res.status(200).json({ entities: loadEntitiesJson(this.app), endpoints: this.app.api.findAll().map(e => e.toJson()) }); }).catch(err => { this.app.watcher.enable(); res.status(500).json({ error: true, message: err.message }); }); } moveEntity(req, res) { const {x, y} = req.body; const entity = this.app.entities.get(req.params.entity); if ( ! entity ) { return res.status(400).json(new Error(`Entity "${req.params.entity}" does not exist`)); } this.app.watcher.disable(); entity.move(x, y).then(() => { this.app.watcher.enable(); res.status(200).json(entity.toJson()); }).catch(err => { this.app.watcher.enable(); res.status(500).send({ error: true, message: err.message }); }); } renameEntity(req, res) { const oldName = req.params.entity; const {new_name} = req.body; this.app.watcher.disable(); this.app.entities.rename(oldName, new_name, { save: true, apply: true, history: true }) .then(() => { this.app.watcher.enable(); res.status(200).json( Object.assign({}, this.app.entities.get(new_name).toJson(), { name: new_name })); }).catch(err => { this.app.watcher.enable(); res.status(500).send({ error: true, message: err.message }); }); } saveField(req, res) { const field = req.body; const entityName = req.params.entity; const entity = this.app.entities.get(entityName); if ( ! entity) { return res.status(400).send({error: true, message: `Entity "${entityName}" does not exists`}); } if (field.primary) { field.unique = true; } if (field.unique) { field.required = true; if (field.default) { delete field.default; } if (field.autoIncrement) { delete field.autoIncrement; } } // TODO: add this when uniqueGroup enabled // if (field.hasUniqueGroup && field.uniqueGroup) { // field.unique = field.uniqueGroup; // if (field.autoIncrement) { // delete field.autoIncrement; // } // } if (field.required) { field.default = false; if (field.defaultValue) { delete field.defaultValue; } } if (field.type !== 'number' && field.autoIncrement) { delete field.autoIncrement; } this.app.watcher.disable(); let promise; if (entity.getField(field.name)) { promise = entity.updateField(field.name, field, { save: true, apply: true, history: true, db: true }); } else { promise = entity.addField(field, { save: true, apply: true, history: true, db: true }); } promise.then(() => { this.app.watcher.enable(); return res.status(200).send(loadEntitiesJson(this.app)); }).catch(err => { this.app.watcher.enable(); return res.status(500).send({ error: true, message: err.message }); }); } loadModel(req, res) { const fromAddon: string = req.query.fromAddon; const modelName: string = req.params.model; const basePath = fromAddon ? fromAddon : path.join(this.app.path, 'server', 'models', 'queries'); fs.readFile( path.join(basePath, modelName + '.js'), 'utf-8', (err, data) => { if (err) { return res.status(500).send({ error: true, message: err.message }); } if (data) { const code = data.toString(); return res.status(200).send(code); } else { return res.status(200).send(); } } ); } removeField(req, res) { const { entity, field } = req.params; const entityInstance = this.app.entities.get(entity); if ( ! entityInstance) { return res.status(400).send({error: true, message: `Entity "${entity}" does not exists`}); } this.app.watcher.disable(); entityInstance.removeField(field, { save: true, apply: true, history: true }) .then(() => { this.app.watcher.enable(); res.status(200).json(loadEntitiesJson(this.app)); }) .catch(err => { this.app.watcher.enable(); res.status(500).send({ error: true, message: err.message }); }); } createQuery(req, res) { const entity = this.app.entities.get(req.params.entity); const query = req.body; if ( ! entity) { return res.status(400).send(new MateriaError(`Entity "${req.params.entity}" does not exists`)); } this.app.watcher.disable(); let p = Promise.resolve(); if (query.type == 'sql') { query.opts.query = query.code; } if (query.type == 'custom') { const basePath = entity.fromAddon ? entity.fromAddon.path : this.app.path; p = p.then(() => this.app.saveFile( path.join( basePath, 'server', 'models', 'queries', query.opts.model + '.js' ), query.code, { mkdir: true } )); } p.then(() => entity.addQuery(query)).then(() => { this.app.watcher.enable(); res.status(200).send(loadEntitiesJson(this.app)); }).catch(err => { this.app.watcher.enable(); res.status(500).send({ error: true, message: err.message }); }); } removeQuery(req, res) { const entity = this.app.entities.get(req.params.entity); if ( ! entity) { return res.status(400).send(new MateriaError(`Entity "${req.params.entity}" does not exists`)); } this.app.watcher.disable(); entity.removeQuery(req.params.queryId).then(() => { this.app.watcher.enable(); res.status(200).json(loadEntitiesJson(this.app)); }).catch(err => { this.app.watcher.enable(); res.status(500).send({ error: true, message: err.message }); }); } runQuery(req, res) { const {entity, queryId} = req.params; const entityInstance = this.app.entities.get(entity); if ( ! entity ) { return res.status(400).send({error: true, message: `Entity "${entity}" does not exists`}); } const query: any = entityInstance.getQuery(queryId); if ( ! query ) { return res.status(400).send({error: true, message: `Query "${queryId}" does not exists (${entity})`}); } query.run(req.body, { raw: true }) .then((response: any) => { if (Array.isArray(response)) { const result = { data: response, count: response.length }; return result; } else if (typeof response === 'string' || typeof response === 'number') { return { data: [{ response: response }], count: 1 }; } else if (response == null) { return {data: [], count: 0}; } else if (typeof response === 'object') { const keys = Object.keys(response); if (response && keys.indexOf('count') != -1 && keys.indexOf('data') != -1) { return response; } else { return { data: [response], count: 1 }; } } }).then(data => { res.status(200).send(data); }).catch(error => { res.status(500).send({ error: true, message: error.message }); }); } listActions(req, res) { res.status(200).json(this.app.actions.findAll()); } addAction(req, res) { generateActionId().then(id => { const action = Object.assign({}, req.body, { id }); this.app.watcher.disable(); try { this.app.actions.register(action, { save: true }); this.app.watcher.enable(); res.status(200).json( loadEntitiesJson(this.app) ); } catch (e) { this.app.watcher.enable(); res.status(400).json({ error: e.message }); } }).catch(err => { res.status(500).send({ error: true, message: err.message }); }); } updateAction(req, res) { const action = req.body; this.app.watcher.disable(); try { action.id = req.params.id; if (req.params[0]) { action.id += req.params[0]; } this.app.actions.register(action, { save: true }); this.app.watcher.enable(); res.status(200).json( loadEntitiesJson(this.app) ); } catch (e) { this.app.watcher.enable(); res.status(400).json({ error: true, message: e.message }); } } removeAction(req, res) { let id = req.params.id; if (req.params[0]) { id += req.params[0]; } this.app.watcher.disable(); if (this.app.actions.remove(id, { save: true })) { this.app.watcher.enable(); res.status(200).json( loadEntitiesJson(this.app) ); } else { this.app.watcher.enable(); res.status(400).json({ error: true, message: `Action id "${req.params.id}" not found.`}); } } createRelation(req, res) { const payload = req.body; this.app.watcher.disable(); this.app.entities .get(payload.rel2.reference.entity) .addRelation(payload.rel1, { save: true, apply: true, history: true, db: true }).then(() => { return this.app.entities .get(payload.rel1.reference.entity) .addRelation(payload.rel2, { save: true, apply: true, history: true, db: true }); }).then(() => { this.app.watcher.enable(); return res.status(201).json({ entities: loadEntitiesJson(this.app), relations: this.app.entities.findAllRelations({ implicit: true }) }); }).catch(err => { this.app.watcher.enable(); res.status(500).send({ error: true, message: err.message }); }); } removeRelation(req, res) { let relation = null; const type = req.params.type; let entity = this.app.entities.get(req.params.entity); if ( ! entity) { return res.status(400).send({error: true, message: `Entity "${req.params.entity}" does not exists`}); } if (type === 'belongsToMany') { const entityRelation = req.params.relationFieldOrEntity; relation = entity.getBelongsToManyRelation(entityRelation); } else { const field = req.params.relationFieldOrEntity; relation = entity.getRelationByField(field); } if (relation.type === 'hasMany' || relation.type === 'hasOne') { entity = this.app.entities.get(relation.reference.entity); relation = entity.getRelationByField(relation.reference.field); } if ( ! relation) { return res.status(400).send({error: true, message: 'Relation not found'}); } this.app.watcher.disable(); entity.removeRelation(relation, { save: true, apply: true, history: true, db: true }) .then(() => { this.app.watcher.enable(); return res.status(200).json({ entities: loadEntitiesJson(this.app), relations: this.app.entities.findAllRelations({ implicit: true }) }); }).catch(err => { this.app.watcher.enable(); res.status(500).send({error: true, message: err.message}); }); } runSql(req, res) { this.app.database.runSql(req.body.opts.query) .then(data => { const result: any = { data: data ?? [], count: data?.length ?? 0 }; if (req.body.from) { result.from = req.body.from; } res.status(200).json(result); }) .catch(err => res.status(500).send({error: true, message: err.message})); } getDiffs(req, res) { return this.app.synchronizer.diff().then((diffs) => { res.status(200).send(diffs); }).catch(err => { res.status(500).send({ error: true, message: err.message }); }); } sync(req, res) { const diffs = req.body.diffs; const type = req.body.type; if (type === 'entitiesToDatabase') { this.app.watcher.disable(); this.app.synchronizer.entitiesToDatabase(diffs, {save: true}) .then((result) => { this.app.watcher.enable(); res.status(200).send(result); }).catch(err => { this.app.watcher.enable(); res.status(500).send(err); }); } else if (type === 'databaseToEntities') { this.app.watcher.disable(); this.app.synchronizer.databaseToEntities(diffs, {save: true}) .then((result) => { this.app.watcher.enable(); res.status(200).send(result); }).catch(err => { this.app.watcher.enable(); res.status(500).send({ error: true, message: err.message }); }); } else { return res.status(500).send({ error: true, message: `Sync type "${type}" not found` }); } } }
the_stack
import { INodeProperties, } from 'n8n-workflow'; import { address, currencies, makeCustomFieldsFixedCollection, makeGetAllFields, } from './SharedFields'; export const leadOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'lead', ], }, }, options: [ { name: 'Create', value: 'create', description: 'Create a lead', }, { name: 'Create or Update', value: 'upsert', description: 'Create a new record, or update the current one if it already exists (upsert)', }, { name: 'Delete', value: 'delete', description: 'Delete a lead', }, { name: 'Get', value: 'get', description: 'Get a lead', }, { name: 'Get All', value: 'getAll', description: 'Get all leads', }, { name: 'Get Fields', value: 'getFields', description: 'Get lead fields', }, { name: 'Update', value: 'update', description: 'Update a lead', }, ], default: 'create', description: 'Operation to perform', }, ]; export const leadFields: INodeProperties[] = [ // ---------------------------------------- // lead: create // ---------------------------------------- { displayName: 'Company', name: 'Company', description: 'Company at which the lead works.', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'lead', ], operation: [ 'create', ], }, }, }, { displayName: 'Last Name', name: 'lastName', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'lead', ], operation: [ 'create', ], }, }, }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'lead', ], operation: [ 'create', ], }, }, options: [ address, { displayName: 'Annual Revenue', name: 'Annual_Revenue', type: 'number', default: '', description: 'Annual revenue of the lead’s company.', }, { displayName: 'Currency', name: 'Currency', type: 'options', default: 'USD', description: 'Symbol of the currency in which revenue is generated.', options: currencies, }, makeCustomFieldsFixedCollection('lead'), { displayName: 'Description', name: 'Description', type: 'string', default: '', }, { displayName: 'Designation', name: 'Designation', type: 'string', default: '', description: 'Position of the lead at their company.', }, { displayName: 'Email', name: 'Email', type: 'string', default: '', }, { displayName: 'Email Opt Out', name: 'Email_Opt_Out', type: 'boolean', default: false, }, { displayName: 'Fax', name: 'Fax', type: 'string', default: '', }, { displayName: 'First Name', name: 'First_Name', type: 'string', default: '', }, { displayName: 'Full Name', name: 'Full_Name', type: 'string', default: '', }, { displayName: 'Industry', name: 'Industry', type: 'string', default: '', description: 'Industry to which the lead belongs.', }, { displayName: 'Industry Type', name: 'Industry_Type', type: 'string', default: '', description: 'Type of industry to which the lead belongs.', }, { displayName: 'Lead Source', name: 'Lead_Source', type: 'string', default: '', description: 'Source from which the lead was created.', }, { displayName: 'Lead Status', name: 'Lead_Status', type: 'string', default: '', }, { displayName: 'Mobile', name: 'Mobile', type: 'string', default: '', }, { displayName: 'Number of Employees', name: 'No_of_Employees', type: 'number', default: '', description: 'Number of employees in the lead’s company.', }, { displayName: 'Phone', name: 'Phone', type: 'string', default: '', }, { displayName: 'Salutation', name: 'Salutation', type: 'string', default: '', }, { displayName: 'Secondary Email', name: 'Secondary_Email', type: 'string', default: '', }, { displayName: 'Skype ID', name: 'Skype_ID', type: 'string', default: '', }, { displayName: 'Twitter', name: 'Twitter', type: 'string', default: '', }, { displayName: 'Website', name: 'Website', type: 'string', default: '', }, ], }, // ---------------------------------------- // lead: upsert // ---------------------------------------- { displayName: 'Company', name: 'Company', description: 'Company at which the lead works.', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'lead', ], operation: [ 'upsert', ], }, }, }, { displayName: 'Last Name', name: 'lastName', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'lead', ], operation: [ 'upsert', ], }, }, }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'lead', ], operation: [ 'upsert', ], }, }, options: [ address, { displayName: 'Annual Revenue', name: 'Annual_Revenue', type: 'number', default: '', description: 'Annual revenue of the lead’s company.', }, { displayName: 'Currency', name: 'Currency', type: 'options', default: 'USD', description: 'Symbol of the currency in which revenue is generated.', options: currencies, }, makeCustomFieldsFixedCollection('lead'), { displayName: 'Description', name: 'Description', type: 'string', default: '', }, { displayName: 'Designation', name: 'Designation', type: 'string', default: '', description: 'Position of the lead at their company.', }, { displayName: 'Email', name: 'Email', type: 'string', default: '', description: 'Email of the lead. If a record with this email exists it will be updated, otherwise a new one will be created.', }, { displayName: 'Email Opt Out', name: 'Email_Opt_Out', type: 'boolean', default: false, }, { displayName: 'Fax', name: 'Fax', type: 'string', default: '', }, { displayName: 'First Name', name: 'First_Name', type: 'string', default: '', }, { displayName: 'Full Name', name: 'Full_Name', type: 'string', default: '', }, { displayName: 'Industry', name: 'Industry', type: 'string', default: '', description: 'Industry to which the lead belongs.', }, { displayName: 'Industry Type', name: 'Industry_Type', type: 'string', default: '', description: 'Type of industry to which the lead belongs.', }, { displayName: 'Lead Source', name: 'Lead_Source', type: 'string', default: '', description: 'Source from which the lead was created.', }, { displayName: 'Lead Status', name: 'Lead_Status', type: 'string', default: '', }, { displayName: 'Mobile', name: 'Mobile', type: 'string', default: '', }, { displayName: 'Number of Employees', name: 'No_of_Employees', type: 'number', default: '', description: 'Number of employees in the lead’s company.', }, { displayName: 'Phone', name: 'Phone', type: 'string', default: '', }, { displayName: 'Salutation', name: 'Salutation', type: 'string', default: '', }, { displayName: 'Secondary Email', name: 'Secondary_Email', type: 'string', default: '', }, { displayName: 'Skype ID', name: 'Skype_ID', type: 'string', default: '', }, { displayName: 'Twitter', name: 'Twitter', type: 'string', default: '', }, { displayName: 'Website', name: 'Website', type: 'string', default: '', }, ], }, // ---------------------------------------- // lead: delete // ---------------------------------------- { displayName: 'Lead ID', name: 'leadId', description: 'ID of the lead to delete.', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'lead', ], operation: [ 'delete', ], }, }, }, // ---------------------------------------- // lead: get // ---------------------------------------- { displayName: 'Lead ID', name: 'leadId', description: 'ID of the lead to retrieve.', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'lead', ], operation: [ 'get', ], }, }, }, // ---------------------------------------- // lead: getAll // ---------------------------------------- ...makeGetAllFields('lead'), // ---------------------------------------- // lead: update // ---------------------------------------- { displayName: 'Lead ID', name: 'leadId', description: 'ID of the lead to update.', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'lead', ], operation: [ 'update', ], }, }, }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'lead', ], operation: [ 'update', ], }, }, options: [ address, { displayName: 'Annual Revenue', name: 'Annual_Revenue', type: 'number', default: '', description: 'Annual revenue of the lead’s company.', }, { displayName: 'Company', name: 'Company', type: 'string', default: '', description: 'Company at which the lead works.', }, { displayName: 'Currency', name: 'Currency', type: 'options', default: 'USD', description: 'Symbol of the currency in which revenue is generated.', options: currencies, }, makeCustomFieldsFixedCollection('lead'), { displayName: 'Description', name: 'Description', type: 'string', default: '', }, { displayName: 'Designation', name: 'Designation', type: 'string', default: '', description: 'Position of the lead at their company.', }, { displayName: 'Email', name: 'Email', type: 'string', default: '', }, { displayName: 'Email Opt Out', name: 'Email_Opt_Out', type: 'boolean', default: false, }, { displayName: 'Fax', name: 'Fax', type: 'string', default: '', }, { displayName: 'First Name', name: 'First_Name', type: 'string', default: '', }, { displayName: 'Full Name', name: 'Full_Name', type: 'string', default: '', }, { displayName: 'Industry', name: 'Industry', type: 'string', default: '', description: 'Industry to which the lead belongs.', }, { displayName: 'Industry Type', name: 'Industry_Type', type: 'string', default: '', description: 'Type of industry to which the lead belongs.', }, { displayName: 'Last Name', name: 'Last_Name', type: 'string', default: '', }, { displayName: 'Lead Source', name: 'Lead_Source', type: 'string', default: '', description: 'Source from which the lead was created.', }, { displayName: 'Lead Status', name: 'Lead_Status', type: 'string', default: '', }, { displayName: 'Mobile', name: 'Mobile', type: 'string', default: '', }, { displayName: 'Number of Employees', name: 'No_of_Employees', type: 'number', default: '', description: 'Number of employees in the lead’s company.', }, { displayName: 'Phone', name: 'Phone', type: 'string', default: '', }, { displayName: 'Salutation', name: 'Salutation', type: 'string', default: '', }, { displayName: 'Secondary Email', name: 'Secondary_Email', type: 'string', default: '', }, { displayName: 'Skype ID', name: 'Skype_ID', type: 'string', default: '', }, { displayName: 'Twitter', name: 'Twitter', type: 'string', default: '', }, { displayName: 'Website', name: 'Website', type: 'string', default: '', }, ], }, ];
the_stack
import { CoreTextUtils } from '@services/utils/text'; import { CoreUtils } from '@services/utils/utils'; import { CoreH5P } from '@features/h5p/services/h5p'; import { Translate } from '@singletons'; import { CoreH5PCore, CoreH5PLibraryData, CoreH5PLibraryAddonData, CoreH5PContentDepsTreeDependency } from './core'; const ALLOWED_STYLEABLE_TAGS = ['span', 'p', 'div', 'h1', 'h2', 'h3', 'td']; /** * Equivalent to H5P's H5PContentValidator, but without some of the validations. * It's also used to build the dependency list. */ export class CoreH5PContentValidator { protected typeMap = { text: 'validateText', number: 'validateNumber', // eslint-disable-line id-blacklist boolean: 'validateBoolean', // eslint-disable-line id-blacklist list: 'validateList', group: 'validateGroup', file: 'validateFile', image: 'validateImage', video: 'validateVideo', audio: 'validateAudio', select: 'validateSelect', library: 'validateLibrary', }; protected nextWeight = 1; protected libraries: {[libString: string]: CoreH5PLibraryData} = {}; protected dependencies: {[key: string]: CoreH5PContentDepsTreeDependency} = {}; protected relativePathRegExp = /^((\.\.\/){1,2})(.*content\/)?(\d+|editor)\/(.+)$/; protected allowedHtml: {[tag: string]: string} = {}; protected allowedStyles?: RegExp[]; protected metadataSemantics?: CoreH5PSemantics[]; protected copyrightSemantics?: CoreH5PSemantics; constructor(protected siteId: string) { } /** * Add Addon library. * * @param library The addon library to add. * @return Promise resolved when done. */ async addon(library: CoreH5PLibraryAddonData): Promise<void> { const depKey = 'preloaded-' + library.machineName; this.dependencies[depKey] = { library: library, type: 'preloaded', }; this.nextWeight = await CoreH5P.h5pCore.findLibraryDependencies(this.dependencies, library, this.nextWeight); this.dependencies[depKey].weight = this.nextWeight++; } /** * Get the flat dependency tree. * * @return Dependencies. */ getDependencies(): {[key: string]: CoreH5PContentDepsTreeDependency} { return this.dependencies; } /** * Validate metadata * * @param metadata Metadata. * @return Promise resolved with metadata validated & filtered. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any validateMetadata(metadata: any): Promise<unknown> { const semantics = this.getMetadataSemantics(); const group = CoreUtils.clone(metadata || {}); // Stop complaining about "invalid selected option in select" for old content without license chosen. if (group.license === undefined) { group.license = 'U'; } return this.validateGroup(group, { type: 'group', fields: semantics }, false); } /** * Validate given text value against text semantics. * * @param text Text to validate. * @param semantics Semantics. * @return Validated text. */ validateText(text: string, semantics: CoreH5PSemantics): string { if (typeof text != 'string') { text = ''; } if (semantics.tags) { // Not testing for empty array allows us to use the 4 defaults without specifying them in semantics. let tags = ['div', 'span', 'p', 'br'].concat(semantics.tags); // Add related tags for table etc. if (tags.indexOf('table') != -1) { tags = tags.concat(['tr', 'td', 'th', 'colgroup', 'thead', 'tbody', 'tfoot']); } if (tags.indexOf('b') != -1) { tags.push('strong'); } if (tags.indexOf('i') != -1) { tags.push('em'); } if (tags.indexOf('ul') != -1 || tags.indexOf('ol') != -1) { tags.push('li'); } if (tags.indexOf('del') != -1 || tags.indexOf('strike') != -1) { tags.push('s'); } tags = CoreUtils.uniqueArray(tags); // Determine allowed style tags const stylePatterns: RegExp[] = []; // All styles must be start to end patterns (^...$) if (semantics.font) { if (semantics.font.size) { stylePatterns.push(/^font-size: *[0-9.]+(em|px|%) *;?$/i); } if (semantics.font.family) { stylePatterns.push(/^font-family: *[-a-z0-9," ]+;?$/i); } if (semantics.font.color) { stylePatterns.push(/^color: *(#[a-f0-9]{3}[a-f0-9]{3}?|rgba?\([0-9, ]+\)) *;?$/i); } if (semantics.font.background) { stylePatterns.push(/^background-color: *(#[a-f0-9]{3}[a-f0-9]{3}?|rgba?\([0-9, ]+\)) *;?$/i); } if (semantics.font.spacing) { stylePatterns.push(/^letter-spacing: *[0-9.]+(em|px|%) *;?$/i); } if (semantics.font.height) { stylePatterns.push(/^line-height: *[0-9.]+(em|px|%|) *;?$/i); } } // Alignment is allowed for all wysiwyg texts stylePatterns.push(/^text-align: *(center|left|right);?$/i); // Strip invalid HTML tags. text = this.filterXss(text, tags, stylePatterns); } else { // Filter text to plain text. text = CoreTextUtils.escapeHTML(text, false); } // Check if string is within allowed length. if (semantics.maxLength !== undefined) { text = text.substring(0, semantics.maxLength); } return text; } /** * Validates content files * * @param contentPath The path containing content files to validate. * @param isLibrary Whether it's a library. * @return True if all files are valid. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars validateContentFiles(contentPath: string, isLibrary: boolean = false): boolean { // Nothing to do, already checked by Moodle. return true; } /** * Validate given value against number semantics. * * @param num Number to validate. * @param semantics Semantics. * @return Validated number. */ validateNumber(value: unknown, semantics: CoreH5PSemantics): number { // Validate that num is indeed a number. let num = Number(value); if (isNaN(num)) { num = 0; } // Check if number is within valid bounds. Move within bounds if not. if (semantics.min !== undefined && num < semantics.min) { num = semantics.min; } if (semantics.max !== undefined && num > semantics.max) { num = semantics.max; } // Check if number is within allowed bounds even if step value is set. if (semantics.step !== undefined) { const testNumber = num - (semantics.min !== undefined ? semantics.min : 0); const rest = testNumber % semantics.step; if (rest !== 0) { num -= rest; } } // Check if number has proper number of decimals. if (semantics.decimals !== undefined) { num = Number(num.toFixed(semantics.decimals)); } return num; } /** * Validate given value against boolean semantics. * * @param bool Boolean to check. * @return Validated bool. */ validateBoolean(bool: unknown): boolean { return !!bool; } /** * Validate select values. * * @param select Values to validate. * @param semantics Semantics. * @return Validated select. */ validateSelect(select: string | string[], semantics: CoreH5PSemantics): string | string[] { const optional = semantics.optional; const options: Record<string, boolean> = {}; let strict = false; if (semantics.options && semantics.options.length) { // We have a strict set of options to choose from. strict = true; semantics.options.forEach((option: OptionSemantics) => { // Support optgroup - just flatten options into one. if (option.type == 'optgroup') { option.options?.forEach((subOption) => { options[subOption.value || ''] = true; }); } else if (option.value) { options[option.value] = true; } }); } if (semantics.multiple && Array.isArray(select)) { // Multi-choice generates array of values. Test each one against valid options, if we are strict. for (const key in select) { const value = select[key]; if (strict && !optional && !options[value]) { delete select[key]; } else { select[key] = CoreTextUtils.escapeHTML(value, false); } } } else { // Single mode. If we get an array in here, we chop off the first element and use that instead. if (Array.isArray(select)) { select = select[0]; } if (strict && !optional && !options[select]) { select = (<OptionSemantics> semantics.options![0]).value || ''; } select = CoreTextUtils.escapeHTML(select, false); } return select; } /** * Validate given list value against list semantics. * Will recurse into validating each item in the list according to the type. * * @param list List to validate. * @param semantics Semantics. * @return Validated list. */ async validateList(list: Record<string, unknown> | unknown[], semantics: CoreH5PSemantics): Promise<unknown[] | null> { const field = semantics.field!; const validateFunction = this[this.typeMap[field.type || '']].bind(this); const isArray = Array.isArray(list); let keys = Object.keys(list); // Check that list is not longer than allowed length. if (semantics.max !== undefined) { keys = keys.slice(0, semantics.max); } // Validate each element in list. for (const i in keys) { const key = keys[i]; const keyNumber = parseInt(key, 10); if (isNaN(keyNumber)) { // It's an object and the key isn't an integer. Delete it. delete list[key]; } else { const val = await validateFunction(list[keyNumber], field); if (val === null) { if (isArray) { (<unknown[]> list).splice(keyNumber, 1); } else { delete list[key]; } } else { list[keyNumber] = val; } } } if (!isArray) { list = CoreUtils.objectToArray(<Record<string, unknown>> list); } if (!list.length) { return null; } return <unknown[]> list; } /** * Validate a file like object, such as video, image, audio and file. * * @param file File to validate. * @param semantics Semantics. * @param typeValidKeys List of valid keys. * @return Promise resolved with the validated file. */ protected async validateFilelike(file: FileLike, semantics: CoreH5PSemantics, typeValidKeys: string[] = []): Promise<FileLike> { // Do not allow to use files from other content folders. const matches = file.path.match(this.relativePathRegExp); if (matches && matches.length) { file.path = matches[5]; } // Remove temporary files suffix. if (file.path.slice(-4) === '#tmp') { file.path = file.path.substring(0, file.path.length - 4); } // Make sure path and mime does not have any special chars file.path = CoreTextUtils.escapeHTML(file.path, false); if (file.mime) { file.mime = CoreTextUtils.escapeHTML(file.mime, false); } // Remove attributes that should not exist, they may contain JSON escape code. let validKeys = ['path', 'mime', 'copyright'].concat(typeValidKeys); if (semantics.extraAttributes) { validKeys = validKeys.concat(semantics.extraAttributes); } validKeys = CoreUtils.uniqueArray(validKeys); this.filterParams(file, validKeys); if (typeof file.width == 'string') { file.width = parseInt(file.width, 10); } if (typeof file.height == 'string') { file.height = parseInt(file.height, 10); } if (file.codecs) { file.codecs = CoreTextUtils.escapeHTML(file.codecs, false); } if (typeof file.bitrate == 'string') { file.bitrate = parseInt(file.bitrate, 10); } if (file.quality !== undefined) { if (file.quality === null || file.quality.level === undefined || file.quality.label === undefined) { delete file.quality; } else { this.filterParams(file.quality, ['level', 'label']); file.quality.level = Number(file.quality.level); file.quality.label = CoreTextUtils.escapeHTML(file.quality.label, false); } } if (file.copyright !== undefined) { await this.validateGroup(file.copyright, this.getCopyrightSemantics()); } return file; } /** * Validate given file data. * * @param file File. * @param semantics Semantics. * @return Promise resolved with the validated file. */ validateFile(file: FileLike, semantics: CoreH5PSemantics): Promise<FileLike> { return this.validateFilelike(file, semantics); } /** * Validate given image data. * * @param image Image. * @param semantics Semantics. * @return Promise resolved with the validated file. */ validateImage(image: FileLike, semantics: CoreH5PSemantics): Promise<FileLike> { return this.validateFilelike(image, semantics, ['width', 'height', 'originalImage']); } /** * Validate given video data. * * @param video Video. * @param semantics Semantics. * @return Promise resolved with the validated file. */ async validateVideo(video: Record<string, FileLike>, semantics: CoreH5PSemantics): Promise<Record<string, FileLike>> { for (const key in video) { await this.validateFilelike(video[key], semantics, ['width', 'height', 'codecs', 'quality', 'bitrate']); } return video; } /** * Validate given audio data. * * @param audio Audio. * @param semantics Semantics. * @return Promise resolved with the validated file. */ async validateAudio(audio: Record<string, FileLike>, semantics: CoreH5PSemantics): Promise<Record<string, FileLike>> { for (const key in audio) { await this.validateFilelike(audio[key], semantics); } return audio; } /** * Validate given group value against group semantics. * Will recurse into validating each group member. * * @param group Group. * @param semantics Semantics. * @param flatten Whether to flatten. * @return Promise resolved when done. */ async validateGroup(group: unknown, semantics: CoreH5PSemantics, flatten: boolean = true): Promise<unknown> { if (!semantics.fields) { return group; } // Groups with just one field are compressed in the editor to only output the child content. const isSubContent = semantics.isSubContent === true; if (semantics.fields.length == 1 && flatten && !isSubContent) { const field = semantics.fields[0]; const validateFunction = this[this.typeMap[field.type || '']].bind(this); return validateFunction(group, field); } else { const groupObject = <Record<string, unknown>> group; for (const key in groupObject) { // If subContentId is set, keep value if (isSubContent && key == 'subContentId') { continue; } // Find semantics for name=key. let found = false; let validateFunction: undefined | ((...args: unknown[]) => unknown); let field: CoreH5PSemantics | undefined; for (let i = 0; i < semantics.fields.length; i++) { field = semantics.fields[i]; if (field.name == key) { if (semantics.optional) { field.optional = true; } validateFunction = this[this.typeMap[field.type || '']].bind(this); found = true; break; } } if (found && validateFunction) { const val = await validateFunction(groupObject[key], field); groupObject[key] = val; if (val === null) { delete groupObject[key]; } } else { // Something exists in content that does not have a corresponding semantics field. Remove it. delete groupObject.key; } } return groupObject; } } /** * Validate given library value against library semantics. * Check if provided library is within allowed options. * Will recurse into validating the library's semantics too. * * @param value Value. * @param semantics Semantics. * @return Promise resolved when done. */ async validateLibrary(value: LibraryType, semantics: CoreH5PSemantics): Promise<LibraryType | undefined> { if (!value.library) { return; } if (!this.libraries[value.library]) { // Load the library and store it in the index of libraries. const libSpec = CoreH5PCore.libraryFromString(value.library); this.libraries[value.library] = await CoreH5P.h5pCore.loadLibrary( libSpec?.machineName || '', libSpec?.majorVersion || 0, libSpec?.minorVersion || 0, this.siteId, ); } const library = this.libraries[value.library]; // Validate parameters. value.params = await this.validateGroup(value.params, { type: 'group', fields: library.semantics }, false); // Validate subcontent's metadata if (value.metadata) { value.metadata = await this.validateMetadata(value.metadata); } let validKeys = ['library', 'params', 'subContentId', 'metadata']; if (semantics.extraAttributes) { validKeys = CoreUtils.uniqueArray(validKeys.concat(semantics.extraAttributes)); } this.filterParams(value, validKeys); if (value.subContentId && !value.subContentId.match(/^\{?[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\}?$/)) { delete value.subContentId; } // Find all dependencies for this library. const depKey = 'preloaded-' + library.machineName; if (!this.dependencies[depKey]) { this.dependencies[depKey] = { library: library, type: 'preloaded', }; this.nextWeight = await CoreH5P.h5pCore.findLibraryDependencies(this.dependencies, library, this.nextWeight); this.dependencies[depKey].weight = this.nextWeight++; return value; } else { return value; } } /** * Check params for a whitelist of allowed properties. * * @param params Object to filter. * @param whitelist List of keys to keep. */ filterParams(params: Record<string, unknown>, whitelist: string[]): void { for (const key in params) { if (whitelist.indexOf(key) == -1) { delete params[key]; } } } /** * Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities. * Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses. * * @param text The string with raw HTML in it. * @param allowedTags An array of allowed tags. * @param allowedStyles Allowed styles. * @return An XSS safe version of the string. */ protected filterXss(text: string, allowedTags?: string[], allowedStyles?: RegExp[]): string { if (!text || typeof text != 'string') { return text; } allowedTags = allowedTags || ['a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd']; this.allowedStyles = allowedStyles; // Store the text format. this.filterXssSplit(allowedTags, true); // Remove Netscape 4 JS entities. text = text.replace(/&\s*\{[^}]*(\}\s*;?|$)/g, ''); // Defuse all HTML entities. text = text.replace(/&/g, '&amp;'); // Change back only well-formed entities in our whitelist: // Decimal numeric entities. text = text.replace(/&amp;#([0-9]+;)/g, '&#$1'); // Hexadecimal numeric entities. text = text.replace(/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/g, '&#x$1'); // Named entities. text = text.replace(/&amp;([A-Za-z][A-Za-z0-9]*;)/g, '&$1'); const matches = text.match(/(<(?=[^a-zA-Z!/])|<!--.*?-->|<[^>]*(>|$)|>)/g); if (matches && matches.length) { matches.forEach((match) => { text = text.replace(match, this.filterXssSplit([match])); }); } return text; } /** * Processes an HTML tag. * * @param tags An array with various meaning depending on the value of store. * If store is TRUE then the array contains the allowed tags. * If store is FALSE then the array has one element, the HTML tag to process. * @param store Whether to store m. * @return string If the element isn't allowed, an empty string. Otherwise, the cleaned up version of the HTML element. */ protected filterXssSplit(tags: string[], store: boolean = false): string { if (store) { this.allowedHtml = CoreUtils.arrayToObject(tags); return ''; } const tag = tags[0]; if (tag.substring(0, 1) != '<') { // We matched a lone ">" character. return '&gt;'; } else if (tag.length == 1) { // We matched a lone "<" character. return '&lt;'; } const matches = tag.match(/^<\s*(\/\s*)?([a-zA-Z0-9-]+)\s*([^>]*)>?|(<!--.*?-->)$/); if (!matches) { // Seriously malformed. return ''; } const slash = matches[1] ? matches[1].trim() : ''; const attrList = matches[3] || ''; const comment = matches[4] || ''; let elem = matches[2] || ''; if (comment) { elem = '!--'; } if (!this.allowedHtml[elem.toLowerCase()]) { // Disallowed HTML element. return ''; } if (comment) { return comment; } if (slash != '') { return '</' + elem + '>'; } // Is there a closing XHTML slash at the end of the attributes? const newAttrList = attrList.replace(/(\s?)\/\s*$/g, '$1'); const xhtmlSlash = attrList != newAttrList ? ' /' : ''; // Clean up attributes. let attr2 = this.filterXssAttributes( newAttrList, ALLOWED_STYLEABLE_TAGS.indexOf(elem) != -1 ? this.allowedStyles : undefined, ).join(' '); attr2 = attr2.replace(/[<>]/g, ''); attr2 = attr2.length ? ' ' + attr2 : ''; return '<' + elem + attr2 + xhtmlSlash + '>'; } /** * Processes a string of HTML attributes. * * @param attr HTML attributes. * @param allowedStyles Allowed styles. * @return Cleaned up version of the HTML attributes. */ protected filterXssAttributes(attr: string, allowedStyles?: RegExp[]): string[] { const attrArray: string[] = []; let mode = 0; let attrName = ''; let skip = false; while (attr.length != 0) { // Was the last operation successful? let working = 0; let matches: RegExpMatchArray | null = null; let thisVal: string | undefined; switch (mode) { case 0: // Attribute name, href for instance. matches = attr.match(/^([-a-zA-Z]+)/); if (matches && matches.length > 1) { attrName = matches[1].toLowerCase(); skip = attrName == 'style' || attrName.substring(0, 2) == 'on' || attrName.substring(0, 1) == '-' || attrName.length > 96; // Ignore long attributes to avoid unnecessary processing overhead. working = mode = 1; attr = attr.replace(/^[-a-zA-Z]+/, ''); } break; case 1: // Equals sign or valueless ("selected"). if (attr.match(/^\s*=\s*/)) { working = 1; mode = 2; attr = attr.replace(/^\s*=\s*/, ''); break; } if (attr.match(/^\s+/)) { working = 1; mode = 0; if (!skip) { attrArray.push(attrName); } attr = attr.replace(/^\s+/, ''); } break; case 2: // Attribute value, a URL after href= for instance. matches = attr.match(/^"([^"]*)"(\s+|$)/); if (matches && matches.length > 1) { if (allowedStyles && attrName === 'style') { // Allow certain styles. for (let i = 0; i < allowedStyles.length; i++) { const pattern = allowedStyles[i]; if (matches[1].match(pattern)) { // All patterns are start to end patterns, and CKEditor adds one span per style. attrArray.push('style="' + matches[1] + '"'); break; } } break; } thisVal = this.filterXssBadProtocol(matches[1]); if (!skip) { attrArray.push(attrName + '="' + thisVal + '"'); } working = 1; mode = 0; attr = attr.replace(/^"[^"]*"(\s+|$)/, ''); break; } matches = attr.match(/^'([^']*)'(\s+|$)/); if (matches && matches.length > 1) { thisVal = this.filterXssBadProtocol(matches[1]); if (!skip) { attrArray.push(attrName + '="' + thisVal + '"'); } working = 1; mode = 0; attr = attr.replace(/^'[^']*'(\s+|$)/, ''); break; } matches = attr.match(/^([^\s"']+)(\s+|$)/); if (matches && matches.length > 1) { thisVal = this.filterXssBadProtocol(matches[1]); if (!skip) { attrArray.push(attrName + '="' + thisVal + '"'); } working = 1; mode = 0; attr = attr.replace(/^([^\s"']+)(\s+|$)/, ''); } break; default: } if (working == 0) { // Not well formed; remove and try again. attr = attr.replace(/^("[^"]*("|$)|'[^']*('|$)||\S)*\s*/, ''); mode = 0; } } // The attribute list ends with a valueless attribute like "selected". if (mode == 1 && !skip) { attrArray.push(attrName); } return attrArray; } /** * Processes an HTML attribute value and strips dangerous protocols from URLs. * * @param str The string with the attribute value. * @param decode Whether to decode entities in the str. * @return Cleaned up and HTML-escaped version of str. */ filterXssBadProtocol(str: string, decode: boolean = true): string { // Get the plain text representation of the attribute value (i.e. its meaning). if (decode) { str = CoreTextUtils.decodeHTMLEntities(str); } return CoreTextUtils.escapeHTML(this.stripDangerousProtocols(str), false); } /** * Strips dangerous protocols (e.g. 'javascript:') from a URI. * * @param uri A plain-text URI that might contain dangerous protocols. * @return A plain-text URI stripped of dangerous protocols. */ protected stripDangerousProtocols(uri: string): string { const allowedProtocols = { ftp: true, http: true, https: true, mailto: true, }; let before: string | undefined; // Iteratively remove any invalid protocol found. do { before = uri; const colonPos = uri.indexOf(':'); if (colonPos > 0) { // We found a colon, possibly a protocol. Verify. const protocol = uri.substring(0, colonPos); // If a colon is preceded by a slash, question mark or hash, it cannot possibly be part of the URL scheme. // This must be a relative URL, which inherits the (safe) protocol of the base document. if (protocol.match(/[/?#]/)) { break; } // Check if this is a disallowed protocol. if (!allowedProtocols[protocol.toLowerCase()]) { uri = uri.substring(colonPos + 1); } } } while (before != uri); return uri; } /** * Get metadata semantics. * * @return Semantics. */ getMetadataSemantics(): CoreH5PSemantics[] { if (this.metadataSemantics) { return this.metadataSemantics; } const ccVersions = this.getCCVersions(); this.metadataSemantics = [ { name: 'title', type: 'text', label: Translate.instant('core.h5p.title'), placeholder: 'La Gioconda', }, { name: 'license', type: 'select', label: Translate.instant('core.h5p.license'), default: 'U', options: [ { value: 'U', label: Translate.instant('core.h5p.undisclosed'), }, { type: 'optgroup', label: Translate.instant('core.h5p.creativecommons'), options: [ { value: 'CC BY', label: Translate.instant('core.h5p.ccattribution'), versions: ccVersions, }, { value: 'CC BY-SA', label: Translate.instant('core.h5p.ccattributionsa'), versions: ccVersions, }, { value: 'CC BY-ND', label: Translate.instant('core.h5p.ccattributionnd'), versions: ccVersions, }, { value: 'CC BY-NC', label: Translate.instant('core.h5p.ccattributionnc'), versions: ccVersions, }, { value: 'CC BY-NC-SA', label: Translate.instant('core.h5p.ccattributionncsa'), versions: ccVersions, }, { value: 'CC BY-NC-ND', label: Translate.instant('core.h5p.ccattributionncnd'), versions: ccVersions, }, { value: 'CC0 1.0', label: Translate.instant('core.h5p.ccpdd'), }, { value: 'CC PDM', label: Translate.instant('core.h5p.pdm'), }, ], }, { value: 'GNU GPL', label: Translate.instant('core.h5p.gpl'), }, { value: 'PD', label: Translate.instant('core.h5p.pd'), }, { value: 'ODC PDDL', label: Translate.instant('core.h5p.pddl'), }, { value: 'C', label: Translate.instant('core.h5p.copyrightstring'), }, ], }, { name: 'licenseVersion', type: 'select', label: Translate.instant('core.h5p.licenseversion'), options: ccVersions, optional: true, }, { name: 'yearFrom', type: 'number', label: Translate.instant('core.h5p.yearsfrom'), placeholder: '1991', min: -9999, max: 9999, optional: true, }, { name: 'yearTo', type: 'number', label: Translate.instant('core.h5p.yearsto'), placeholder: '1992', min: -9999, max: 9999, optional: true, }, { name: 'source', type: 'text', label: Translate.instant('core.h5p.source'), placeholder: 'https://', optional: true, }, { name: 'authors', type: 'list', field: { name: 'author', type: 'group', fields: [ { label: Translate.instant('core.h5p.authorname'), name: 'name', optional: true, type: 'text', }, { name: 'role', type: 'select', label: Translate.instant('core.h5p.authorrole'), default: 'Author', options: [ { value: 'Author', label: Translate.instant('core.h5p.author'), }, { value: 'Editor', label: Translate.instant('core.h5p.editor'), }, { value: 'Licensee', label: Translate.instant('core.h5p.licensee'), }, { value: 'Originator', label: Translate.instant('core.h5p.originator'), }, ], }, ], }, }, { name: 'licenseExtras', type: 'text', widget: 'textarea', label: Translate.instant('core.h5p.licenseextras'), optional: true, description: Translate.instant('core.h5p.additionallicenseinfo'), }, { name: 'changes', type: 'list', field: { name: 'change', type: 'group', label: Translate.instant('core.h5p.changelog'), fields: [ { name: 'date', type: 'text', label: Translate.instant('core.h5p.date'), optional: true, }, { name: 'author', type: 'text', label: Translate.instant('core.h5p.changedby'), optional: true, }, { name: 'log', type: 'text', widget: 'textarea', label: Translate.instant('core.h5p.changedescription'), placeholder: Translate.instant('core.h5p.changeplaceholder'), optional: true, }, ], }, }, { name: 'authorComments', type: 'text', widget: 'textarea', label: Translate.instant('core.h5p.authorcomments'), description: Translate.instant('core.h5p.authorcommentsdescription'), optional: true, }, { name: 'contentType', type: 'text', widget: 'none', }, { name: 'defaultLanguage', type: 'text', widget: 'none', }, ]; return this.metadataSemantics!; } /** * Get copyright semantics. * * @return Semantics. */ getCopyrightSemantics(): CoreH5PSemantics { if (this.copyrightSemantics) { return this.copyrightSemantics; } const ccVersions = this.getCCVersions(); this.copyrightSemantics = { name: 'copyright', type: 'group', label: Translate.instant('core.h5p.copyrightinfo'), fields: [ { name: 'title', type: 'text', label: Translate.instant('core.h5p.title'), placeholder: 'La Gioconda', optional: true, }, { name: 'author', type: 'text', label: Translate.instant('core.h5p.author'), placeholder: 'Leonardo da Vinci', optional: true, }, { name: 'year', type: 'text', label: Translate.instant('core.h5p.years'), placeholder: '1503 - 1517', optional: true, }, { name: 'source', type: 'text', label: Translate.instant('core.h5p.source'), placeholder: 'http://en.wikipedia.org/wiki/Mona_Lisa', optional: true, regexp: { pattern: '^http[s]?://.+', modifiers: 'i', }, }, { name: 'license', type: 'select', label: Translate.instant('core.h5p.license'), default: 'U', options: [ { value: 'U', label: Translate.instant('core.h5p.undisclosed'), }, { value: 'CC BY', label: Translate.instant('core.h5p.ccattribution'), versions: ccVersions, }, { value: 'CC BY-SA', label: Translate.instant('core.h5p.ccattributionsa'), versions: ccVersions, }, { value: 'CC BY-ND', label: Translate.instant('core.h5p.ccattributionnd'), versions: ccVersions, }, { value: 'CC BY-NC', label: Translate.instant('core.h5p.ccattributionnc'), versions: ccVersions, }, { value: 'CC BY-NC-SA', label: Translate.instant('core.h5p.ccattributionncsa'), versions: ccVersions, }, { value: 'CC BY-NC-ND', label: Translate.instant('core.h5p.ccattributionncnd'), versions: ccVersions, }, { value: 'GNU GPL', label: Translate.instant('core.h5p.licenseGPL'), versions: [ { value: 'v3', label: Translate.instant('core.h5p.licenseV3'), }, { value: 'v2', label: Translate.instant('core.h5p.licenseV2'), }, { value: 'v1', label: Translate.instant('core.h5p.licenseV1'), }, ], }, { value: 'PD', label: Translate.instant('core.h5p.pd'), versions: [ { value: '-', label: '-', }, { value: 'CC0 1.0', label: Translate.instant('core.h5p.licenseCC010U'), }, { value: 'CC PDM', label: Translate.instant('core.h5p.pdm'), }, ], }, { value: 'C', label: Translate.instant('core.h5p.copyrightstring'), }, ], }, { name: 'version', type: 'select', label: Translate.instant('core.h5p.licenseversion'), options: [], }, ], }; return this.copyrightSemantics!; } /** * Get CC versions for semantics. * * @return CC versions. */ protected getCCVersions(): VersionSemantics[] { return [ { value: '4.0', label: Translate.instant('core.h5p.licenseCC40'), }, { value: '3.0', label: Translate.instant('core.h5p.licenseCC30'), }, { value: '2.5', label: Translate.instant('core.h5p.licenseCC25'), }, { value: '2.0', label: Translate.instant('core.h5p.licenseCC20'), }, { value: '1.0', label: Translate.instant('core.h5p.licenseCC10'), }, ]; } } /** * Semantics of each field type. More info in https://h5p.org/semantics */ export type CoreH5PSemantics = { type?: string; name?: string; label?: string; description?: string; optional?: boolean; default?: string; importance?: 'low' | 'medium' | 'high'; common?: boolean; widget?: string; widgets?: { name: string; label: string; }[]; field?: CoreH5PSemantics; fields?: CoreH5PSemantics[]; maxLength?: number; regexp?: { pattern: string; modifiers: string; }; enterMode?: 'p' | 'div'; tags?: string[]; font?: { size?: unknown; family?: unknown; color?: unknown; background?: unknown; spacing?: unknown; height?: unknown; }; min?: number; max?: number; step?: number; decimals?: number; entity?: string; isSubContent?: boolean; expanded?: boolean; options?: (string | OptionSemantics)[]; important?: { description: string; example: string; }; multiple?: boolean; extraAttributes?: string[]; placeholder?: string; }; type OptionSemantics = { value?: string; label?: string; type?: string; options?: OptionSemantics[]; versions?: VersionSemantics[]; }; type VersionSemantics = { value: string; label: string; }; /** * File like object, such as video, image, audio and file. */ type FileLike = { path: string; mime?: string; width?: number | string; height?: number | string; codecs?: string; bitrate?: number | string; quality?: { level?: string | number; label?: string; }; copyright?: unknown; }; /** * Library type. */ type LibraryType = { library: string; params: unknown; metadata?: unknown; subContentId?: string; };
the_stack
import * as React from 'react' import type { RouteComponentProps } from 'react-router' import { Form, Field } from 'react-final-form' import styled from '@emotion/styled' import { FieldArray } from 'react-final-form-arrays' import arrayMutators from 'final-form-arrays' import createDecorator from 'final-form-calculate' import type { IHowtoFormInput } from 'src/models/howto.models' import type { UploadedFile } from 'src/pages/common/UploadedFile/UploadedFile' import { SelectField } from 'src/components/Form/Select.field' import { HowtoStep } from './HowtoStep.form' import { Button, FieldTextarea, FieldInput } from 'oa-components' import type { HowtoStore } from 'src/stores/Howto/howto.store' import { Heading, Card, Flex, Box, Text } from 'theme-ui' import { TagsSelectField } from 'src/components/Form/TagsSelect.field' import { ImageInputField } from 'src/components/Form/ImageInput.field' import { FileInputField } from 'src/components/Form/FileInput.field' import { motion, AnimatePresence } from 'framer-motion' import { inject, observer } from 'mobx-react' import { stripSpecialCharacters } from 'src/utils/helpers' import { PostingGuidelines } from './PostingGuidelines' import theme from 'src/themes/styled.theme' import { DIFFICULTY_OPTIONS, TIME_OPTIONS } from './FormSettings' import { FileInfo } from 'src/components/FileInfo/FileInfo' import { HowToSubmitStatus } from './SubmitStatus' import { required, validateUrlAcceptEmpty } from 'src/utils/validators' import ElWithBeforeIcon from 'src/components/ElWithBeforeIcon' import IconHeaderHowto from 'src/assets/images/header-section/howto-header-icon.svg' import { COMPARISONS } from 'src/utils/comparisons' import { UnsavedChangesDialog } from 'src/components/Form/UnsavedChangesDialog' import { logger } from 'src/logger' import { HOWTO_MAX_LENGTH, HOWTO_TITLE_MAX_LENGTH } from '../../constants' import { CategoriesSelect } from 'src/pages/Howto/Category/CategoriesSelect' import { AuthWrapper } from 'src/components/Auth/AuthWrapper' const MAX_LINK_LENGTH = 2000 interface IState { formSaved: boolean _toDocsList: boolean showSubmitModal?: boolean editCoverImg?: boolean fileEditMode?: boolean showInvalidFileWarning: boolean } interface IProps extends RouteComponentProps<any> { formValues: any parentType: 'create' | 'edit' } interface IInjectedProps extends IProps { howtoStore: HowtoStore } const AnimationContainer = (props: any) => { const variants = { pre: { opacity: 0, }, enter: { opacity: 1, duration: 0.2, display: 'block', }, post: { display: 'none', duration: 0.2, top: '-100%', }, } return ( <motion.div layout initial="pre" animate="enter" exit="post" variants={variants} > {props.children} </motion.div> ) } const FormContainer = styled.form` width: 100%; ` const Label = styled.label` font-size: ${theme.fontSizes[2] + 'px'}; margin-bottom: ${theme.space[2] + 'px'}; display: block; ` @inject('howtoStore') @observer export class HowtoForm extends React.PureComponent<IProps, IState> { isDraft = false uploadRefs: { [key: string]: UploadedFile | null } = {} formContainerRef = React.createRef<HTMLElement>() constructor(props: any) { super(props) this.state = { formSaved: false, _toDocsList: false, editCoverImg: false, fileEditMode: false, showSubmitModal: false, showInvalidFileWarning: false, } this.isDraft = props.moderation === 'draft' } /** When submitting from outside the form dispatch an event from the form container ref to trigger validation */ private trySubmitForm = (draft: boolean) => { this.isDraft = draft const formContainerRef = this.formContainerRef.current // dispatch submit from the element if (formContainerRef) { // https://github.com/final-form/react-final-form/issues/878 formContainerRef.dispatchEvent( new Event('submit', { cancelable: true, bubbles: true }), ) } } public checkFilesValid = (formValues: IHowtoFormInput) => { if (formValues.fileLink && formValues.files.length > 0) { this.setState({ showInvalidFileWarning: true }) return false } else { this.setState({ showInvalidFileWarning: false }) return true } } public onSubmit = async (formValues: IHowtoFormInput) => { if (!this.checkFilesValid(formValues)) { return } this.setState({ showSubmitModal: true }) formValues.moderation = this.isDraft ? 'draft' : 'awaiting-moderation' logger.debug('submitting form', formValues) await this.store.uploadHowTo(formValues) } get injected() { return this.props as IInjectedProps } get store() { return this.injected.howtoStore } public validateTitle = async (value: any) => { const originalId = this.props.parentType === 'edit' ? this.props.formValues._id : undefined return this.store.validateTitleForSlug(value, 'howtos', originalId) } // automatically generate the slug when the title changes private calculatedFields = createDecorator({ field: 'title', updates: { slug: (title) => stripSpecialCharacters(title).toLowerCase(), }, }) public render() { const { formValues, parentType } = this.props const { fileEditMode, showSubmitModal } = this.state return ( <> {showSubmitModal && ( <HowToSubmitStatus {...this.props} onClose={() => { this.setState({ showSubmitModal: false }) this.injected.howtoStore.resetUploadStatus() }} /> )} <Form onSubmit={(v) => { this.onSubmit(v as IHowtoFormInput) }} initialValues={formValues} mutators={{ ...arrayMutators, }} validateOnBlur decorators={[this.calculatedFields]} render={({ submitting, handleSubmit }) => { return ( <Flex mx={-2} bg={'inherit'} sx={{ flexWrap: 'wrap' }}> <UnsavedChangesDialog uploadComplete={this.store.uploadStatus.Complete} /> <Flex bg="inherit" px={2} sx={{ width: ['100%', '100%', `${(2 / 3) * 100}%`] }} mt={4} > <FormContainer ref={this.formContainerRef as any} id="howtoForm" onSubmit={handleSubmit} > {/* How To Info */} <Flex sx={{ flexDirection: 'column' }}> <Card bg={theme.colors.softblue}> <Flex px={3} py={2} sx={{ alignItems: 'center' }}> <Heading> {this.props.parentType === 'create' ? ( <span>Create</span> ) : ( <span>Edit</span> )}{' '} a How-To </Heading> <Box ml="15px"> <ElWithBeforeIcon IconUrl={IconHeaderHowto} height="20px" /> </Box> </Flex> </Card> <Box sx={{ mt: '20px', display: ['block', 'block', 'none'] }} > <PostingGuidelines /> </Box> <Card mt={3}> <Flex p={4} sx={{ flexWrap: 'wrap', flexDirection: 'column' }} > {/* Left Side */} <Heading variant="small" mb={3}> Intro </Heading> <Flex mx={-2} sx={{ flexDirection: ['column', 'column', 'row'] }} > <Flex px={2} sx={{ flexDirection: 'column', flex: [1, 1, 4] }} > <Flex sx={{ flexDirection: 'column' }} mb={3}> <Label htmlFor="title"> Title of your How-to * </Label> <Field id="title" name="title" data-cy="intro-title" validateFields={[]} validate={this.validateTitle} isEqual={COMPARISONS.textInput} modifiers={{ capitalize: true }} component={FieldInput} maxLength={HOWTO_TITLE_MAX_LENGTH} placeholder={`Make a chair from... (max ${HOWTO_TITLE_MAX_LENGTH} characters)`} /> </Flex> <AuthWrapper roleRequired="beta-tester"> <Flex sx={{ flexDirection: 'column' }} mb={3}> <Label>Category *</Label> <Field name="category" render={({ input, ...rest }) => ( <CategoriesSelect {...rest} onChange={(category) => input.onChange(category) } value={input.value} styleVariant="selector" placeholder="Select one category" /> )} /> </Flex> </AuthWrapper> <Flex sx={{ flexDirection: 'column' }} mb={3}> <Label>Select tags for your How-to*</Label> <Field name="tags" component={TagsSelectField} category="how-to" isEqual={COMPARISONS.tags} /> </Flex> <Flex sx={{ flexDirection: 'column' }} mb={3}> <Label htmlFor="time"> How long does it take? * </Label> <Field id="time" name="time" validate={required} validateFields={[]} isEqual={COMPARISONS.textInput} options={TIME_OPTIONS} component={SelectField} data-cy="time-select" placeholder="How much time?" /> </Flex> <Flex sx={{ flexDirection: 'column' }} mb={3}> <Label htmlFor="difficulty_level"> Difficulty level? * </Label> <Field px={1} id="difficulty_level" name="difficulty_level" data-cy="difficulty-select" validate={required} validateFields={[]} isEqual={COMPARISONS.textInput} component={SelectField} options={DIFFICULTY_OPTIONS} placeholder="How hard is it?" /> </Flex> <Flex sx={{ flexDirection: 'column' }} mb={3}> <Label htmlFor="description"> Short description of your How-to * </Label> <Field id="description" name="description" data-cy="intro-description" validate={required} validateFields={[]} modifiers={{ capitalize: true }} isEqual={COMPARISONS.textInput} component={FieldTextarea} style={{ resize: 'none', flex: 1, minHeight: '150px', }} maxLength={HOWTO_MAX_LENGTH} placeholder="Introduction to your How-To (max 400 characters)" /> </Flex> <Label htmlFor="description"> Do you have supporting file to help others replicate your How-to? </Label> <Flex sx={{ flexDirection: 'column' }} mb={[4, 4, 0]} > {formValues.files.length !== 0 && parentType === 'edit' && !fileEditMode ? ( <Flex sx={{ flexDirection: 'column', alignItems: 'center', }} > {formValues.files.map((file) => ( <FileInfo allowDownload file={file} key={file.name} /> ))} <Button variant={'tertiary'} icon="delete" onClick={() => this.setState({ fileEditMode: !this.state.fileEditMode, }) } > Re-upload files (this will delete the existing ones) </Button> </Flex> ) : ( <> <Flex sx={{ flexDirection: 'column', }} mb={3} > <Label htmlFor="file-download-link" style={{ fontSize: '12px' }} > Add a download link </Label> <Field id="fileLink" name="fileLink" data-cy="fileLink" component={FieldInput} placeholder="Link to Gdrive, Dropbox, Grabcad etc" isEqual={COMPARISONS.textInput} maxLength={MAX_LINK_LENGTH} validate={validateUrlAcceptEmpty} validateFields={[]} /> </Flex> <Flex sx={{ flexDirection: 'column', }} > <Label htmlFor="files" style={{ fontSize: '12px' }} > Or upload your files here </Label> <Field name="files" component={FileInputField} /> </Flex> </> )} </Flex> </Flex> {/* Right side */} <Flex px={2} sx={{ flexDirection: 'column', flex: [1, 1, 3] }} data-cy={'intro-cover'} > <Label htmlFor="cover_image">Cover image *</Label> <Box sx={{ height: '230px' }}> <Field id="cover_image" name="cover_image" validate={required} isEqual={COMPARISONS.image} component={ImageInputField} /> </Box> <Text color={'grey'} mt={4} sx={{ fontSize: 1 }}> This image should be landscape. We advise 1280x960px </Text> </Flex> </Flex> </Flex> </Card> {/* Steps Info */} <FieldArray name="steps" isEqual={COMPARISONS.step}> {({ fields }) => ( <> <AnimatePresence> {fields.map((name, index: number) => ( <AnimationContainer key={fields.value[index]._animationKey} > <HowtoStep key={fields.value[index]._animationKey} step={name} index={index} moveStep={(from, to) => { if (to !== fields.length) { fields.move(from, to) } }} images={fields.value[index].images} onDelete={(fieldIndex: number) => { fields.remove(fieldIndex) }} /> </AnimationContainer> ))} </AnimatePresence> <Flex> <Button icon={'add'} data-cy={'add-step'} mx="auto" mt={[10, 10, 20]} mb={[5, 5, 20]} variant="secondary" medium onClick={() => { fields.push({ title: '', text: '', images: [], // HACK - need unique key, this is a rough method to generate form random numbers _animationKey: `unique${Math.random() .toString(36) .substring(7)}`, }) }} > Add step </Button> </Flex> </> )} </FieldArray> </Flex> </FormContainer> </Flex> {/* post guidelines container */} <Flex sx={{ flexDirection: 'column', width: [1, 1, 1 / 3], height: '100%', }} bg="inherit" px={2} mt={[0, 0, 4]} > <Box sx={{ position: ['relative', 'relative', 'fixed'], maxWidth: ['inherit', 'inherit', '400px'], }} > <Box sx={{ display: ['none', 'none', 'block'] }}> <PostingGuidelines /> </Box> <Button data-cy={'draft'} onClick={() => this.trySubmitForm(true)} mt={[0, 0, 3]} variant="secondary" type="submit" disabled={submitting} sx={{ width: '100%', display: 'block' }} > {formValues.moderation !== 'draft' ? ( <span>Save to draft</span> ) : ( <span>Revert to draft</span> )}{' '} </Button> <Button data-cy={'submit'} onClick={() => this.trySubmitForm(false)} mt={3} variant="primary" type="submit" disabled={submitting} sx={{ width: '100%', mb: ['40px', '40px', 0] }} > <span>Publish</span> </Button> </Box> </Flex> </Flex> ) }} /> </> ) } }
the_stack
import * as React from 'react'; import Tagify = require('@yaireo/tagify'); import { BaseTagData, ChangeEventData, EventData, TagifySettings } from '@yaireo/tagify'; import Tags = require('@yaireo/tagify/dist/react.tagify'); import { MixedTags, TagifyTagsReactProps } from '@yaireo/tagify/dist/react.tagify'; // Tests the minimal required attribute for the Tags component export function TestTagsMinimal(): React.ReactElement { return (<div> <Tags /> </div>); } // Tests the autoFocus prop of the Tags component export function TestTagsAutoFocus(): React.ReactElement { return (<div> <Tags autoFocus={true} /> <Tags autoFocus={false} /> </div>); } // Tests the children prop of the Tags component export function TestTagsChildren(): React.ReactElement { return (<div> <Tags>a,b,c</Tags> <Tags>{["a", "b", "c"]}</Tags> { // $ExpectError <Tags><span>a</span></Tags> } { // $ExpectError <Tags>{{ foo: 'bar' }}</Tags> } </div>); } // Tests the className prop of the Tags component export function TestTagsClassName(): React.ReactElement { return (<div> <Tags className='my-awesome-tagify' /> </div>); } // Tests the defaultValue prop of the Tags component export function TestTagsDefaultValue(): React.ReactElement { return (<div> <Tags defaultValue="a,b,c" /> <Tags defaultValue={['a', 'b', 'c']} /> <Tags defaultValue={[{ value: 'a' }, { value: 'b' }, { value: 'c' }]} /> </div>); } // Tests the possible values for the InputMode prop export function TestTagsInputMode(): React.ReactElement { return (<div> <Tags InputMode='input' /> <Tags InputMode='textarea' /> { // $ExpectError <Tags InputMode='select' /> } </div>); } // Tests the loading prop of the Tags component export function TestTagsLoading(): React.ReactElement { return (<div> <Tags loading={true} /> <Tags loading={false} /> </div>); } // Tests the name prop of the Tags component export function TestTagsName(): React.ReactElement { return (<div> <Tags name='emails' /> </div>); } // Tests the on... callback props of the Tags component export function TestTagsOnCallbacks(): React.ReactElement { return (<div> <Tags onAdd={e => { // $ExpectType AddEventData<TagData> e.detail; }} onBlur={e => { // $ExpectType BlurEventData<TagData> e.detail; }} onChange={e => { // $ExpectType ChangeEventData<TagData> e.detail; }} onClick={e => { // $ExpectType ClickEventData<TagData> e.detail; }} onDropdownHide={e => { // $ExpectType DropDownHideEventData<TagData> e.detail; }} onDropdownNoMatch={e => { // $ExpectType DropDownNoMatchEventData<TagData> e.detail; }} onDropdownScroll={e => { // $ExpectType DropDownScrollEventData<TagData> e.detail; }} onDropdownSelect={e => { // $ExpectType DropDownSelectEventData<TagData> e.detail; }} onDropdownShow={e => { // $ExpectType DropDownShowEventData<TagData> e.detail; }} onDropdownUpdated={e => { // $ExpectType DropDownUpdatedEventData<TagData> e.detail; }} onEditBeforeUpdate={e => { // $ExpectType EditBeforeUpdateEventData<TagData> e.detail; }} onEditInput={e => { // $ExpectType EditInputEventData<TagData> e.detail; }} onEditKeydown={e => { // $ExpectType EditKeydownEventData<TagData> e.detail; }} onEditStart={e => { // $ExpectType EditStartEventData<TagData> e.detail; }} onEditUpdated={e => { // $ExpectType EditUpdatedEventData<TagData> e.detail; }} onFocus={e => { // $ExpectType FocusEventData<TagData> e.detail; }} onInput={e => { // $ExpectType InputEventData<TagData> e.detail; }} onInvalid={e => { // $ExpectType InvalidTagEventData<TagData> e.detail; }} onKeydown={e => { // $ExpectType KeydownEventData<TagData> e.detail; }} onRemove={e => { // $ExpectType RemoveEventData<TagData> e.detail; }} /> </div>); } // Tests the placeholder prop of the Tags component export function TestTagsPlaceholder(): React.ReactElement { return (<div> <Tags placeholder='Enter more emails here...' /> </div>); } // Tests the readOnly prop of the Tags component export function TestTagsReadOnly(): React.ReactElement { return (<div> <Tags readOnly={false} /> <Tags readOnly={true} /> </div>); } // Tests the settings prop of the Tags component export function TestTagsSettings(): React.ReactElement { return (<div> <Tags showDropdown={false} /> <Tags showDropdown={true} /> <Tags showDropdown="a,b" /> </div>); } // Tests the showDropdown prop of the Tags component declare const settings: TagifySettings; export function TestTagsShowDropdown(): React.ReactElement { return (<div> <Tags settings={{}} /> <Tags settings={{ maxTags: 10, pattern: /\w+/ }} /> <Tags settings={settings} /> </div>); } // Tests that a reference to the tagify instance can be obtained via the tagifyRef prop export function TestTagsTagifyRef(): React.ReactElement { const ref = React.useRef<Tagify>(); return (<div> <Tags tagifyRef={ref} /> </div>); } // Tests that the value prop can be passed to tagify // Can be either a string with tags, an array of string, or an array of tag data export function TestTagsValue(): React.ReactElement { return (<div> <Tags value='a,b,c' /> <Tags value={['a', 'b', 'c']} /> <Tags value={[{ value: 'a' }, { value: 'b' }, { value: 'c' }]} /> </div>); } // Tests the whitelist prop of the Tags component // Can be either a string of tag values, or an array of tag data export function TestTagsWhitelist(): React.ReactElement { return (<div> <Tags whitelist={['a', 'b', 'c']} /> <Tags whitelist={[{ value: 'a' }, { value: 'b' }, { value: 'c' }]} /> </div>); } // Tests that the Tags component can be parameterized with a type param that // corresponds to the type of tag data used by the component interface ValueTagData extends BaseTagData { name: string; age: number; } export function TestTagsTypeParam(): React.ReactElement { const John: ValueTagData = { age: 12, name: 'John', value: 'p123' }; const Mary = { age: 18, name: 'Mary', value: 'p843' }; const Odo = { age: 341, name: 'Odo', value: 'p354' }; const InvalidTag: Partial<ValueTagData> = { name: '', value: '' }; return (<div> <Tags<ValueTagData> defaultValue={[John]} onAdd={e => { // $ExpectType ValueTagData[] e.detail.tagify.value; }} onBlur={e => { // $ExpectType ValueTagData[] e.detail.tagify.value; }} onChange={e => { // $ExpectType ValueTagData[] e.detail.tagify.value; }} onClick={e => { // $ExpectType ValueTagData[] e.detail.tagify.value; }} onDropdownHide={e => { // $ExpectType DropDownHideEventData<ValueTagData> e.detail; }} onDropdownNoMatch={e => { // $ExpectType DropDownNoMatchEventData<ValueTagData> e.detail; }} onDropdownScroll={e => { // $ExpectType DropDownScrollEventData<ValueTagData> e.detail; }} onDropdownSelect={e => { // $ExpectType DropDownSelectEventData<ValueTagData> e.detail; }} onDropdownShow={e => { // $ExpectType DropDownShowEventData<ValueTagData> e.detail; }} onDropdownUpdated={e => { // $ExpectType DropDownUpdatedEventData<ValueTagData> e.detail; }} onEditBeforeUpdate={e => { // $ExpectType EditBeforeUpdateEventData<ValueTagData> e.detail; }} onEditInput={e => { // $ExpectType EditInputEventData<ValueTagData> e.detail; }} onEditKeydown={e => { // $ExpectType EditKeydownEventData<ValueTagData> e.detail; }} onEditStart={e => { // $ExpectType EditStartEventData<ValueTagData> e.detail; }} onEditUpdated={e => { // $ExpectType EditUpdatedEventData<ValueTagData> e.detail; }} onFocus={e => { // $ExpectType ValueTagData[] e.detail.tagify.value; }} onInput={e => { // $ExpectType ValueTagData[] e.detail.tagify.value; }} onInvalid={e => { // $ExpectType ValueTagData[] e.detail.tagify.value; }} onKeydown={e => { // $ExpectType ValueTagData[] e.detail.tagify.value; }} onRemove={e => { // $ExpectType ValueTagData[] e.detail.tagify.value; }} value={[John]} whitelist={[John, Mary, Odo]} /> { // $ExpectError <Tags<ValueTagData> defaultValue={[InvalidTag]} /> } { // $ExpectError <Tags<ValueTagData> value={[InvalidTag]} /> } { // $ExpectError <Tags<ValueTagData> whitelist={[InvalidTag]} /> } </div>); } // Tests the minimal required attribute for the MixedTags component export function TestMixedTagsMinimal(): React.ReactElement { return (<div> <MixedTags /> </div>); } // Tests the autoFocus prop of the MixedTags component export function TestMixedTagsAutoFocus(): React.ReactElement { return (<div> <MixedTags autoFocus={true} /> <MixedTags autoFocus={false} /> </div>); } // Tests the children prop of the MixedTags component export function TestMixedTagsChildren(): React.ReactElement { return (<div> <Tags>a,b,c</Tags> <Tags>{["a", "b", "c"]}</Tags> { // $ExpectError <Tags><span>a</span></Tags> } { // $ExpectError <Tags>{{ foo: 'bar' }}</Tags> } </div>); } // Tests the className prop of the MixedTags component export function TestMixedTagsClassName(): React.ReactElement { return (<div> <MixedTags className='my-awesome-tagify' /> </div>); } // Tests the defaultValue prop of the MixedTags component export function TestMixedTagsDefaultValue(): React.ReactElement { return (<div> <MixedTags defaultValue="a,b,c" /> <MixedTags defaultValue={['a', 'b', 'c']} /> <MixedTags defaultValue={[{ value: 'a' }, { value: 'b' }, { value: 'c' }]} /> </div>); } // Tests the loading prop of the MixedTags component export function TestMixedTagsLoading(): React.ReactElement { return (<div> <MixedTags loading={true} /> <MixedTags loading={false} /> </div>); } // Tests the name prop of the MixedTags component export function TestMixedTagsName(): React.ReactElement { return (<div> <MixedTags name='emails' /> </div>); } // Tests the on... callback props of the MixedTags component export function TestMixedTagsOnCallbacks(): React.ReactElement { return (<div> <Tags onAdd={e => { // // $ExpectType AddEventData<TagData> e.detail; }} onBlur={e => { // // $ExpectType BlurEventData<TagData> e.detail; }} onChange={e => { // // $ExpectType ChangeEventData<TagData> e.detail; }} onClick={e => { // // $ExpectType ClickEventData<TagData> e.detail; }} onDropdownHide={e => { // $ExpectType DropDownHideEventData<TagData> e.detail; }} onDropdownNoMatch={e => { // $ExpectType DropDownNoMatchEventData<TagData> e.detail; }} onDropdownScroll={e => { // $ExpectType DropDownScrollEventData<TagData> e.detail; }} onDropdownSelect={e => { // $ExpectType DropDownSelectEventData<TagData> e.detail; }} onDropdownShow={e => { // $ExpectType DropDownShowEventData<TagData> e.detail; }} onDropdownUpdated={e => { // $ExpectType DropDownUpdatedEventData<TagData> e.detail; }} onEditBeforeUpdate={e => { // $ExpectType EditBeforeUpdateEventData<TagData> e.detail; }} onEditInput={e => { // $ExpectType EditInputEventData<TagData> e.detail; }} onEditKeydown={e => { // $ExpectType EditKeydownEventData<TagData> e.detail; }} onEditStart={e => { // $ExpectType EditStartEventData<TagData> e.detail; }} onEditUpdated={e => { // $ExpectType EditUpdatedEventData<TagData> e.detail; }} onFocus={e => { // // $ExpectType FocusEventData<TagData> e.detail; }} onInput={e => { // // $ExpectType InputEventData<TagData> e.detail; }} onInvalid={e => { // // $ExpectType InvalidTagEventData<TagData> e.detail; }} onKeydown={e => { // // $ExpectType KeydownEventData<TagData> e.detail; }} onRemove={e => { // // $ExpectType RemoveEventData<TagData> e.detail; }} /> </div>); } // Tests the placeholder prop of the MixedTags component export function TestMixedTagsPlaceholder(): React.ReactElement { return (<div> <MixedTags placeholder='Enter more emails here...' /> </div>); } // Tests the readOnly prop of the MixedTags component export function TestMixedTagsReadOnly(): React.ReactElement { return (<div> <MixedTags readOnly={false} /> <MixedTags readOnly={true} /> </div>); } // Tests the settings prop of the MixedTags component export function TestMixedTagsSettings(): React.ReactElement { return (<div> <MixedTags showDropdown={false} /> <MixedTags showDropdown={true} /> <MixedTags showDropdown="a,b" /> </div>); } // Tests the showDropdown prop of the MixedTags component export function TestMixedTagsShowDropdown(): React.ReactElement { return (<div> <MixedTags settings={{}} /> <MixedTags settings={{ maxTags: 10, pattern: /\w+/ }} /> <MixedTags settings={settings} /> </div>); } // Tests that a reference to the tagify instance can be obtained via the tagifyRef prop export function TestMixedTagsTagifyRef(): React.ReactElement { const ref = React.useRef<Tagify>(); return (<div> <MixedTags tagifyRef={ref} /> </div>); } // Tests that the value prop can be passed to tagify // Can be either a string with tags, an array of string, or an array of tag data export function TestMixedTagsValue(): React.ReactElement { return (<div> <MixedTags value='a,b,c' /> <MixedTags value={['a', 'b', 'c']} /> <MixedTags value={[{ value: 'a' }, { value: 'b' }, { value: 'c' }]} /> </div>); } // Tests the whitelist prop of the MixedTags component // Can be either a string of tag values, or an array of tag data export function TestMixedTagsWhitelist(): React.ReactElement { return (<div> <MixedTags whitelist={['a', 'b', 'c']} /> <MixedTags whitelist={[{ value: 'a' }, { value: 'b' }, { value: 'c' }]} /> </div>); } // Tests that the MixedTags component can be parameterized with a type param that // corresponds to the type of tag data used by the component interface ValueTagData extends BaseTagData { name: string; age: number; } export function TestMixedTagsTypeParam(): React.ReactElement { const John: ValueTagData = { age: 12, name: 'John', value: 'p123' }; const Mary = { age: 18, name: 'Mary', value: 'p843' }; const Odo = { age: 341, name: 'Odo', value: 'p354' }; const InvalidTag: Partial<ValueTagData> = { name: '', value: '' }; return (<div> <Tags<ValueTagData> onAdd={e => { // // $ExpectType ValueTagData[] e.detail.tagify.value; }} onBlur={e => { // // $ExpectType ValueTagData[] e.detail.tagify.value; }} onChange={e => { // // $ExpectType ValueTagData[] e.detail.tagify.value; }} onClick={e => { // // $ExpectType ValueTagData[] e.detail.tagify.value; }} onDropdownHide={e => { // $ExpectType DropDownHideEventData<ValueTagData> e.detail; }} onDropdownNoMatch={e => { // $ExpectType DropDownNoMatchEventData<ValueTagData> e.detail; }} onDropdownScroll={e => { // $ExpectType DropDownScrollEventData<ValueTagData> e.detail; }} onDropdownSelect={e => { // $ExpectType DropDownSelectEventData<ValueTagData> e.detail; }} onDropdownShow={e => { // $ExpectType DropDownShowEventData<ValueTagData> e.detail; }} onDropdownUpdated={e => { // $ExpectType DropDownUpdatedEventData<ValueTagData> e.detail; }} onEditBeforeUpdate={e => { // $ExpectType EditBeforeUpdateEventData<ValueTagData> e.detail; }} onEditInput={e => { // $ExpectType EditInputEventData<ValueTagData> e.detail; }} onEditKeydown={e => { // $ExpectType EditKeydownEventData<ValueTagData> e.detail; }} onEditStart={e => { // $ExpectType EditStartEventData<ValueTagData> e.detail; }} onEditUpdated={e => { // $ExpectType EditUpdatedEventData<ValueTagData> e.detail; }} onFocus={e => { // // $ExpectType ValueTagData[] e.detail.tagify.value; }} onInput={e => { // // $ExpectType ValueTagData[] e.detail.tagify.value; }} onInvalid={e => { // // $ExpectType ValueTagData[] e.detail.tagify.value; }} onKeydown={e => { // // $ExpectType ValueTagData[] e.detail.tagify.value; }} onRemove={e => { // // $ExpectType ValueTagData[] e.detail.tagify.value; }} value={[John]} whitelist={[John, Mary, Odo]} /> { // $ExpectError <Tags<ValueTagData> value={[John]} whitelist={[InvalidTag]} /> } </div>); } // Test that InputMode cannot be specified on the MixedTags component export function TestMixedTagsNoInputMode(): React.ReactElement { return (<div> { // $ExpectError <MixedTags InputMode='textarea' /> } </div>); } // Taken from the official example for the react wrapper // https://codesandbox.io/s/tagify-react-wrapper-oempc const baseTagifySettings: TagifySettings = { blacklist: ['xxx', 'yyy', 'zzz'], maxTags: 6, // backspace: 'edit', placeholder: 'type something', dropdown: { enabled: 0 // a;ways show suggestions dropdown }, }; // this example callback is used for all Tagify events const callback = (e: CustomEvent<EventData>) => console.log(`%c ${e.type}: `, 'background:#222; color:#bada55', e.detail); // callbacks props (for this demo, the same callback reference is assigned to every event type) const tagifyCallbacks: TagifySettings['callbacks'] = { add: callback, remove: callback, input: callback, invalid: callback, click: callback, keydown: callback, focus: callback, blur: callback, 'edit:input': callback, 'edit:updated': callback, 'edit:start': callback, 'edit:keydown': callback, 'dropdown:show': callback, 'dropdown:hide': callback, 'dropdown:select': callback, }; // this is an example React component which implements Tagify within // itself. This example is a bit elaborate, to demonstrate what's possible. declare function getWhitelistFromServer(duration: number): Promise<string>; declare function getValue(duration: number): Promise<string>; export const CrazyTags = () => { const tagifyRef = React.useRef<Tagify>(); // just a name I made up for allowing dynamic changes for tagify settings on this component const [tagifySettings, setTagifySettings] = React.useState<TagifySettings>({}); const [tagifyProps, setTagifyProps] = React.useState<TagifyTagsReactProps>({}); // on component mount React.useEffect(() => { setTagifyProps({ loading: true }); getWhitelistFromServer(2000).then((response) => { setTagifyProps((lastProps) => ({ ...lastProps, whitelist: response.split(','), showDropdown: 'a', loading: false })); }); // simulate setting tags value via server request getValue(3000).then((response) => setTagifyProps((lastProps) => ({ ...lastProps, value: response })) ); // simulated state change where some tags were deleted setTimeout( () => setTagifyProps((lastProps) => ({ ...lastProps, value: ['abc'], showDropdown: false })), 5000 ); }, []); // merged tagify settings (static & dynamic) const settings: TagifySettings = { ...baseTagifySettings, ...tagifySettings, callbacks: tagifyCallbacks }; const onChange = React.useCallback((e: CustomEvent<ChangeEventData>) => { if (e.target instanceof HTMLInputElement) { console.log('CHANGED:', e.target.value); } }, []); // access Tagify internal methods example: const clearAll = () => { tagifyRef.current && tagifyRef.current.removeAllTags(); }; return ( <> <h2> <em>Crazy</em> Tags: </h2> <p> Wait a <em>few seconds</em> to see things happen. <br /> <small> <em>(Carefully examine the source-code)</em> </small> </p> <button className='clearAllBtn' onClick={clearAll}> Clear All </button> <Tags tagifyRef={tagifyRef} settings={settings} value='a,b,c' autoFocus={true} {...tagifyProps} onChange={onChange} /> <h2>Readonly tags:</h2> <Tags value='foo,bar' readOnly /> </> ); };
the_stack
import * as React from 'react'; import { useEffect } from 'react'; import { render, cleanup, fireEvent, waitFor } from '@testing-library/react'; import { useEffectReducer, EffectReducer, EffectEntity, InitialEffectStateGetter, } from '../src'; // have to add this because someone made a breaking change somewhere... class MutationObserver { public observe() {} public disconnect() {} } (global as any).MutationObserver = MutationObserver; describe('useEffectReducer', () => { afterEach(cleanup); it('basic example', async () => { interface User { name: string; } type FetchState = | { status: 'idle'; user: undefined; } | { status: 'fetching'; user: User | undefined; } | { status: 'fulfilled'; user: User; }; type FetchEvent = | { type: 'FETCH'; user: string; } | { type: 'RESOLVE'; data: User; }; type FetchEffect = { type: 'fetchFromAPI'; user: string; }; const fetchEffectReducer: EffectReducer< FetchState, FetchEvent, FetchEffect > = (state, event, exec) => { switch (event.type) { case 'FETCH': exec({ type: 'fetchFromAPI', user: event.user }); return { ...state, status: 'fetching', }; case 'RESOLVE': return { status: 'fulfilled', user: event.data, }; default: return state; } }; const Fetcher = () => { const [state, dispatch] = useEffectReducer( fetchEffectReducer, { status: 'idle', user: undefined }, { fetchFromAPI(_, effect) { setTimeout(() => { dispatch({ type: 'RESOLVE', data: { name: effect.user }, }); }, 100); }, } ); return ( <div onClick={() => dispatch({ type: 'FETCH', user: '42' })} data-testid="result" > {state.user ? state.user.name : '--'} </div> ); }; const { getByTestId } = render(<Fetcher />); const resultEl = getByTestId('result'); expect(resultEl.textContent).toEqual('--'); fireEvent.click(resultEl); await waitFor(() => { expect(resultEl.textContent).toEqual('42'); }); }); it('third argument dispatch', async () => { interface User { name: string; } type FetchState = | { status: 'idle'; user: undefined; } | { status: 'fetching'; user: User | undefined; } | { status: 'fulfilled'; user: User; }; type FetchEvent = | { type: 'FETCH'; user: string; } | { type: 'RESOLVE'; data: User; }; type FetchEffect = { type: 'fetchFromAPI'; user: string; }; const fetchEffectReducer: EffectReducer< FetchState, FetchEvent, FetchEffect > = (state, event, exec) => { switch (event.type) { case 'FETCH': exec({ type: 'fetchFromAPI', user: event.user }); return { ...state, status: 'fetching', }; case 'RESOLVE': return { status: 'fulfilled', user: event.data, }; default: return state; } }; const Fetcher = () => { const [state, dispatch] = useEffectReducer( fetchEffectReducer, { status: 'idle', user: undefined }, { fetchFromAPI(_, effect, _dispatch) { setTimeout(() => { _dispatch({ type: 'RESOLVE', data: { name: effect.user }, }); }, 100); }, } ); return ( <div onClick={() => dispatch({ type: 'FETCH', user: '42' })} data-testid="result" > {state.user ? state.user.name : '--'} </div> ); }; const { getByTestId } = render(<Fetcher />); const resultEl = getByTestId('result'); expect(resultEl.textContent).toEqual('--'); fireEvent.click(resultEl); await waitFor(() => { expect(resultEl.textContent).toEqual('42'); }); }); it('handles batched dispatch calls', () => { interface ThingContext { count: number; } type ThingEvent = { type: 'INC'; }; const sideEffectCapture: any[] = []; let renderCount = 0; const Thing = () => { const [state, dispatch] = useEffectReducer<ThingContext, ThingEvent>( (state, event, exec) => { if (event.type === 'INC') { exec(s => { sideEffectCapture.push(s.count); }); return { ...state, count: state.count + 1 }; } return state; }, { count: 0 } ); // just for tracking renders renderCount++; useEffect(() => { dispatch({ type: 'INC' }); dispatch({ type: 'INC' }); dispatch({ type: 'INC' }); dispatch({ type: 'INC' }); dispatch({ type: 'INC' }); }, []); return <div data-testid="count">{state.count}</div>; }; const { getByTestId } = render(<Thing />); expect(getByTestId('count').textContent).toEqual('5'); expect(sideEffectCapture).toEqual([1, 2, 3, 4, 5]); // Should be less than number of side-effects due to batching expect(renderCount).toBeLessThan(sideEffectCapture.length); }); it('supports queueing effects during commit phase', () => { let effectCount = 0; const Thing = () => { const [hasClicked, setHasClicked] = React.useState(false); const [count, dispatch] = useEffectReducer((state, _event, exec) => { exec(() => { effectCount += 1; }); return state + 1; }, 0); React.useLayoutEffect(() => { if (hasClicked) dispatch({ type: 'foo' }); }, [hasClicked, dispatch]); function handleClick() { setHasClicked(true); dispatch({ type: 'foo' }); } return ( <> <div data-testid="count">{count}</div> <button data-testid="button" onClick={handleClick} /> </> ); }; const { getByTestId } = render(<Thing />); expect(getByTestId('count').textContent).toEqual('0'); const buttonEl = getByTestId('button'); fireEvent.click(buttonEl); expect(getByTestId('count').textContent).toEqual('2'); expect(effectCount).toEqual(2); }); it('should run cleanup when effectEntity.stop() is called', async () => { interface ThingContext { count: number; entity?: any; } type ThingEvent = | { type: 'INC'; } | { type: 'STOP' }; let started = false; let stopped = false; const Thing = () => { const [state, dispatch] = useEffectReducer<ThingContext, ThingEvent>( (state, event, exec) => { if (event.type === 'INC') { if (state.count === 0) { return { count: 1, entity: exec(() => { started = true; return () => { stopped = true; }; }), }; } return { ...state, count: state.count + 1 }; } if (event.type === 'STOP') { exec.stop(state.entity!); return state; } return state; }, { count: 0 } ); useEffect(() => { dispatch({ type: 'INC' }); dispatch({ type: 'INC' }); dispatch({ type: 'INC' }); dispatch({ type: 'INC' }); dispatch({ type: 'INC' }); setTimeout(() => { dispatch({ type: 'STOP' }); }, 10); }, []); return <div data-testid="count">{state.count}</div>; }; const { getByTestId } = render(<Thing />); expect(getByTestId('count').textContent).toEqual('5'); expect(started).toBeTruthy(); expect(stopped).toBeFalsy(); await waitFor(() => { expect(stopped).toBeTruthy(); }); }); it('should run cleanup when the component is unmounted', () => { // @ts-ignore let started = false; // @ts-ignore let stopped = false; const reducer: EffectReducer<{ status: string }, { type: 'START' }> = ( state, event, exec ) => { if (event.type === 'START') { exec(() => { started = true; return () => { stopped = true; }; }); return { status: 'started', }; } return state; }; const Thing = () => { const [state, dispatch] = useEffectReducer(reducer, { status: 'idle' }); return ( <div data-testid="status" onClick={() => { dispatch('START'); }} > {state.status} </div> ); }; const App = () => { const [hidden, setHidden] = React.useState(false); return hidden ? null : ( <div> <button data-testid="hide" onClick={() => setHidden(true)}></button> <Thing /> </div> ); }; const { getByTestId } = render(<App />); const statusEl = getByTestId('status'); const buttonEl = getByTestId('hide'); expect(statusEl.textContent).toEqual('idle'); expect(started).toBeFalsy(); fireEvent.click(statusEl); expect(started).toBeTruthy(); expect(stopped).toBeFalsy(); expect(statusEl.textContent).toEqual('started'); fireEvent.click(buttonEl); expect(stopped).toBeTruthy(); }); it('exec.replace() should replace an effect', async () => { const delayedResults: string[] = []; type TimerEvent = { type: 'START'; delayedMessage: string; }; interface TimerState { timer?: EffectEntity<TimerState, TimerEvent>; } const timerReducer: EffectReducer<TimerState, TimerEvent> = ( state, event, exec ) => { if (event.type === 'START') { return { ...state, timer: exec.replace(state.timer, () => { const id = setTimeout(() => { delayedResults.push(event.delayedMessage); }, 100); return () => { clearTimeout(id); }; }), }; } return state; }; const App = () => { const [, dispatch] = useEffectReducer(timerReducer, {}); return ( <div> <button data-testid="send-hello" onClick={() => dispatch({ type: 'START', delayedMessage: 'hello' })} ></button> <button data-testid="send-goodbye" onClick={() => dispatch({ type: 'START', delayedMessage: 'goodbye' }) } ></button> </div> ); }; const { getByTestId } = render(<App />); const helloButton = getByTestId('send-hello'); const goodbyeButton = getByTestId('send-goodbye'); fireEvent.click(helloButton); setTimeout(() => { fireEvent.click(goodbyeButton); }, 30); await waitFor(() => { // If the first timer effect isn't replaced (disposed), // delayedResults will be ['hello', 'goodbye'] expect(delayedResults).toEqual(['goodbye']); }); }); it('should allow for initial effects', async () => { interface FetchState { data: null | string; effect: EffectEntity<FetchState, FetchEvent>; } type FetchEvent = { type: 'RESOLVE'; data: string; }; type FetchEffects = | { type: 'fetchData'; data: string; } | { type: 'effect'; }; const fetchReducer: EffectReducer<FetchState, FetchEvent, FetchEffects> = ( state, event ) => { if (event.type === 'RESOLVE') { state.effect.stop(); return { ...state, data: event.data, }; } return state; }; const getInitialState: InitialEffectStateGetter< FetchState, FetchEvent, FetchEffects > = exec => { exec({ type: 'fetchData', data: 'secret' }); const effect = exec({ type: 'effect' }); return { data: null, effect }; }; //@ts-ignore let started = false; //@ts-ignore let stopped = false; const App = () => { const [state, dispatch] = useEffectReducer( fetchReducer, getInitialState, { fetchData(_, { data }) { setTimeout(() => { dispatch({ type: 'RESOLVE', data: data.toUpperCase() }); }, 20); }, effect() { started = true; return () => { stopped = true; }; }, } ); return <div data-testid="result">{state.data || '--'}</div>; }; const { getByTestId } = render(<App />); expect(started).toBeTruthy(); const result = getByTestId('result'); expect(result.textContent).toEqual('--'); await waitFor(() => { expect(result.textContent).toEqual('SECRET'); expect(stopped).toBeTruthy(); }); }); });
the_stack
module android.widget{ import ViewConfiguration = android.view.ViewConfiguration; import Interpolator = android.view.animation.Interpolator; import Resources = android.content.res.Resources; import SystemClock = android.os.SystemClock; import Log = android.util.Log; import NumberChecker = androidui.util.NumberChecker; /** * This class encapsulates scrolling with the ability to overshoot the bounds * of a scrolling operation. This class is a drop-in replacement for * {@link android.widget.Scroller} in most cases. */ export class OverScroller{ private mMode = 0; private mScrollerX:SplineOverScroller; private mScrollerY:SplineOverScroller; private mInterpolator:Interpolator; private mFlywheel = true; static DEFAULT_DURATION = 250; static SCROLL_MODE = 0; static FLING_MODE = 1; /** * Creates an OverScroller. * @param interpolator The scroll interpolator. If null, a default (viscous) interpolator will * be used. * @param flywheel If true, successive fling motions will keep on increasing scroll speed. * @hide */ constructor(interpolator?:Interpolator, flywheel=true) { this.mInterpolator = interpolator; this.mFlywheel = flywheel; this.mScrollerX = new SplineOverScroller(); this.mScrollerY = new SplineOverScroller(); } setInterpolator(interpolator:Interpolator):void { this.mInterpolator = interpolator; } /** * The amount of friction applied to flings. The default value * is {@link ViewConfiguration#getScrollFriction}. * * @param friction A scalar dimension-less value representing the coefficient of * friction. */ setFriction(friction:number) { NumberChecker.warnNotNumber(friction); this.mScrollerX.setFriction(friction); this.mScrollerY.setFriction(friction); } /** * * Returns whether the scroller has finished scrolling. * * @return True if the scroller has finished scrolling, false otherwise. */ isFinished():boolean { return this.mScrollerX.mFinished && this.mScrollerY.mFinished; } /** * Force the finished field to a particular value. Contrary to * {@link #abortAnimation()}, forcing the animation to finished * does NOT cause the scroller to move to the final x and y * position. * * @param finished The new finished value. */ forceFinished(finished:boolean) { this.mScrollerX.mFinished = this.mScrollerY.mFinished = finished; } /** * Returns the current X offset in the scroll. * * @return The new X offset as an absolute distance from the origin. */ getCurrX():number { return this.mScrollerX.mCurrentPosition; } /** * Returns the current Y offset in the scroll. * * @return The new Y offset as an absolute distance from the origin. */ getCurrY():number { return this.mScrollerY.mCurrentPosition; } /** * Returns the absolute value of the current velocity. * * @return The original velocity less the deceleration, norm of the X and Y velocity vector. */ getCurrVelocity():number { let squaredNorm = this.mScrollerX.mCurrVelocity * this.mScrollerX.mCurrVelocity; squaredNorm += this.mScrollerY.mCurrVelocity * this.mScrollerY.mCurrVelocity; return Math.sqrt(squaredNorm); } /** * Returns the start X offset in the scroll. * * @return The start X offset as an absolute distance from the origin. */ getStartX():number { return this.mScrollerX.mStart; } /** * Returns the start Y offset in the scroll. * * @return The start Y offset as an absolute distance from the origin. */ getStartY():number { return this.mScrollerY.mStart; } /** * Returns where the scroll will end. Valid only for "fling" scrolls. * * @return The final X offset as an absolute distance from the origin. */ getFinalX():number { return this.mScrollerX.mFinal; } /** * Returns where the scroll will end. Valid only for "fling" scrolls. * * @return The final Y offset as an absolute distance from the origin. */ getFinalY():number { return this.mScrollerY.mFinal; } /** * Returns how long the scroll event will take, in milliseconds. * * @return The duration of the scroll in milliseconds. * * @hide Pending removal once nothing depends on it * @deprecated OverScrollers don't necessarily have a fixed duration. * This function will lie to the best of its ability. */ getDuration():number { return Math.max(this.mScrollerX.mDuration, this.mScrollerY.mDuration); } //extendDuration(extend:number) { // this.mScrollerX.extendDuration(extend); // this.mScrollerY.extendDuration(extend); //} //setFinalX(newX:number) { // this.mScrollerX.setFinalPosition(newX); //} //setFinalY(newY:number) { // this.mScrollerY.setFinalPosition(newY); //} /** * Call this when you want to know the new location. If it returns true, the * animation is not yet finished. */ computeScrollOffset():boolean { if (this.isFinished()) { return false; } switch (this.mMode) { case OverScroller.SCROLL_MODE: let time = SystemClock.uptimeMillis(); // Any scroller can be used for time, since they were started // together in scroll mode. We use X here. const elapsedTime = time - this.mScrollerX.mStartTime; const duration = this.mScrollerX.mDuration; if (elapsedTime < duration) { let q = (elapsedTime) / duration; if (this.mInterpolator == null) { q = Scroller_viscousFluid(q); } else { q = this.mInterpolator.getInterpolation(q); } this.mScrollerX.updateScroll(q); this.mScrollerY.updateScroll(q); } else { this.abortAnimation(); } break; case OverScroller.FLING_MODE: if (!this.mScrollerX.mFinished) { if (!this.mScrollerX.update()) { if (!this.mScrollerX.continueWhenFinished()) { this.mScrollerX.finish(); } } } if (!this.mScrollerY.mFinished) { if (!this.mScrollerY.update()) { if (!this.mScrollerY.continueWhenFinished()) { this.mScrollerY.finish(); } } } break; } return true; } /** * Start scrolling by providing a starting point and the distance to travel. * * @param startX Starting horizontal scroll offset in pixels. Positive * numbers will scroll the content to the left. * @param startY Starting vertical scroll offset in pixels. Positive numbers * will scroll the content up. * @param dx Horizontal distance to travel. Positive numbers will scroll the * content to the left. * @param dy Vertical distance to travel. Positive numbers will scroll the * content up. * @param duration Duration of the scroll in milliseconds. */ startScroll(startX:number, startY:number, dx:number, dy:number, duration=OverScroller.DEFAULT_DURATION) { NumberChecker.warnNotNumber(startX, startY, dx, dy, duration); this.mMode = OverScroller.SCROLL_MODE; this.mScrollerX.startScroll(startX, dx, duration); this.mScrollerY.startScroll(startY, dy, duration); } /** * Call this when you want to 'spring back' into a valid coordinate range. * * @param startX Starting X coordinate * @param startY Starting Y coordinate * @param minX Minimum valid X value * @param maxX Maximum valid X value * @param minY Minimum valid Y value * @param maxY Minimum valid Y value * @return true if a springback was initiated, false if startX and startY were * already within the valid range. */ springBack(startX:number, startY:number, minX:number, maxX:number, minY:number, maxY:number):boolean { NumberChecker.warnNotNumber(startX, startY, minX, maxX, minY, maxY); this.mMode = OverScroller.FLING_MODE; // Make sure both methods are called. const spingbackX = this.mScrollerX.springback(startX, minX, maxX); const spingbackY = this.mScrollerY.springback(startY, minY, maxY); return spingbackX || spingbackY; } /** * Start scrolling based on a fling gesture. The distance traveled will * depend on the initial velocity of the fling. * * @param startX Starting point of the scroll (X) * @param startY Starting point of the scroll (Y) * @param velocityX Initial velocity of the fling (X) measured in pixels per * second. * @param velocityY Initial velocity of the fling (Y) measured in pixels per * second * @param minX Minimum X value. The scroller will not scroll past this point * unless overX > 0. If overfling is allowed, it will use minX as * a springback boundary. * @param maxX Maximum X value. The scroller will not scroll past this point * unless overX > 0. If overfling is allowed, it will use maxX as * a springback boundary. * @param minY Minimum Y value. The scroller will not scroll past this point * unless overY > 0. If overfling is allowed, it will use minY as * a springback boundary. * @param maxY Maximum Y value. The scroller will not scroll past this point * unless overY > 0. If overfling is allowed, it will use maxY as * a springback boundary. * @param overX Overfling range. If > 0, horizontal overfling in either * direction will be possible. * @param overY Overfling range. If > 0, vertical overfling in either * direction will be possible. */ fling(startX:number, startY:number, velocityX:number, velocityY:number, minX:number, maxX:number, minY:number, maxY:number, overX=0, overY=0) { NumberChecker.warnNotNumber(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, overX, overY); // Continue a scroll or fling in progress if (this.mFlywheel && !this.isFinished()) { let oldVelocityX = this.mScrollerX.mCurrVelocity; let oldVelocityY = this.mScrollerY.mCurrVelocity; if (Math_signum(velocityX) == Math_signum(oldVelocityX) && Math_signum(velocityY) == Math_signum(oldVelocityY)) { velocityX += oldVelocityX; velocityY += oldVelocityY; } } this.mMode = OverScroller.FLING_MODE; this.mScrollerX.fling(startX, velocityX, minX, maxX, overX); this.mScrollerY.fling(startY, velocityY, minY, maxY, overY); } /** * Notify the scroller that we've reached a horizontal boundary. * Normally the information to handle this will already be known * when the animation is started, such as in a call to one of the * fling functions. However there are cases where this cannot be known * in advance. This function will transition the current motion and * animate from startX to finalX as appropriate. * * @param startX Starting/current X position * @param finalX Desired final X position * @param overX Magnitude of overscroll allowed. This should be the maximum * desired distance from finalX. Absolute value - must be positive. */ notifyHorizontalEdgeReached(startX:number, finalX:number, overX:number) { NumberChecker.warnNotNumber(startX, finalX, overX); this.mScrollerX.notifyEdgeReached(startX, finalX, overX); } /** * Notify the scroller that we've reached a vertical boundary. * Normally the information to handle this will already be known * when the animation is started, such as in a call to one of the * fling functions. However there are cases where this cannot be known * in advance. This function will animate a parabolic motion from * startY to finalY. * * @param startY Starting/current Y position * @param finalY Desired final Y position * @param overY Magnitude of overscroll allowed. This should be the maximum * desired distance from finalY. Absolute value - must be positive. */ notifyVerticalEdgeReached(startY:number, finalY:number, overY:number) { NumberChecker.warnNotNumber(startY, finalY, overY); this.mScrollerY.notifyEdgeReached(startY, finalY, overY); } /** * Returns whether the current Scroller is currently returning to a valid position. * Valid bounds were provided by the * {@link #fling(int, int, int, int, int, int, int, int, int, int)} method. * * One should check this value before calling * {@link #startScroll(int, int, int, int)} as the interpolation currently in progress * to restore a valid position will then be stopped. The caller has to take into account * the fact that the started scroll will start from an overscrolled position. * * @return true when the current position is overscrolled and in the process of * interpolating back to a valid value. */ isOverScrolled():boolean { return ((!this.mScrollerX.mFinished && this.mScrollerX.mState != SplineOverScroller.SPLINE) || (!this.mScrollerY.mFinished && this.mScrollerY.mState != SplineOverScroller.SPLINE)); } /** * Stops the animation. Contrary to {@link #forceFinished(boolean)}, * aborting the animating causes the scroller to move to the final x and y * positions. * * @see #forceFinished(boolean) */ abortAnimation() { this.mScrollerX.finish(); this.mScrollerY.finish(); } /** * Returns the time elapsed since the beginning of the scrolling. * * @return The elapsed time in milliseconds. * * @hide */ timePassed():number { const time = SystemClock.uptimeMillis(); const startTime = Math.min(this.mScrollerX.mStartTime, this.mScrollerY.mStartTime); return (time - startTime); } isScrollingInDirection(xvel:number, yvel:number):boolean { const dx = this.mScrollerX.mFinal - this.mScrollerX.mStart; const dy = this.mScrollerY.mFinal - this.mScrollerY.mStart; return !this.isFinished() && Math_signum(xvel) == Math_signum(dx) && Math_signum(yvel) == Math_signum(dy); } } class SplineOverScroller{ static DECELERATION_RATE = (Math.log(0.78) / Math.log(0.9)); static INFLEXION = 0.35; // Tension lines cross at (INFLEXION, 1) static START_TENSION = 0.5; static END_TENSION = 1.0; static P1 = SplineOverScroller.START_TENSION * SplineOverScroller.INFLEXION; static P2 = 1.0 - SplineOverScroller.END_TENSION * (1 - SplineOverScroller.INFLEXION); static NB_SAMPLES = 100; static SPLINE_POSITION = androidui.util.ArrayCreator.newNumberArray(SplineOverScroller.NB_SAMPLES + 1); static SPLINE_TIME = androidui.util.ArrayCreator.newNumberArray(SplineOverScroller.NB_SAMPLES + 1); static SPLINE = 0; static CUBIC = 1; static BALLISTIC = 2; // Initial position mStart = 0; // Current position mCurrentPosition = 0; // Final position mFinal = 0; // Initial velocity mVelocity = 0; // Current velocity private _mCurrVelocity = 0; get mCurrVelocity():number{ return this._mCurrVelocity; } set mCurrVelocity(value:number){ if(!NumberChecker.checkIsNumber(value)){ value = 0; } this._mCurrVelocity = value; } // Constant current deceleration mDeceleration = 0; // Animation starting time, in system milliseconds mStartTime = 0; // Animation duration, in milliseconds mDuration = 0; // Duration to complete spline component of animation mSplineDuration = 0; // Distance to travel along spline animation mSplineDistance = 0; // Whether the animation is currently in progress mFinished = false; // The allowed overshot distance before boundary is reached. mOver = 0; // Fling friction mFlingFriction = ViewConfiguration.getScrollFriction(); // Current state of the animation. mState = SplineOverScroller.SPLINE; // Constant gravity value, used in the deceleration phase. static GRAVITY = 2000; // A context-specific coefficient adjusted to physical values. mPhysicalCoeff = 0; static _staticFunc = function(){ let x_min = 0.0; let y_min = 0.0; for (let i = 0; i < SplineOverScroller.NB_SAMPLES; i++) { const alpha = i / SplineOverScroller.NB_SAMPLES; let x_max = 1.0; let x, tx, coef; while (true) { x = x_min + (x_max - x_min) / 2.0; coef = 3.0 * x * (1.0 - x); tx = coef * ((1.0 - x) * SplineOverScroller.P1 + x * SplineOverScroller.P2) + x * x * x; if (Math.abs(tx - alpha) < 1E-5) break; if (tx > alpha) x_max = x; else x_min = x; } SplineOverScroller.SPLINE_POSITION[i] = coef * ((1.0 - x) * SplineOverScroller.START_TENSION + x) + x * x * x; let y_max = 1.0; let y, dy; while (true) { y = y_min + (y_max - y_min) / 2.0; coef = 3.0 * y * (1.0 - y); dy = coef * ((1.0 - y) * SplineOverScroller.START_TENSION + y) + y * y * y; if (Math.abs(dy - alpha) < 1E-5) break; if (dy > alpha) y_max = y; else y_min = y; } SplineOverScroller.SPLINE_TIME[i] = coef * ((1.0 - y) * SplineOverScroller.P1 + y * SplineOverScroller.P2) + y * y * y; } SplineOverScroller.SPLINE_POSITION[SplineOverScroller.NB_SAMPLES] = SplineOverScroller.SPLINE_TIME[SplineOverScroller.NB_SAMPLES] = 1.0; }(); setFriction(friction:number) { this.mFlingFriction = friction; } constructor(){ this.mFinished = true; let ppi = Resources.getDisplayMetrics().density * 160; this.mPhysicalCoeff = 9.80665 // g (m/s^2) * 39.37 // inch/meter * ppi * 0.84; // look and feel tuning } updateScroll(q:number) { this.mCurrentPosition = this.mStart + Math.round(q * (this.mFinal - this.mStart)); } static getDeceleration(velocity:number) { return velocity > 0 ? -SplineOverScroller.GRAVITY : SplineOverScroller.GRAVITY; } private adjustDuration(start:number, oldFinal:number, newFinal:number):void { let oldDistance = oldFinal - start; let newDistance = newFinal - start; let x = Math.abs(newDistance / oldDistance); let index = Math.floor(SplineOverScroller.NB_SAMPLES * x); if (index < SplineOverScroller.NB_SAMPLES) { let x_inf = index / SplineOverScroller.NB_SAMPLES; let x_sup = (index + 1) / SplineOverScroller.NB_SAMPLES; let t_inf = SplineOverScroller.SPLINE_TIME[index]; let t_sup = SplineOverScroller.SPLINE_TIME[index + 1]; let timeCoef = t_inf + (x - x_inf) / (x_sup - x_inf) * (t_sup - t_inf); this.mDuration *= timeCoef; } } startScroll(start:number, distance:number, duration:number) { this.mFinished = false; this.mStart = start; this.mFinal = start + distance; this.mStartTime = SystemClock.uptimeMillis(); this.mDuration = duration; // Unused this.mDeceleration = 0; this.mVelocity = 0; } finish() { this.mCurrentPosition = this.mFinal; this.mFinished = true; } setFinalPosition(position:number) { this.mFinal = position; this.mFinished = false; } extendDuration(extend:number) { let time = SystemClock.uptimeMillis(); let elapsedTime = (time - this.mStartTime); this.mDuration = elapsedTime + extend; this.mFinished = false; } springback(start:number, min:number, max:number):boolean { this.mFinished = true; this.mStart = this.mFinal = start; this.mVelocity = 0; this.mStartTime = SystemClock.uptimeMillis(); this.mDuration = 0; if (start < min) { this.startSpringback(start, min, 0); } else if (start > max) { this.startSpringback(start, max, 0); } return !this.mFinished; } startSpringback(start:number, end:number, velocity:number) { // mStartTime has been set this.mFinished = false; this.mState = SplineOverScroller.CUBIC; this.mStart = start; this.mFinal = end; const delta = start - end; this.mDeceleration = SplineOverScroller.getDeceleration(delta); // TODO take velocity into account this.mVelocity = -delta; // only sign is used this.mOver = Math.abs(delta); const density = android.content.res.Resources.getDisplayMetrics().density; this.mDuration = Math.floor(1000.0 * Math.sqrt(-2.0 * (delta / density) / this.mDeceleration)); } fling(start:number, velocity:number, min:number, max:number, over:number) { this.mOver = over; this.mFinished = false; this.mCurrVelocity = this.mVelocity = velocity; this.mDuration = this.mSplineDuration = 0; this.mStartTime = SystemClock.uptimeMillis(); this.mCurrentPosition = this.mStart = start; if (start > max || start < min) { this.startAfterEdge(start, min, max, velocity); return; } this.mState = SplineOverScroller.SPLINE; let totalDistance = 0.0; if (velocity != 0) { this.mDuration = this.mSplineDuration = this.getSplineFlingDuration(velocity); totalDistance = this.getSplineFlingDistance(velocity); } this.mSplineDistance = (totalDistance * Math_signum(velocity)); this.mFinal = start + this.mSplineDistance; // Clamp to a valid final position if (this.mFinal < min) { this.adjustDuration(this.mStart, this.mFinal, min); this.mFinal = min; } if (this.mFinal > max) { this.adjustDuration(this.mStart, this.mFinal, max); this.mFinal = max; } } getSplineDeceleration(velocity:number):number { return Math.log(SplineOverScroller.INFLEXION * Math.abs(velocity) / (this.mFlingFriction * this.mPhysicalCoeff)); } getSplineFlingDistance(velocity:number):number { let l = this.getSplineDeceleration(velocity); let decelMinusOne = SplineOverScroller.DECELERATION_RATE - 1.0; return this.mFlingFriction * this.mPhysicalCoeff * Math.exp(SplineOverScroller.DECELERATION_RATE / decelMinusOne * l); } getSplineFlingDuration(velocity:number):number { let l = this.getSplineDeceleration(velocity); let decelMinusOne = SplineOverScroller.DECELERATION_RATE - 1.0; return (1000.0 * Math.exp(l / decelMinusOne)); } fitOnBounceCurve(start:number, end:number, velocity:number) { // Simulate a bounce that started from edge let durationToApex = - velocity / this.mDeceleration; let distanceToApex = velocity * velocity / 2.0 / Math.abs(this.mDeceleration); let distanceToEdge = Math.abs(end - start); let totalDuration = Math.sqrt( 2.0 * (distanceToApex + distanceToEdge) / Math.abs(this.mDeceleration)); this.mStartTime -= (1000 * (totalDuration - durationToApex)); this.mStart = end; this.mVelocity = (- this.mDeceleration * totalDuration); } startBounceAfterEdge(start:number, end:number, velocity:number) { this.mDeceleration = SplineOverScroller.getDeceleration(velocity == 0 ? start - end : velocity); this.fitOnBounceCurve(start, end, velocity); this.onEdgeReached(); } startAfterEdge(start:number, min:number, max:number, velocity:number) { if (start > min && start < max) { Log.e("OverScroller", "startAfterEdge called from a valid position"); this.mFinished = true; return; } const positive = start > max; const edge = positive ? max : min; const overDistance = start - edge; let keepIncreasing = overDistance * velocity >= 0; if (keepIncreasing) { // Will result in a bounce or a to_boundary depending on velocity. this.startBounceAfterEdge(start, edge, velocity); } else { const totalDistance = this.getSplineFlingDistance(velocity); if (totalDistance > Math.abs(overDistance)) { this.fling(start, velocity, positive ? min : start, positive ? start : max, this.mOver); } else { this.startSpringback(start, edge, velocity); } } } notifyEdgeReached(start:number, end:number, over:number) { // mState is used to detect successive notifications if (this.mState == SplineOverScroller.SPLINE) { this.mOver = over; this.mStartTime = SystemClock.uptimeMillis(); // We were in fling/scroll mode before: current velocity is such that distance to // edge is increasing. This ensures that startAfterEdge will not start a new fling. this.startAfterEdge(start, end, end, this.mCurrVelocity); } } onEdgeReached() { // mStart, mVelocity and mStartTime were adjusted to their values when edge was reached. let distance = this.mVelocity * this.mVelocity / (2 * Math.abs(this.mDeceleration)); const sign = Math_signum(this.mVelocity); if (distance > this.mOver) { // Default deceleration is not sufficient to slow us down before boundary this.mDeceleration = - sign * this.mVelocity * this.mVelocity / (2.0 * this.mOver); distance = this.mOver; } this.mOver = distance; this.mState = SplineOverScroller.BALLISTIC; this.mFinal = this.mStart + (this.mVelocity > 0 ? distance : -distance); this.mDuration = - (1000 * this.mVelocity / this.mDeceleration); } continueWhenFinished():boolean { switch (this.mState) { case SplineOverScroller.SPLINE: // Duration from start to null velocity if (this.mDuration < this.mSplineDuration) { // If the animation was clamped, we reached the edge this.mStart = this.mFinal; // TODO Better compute speed when edge was reached this.mVelocity = this.mCurrVelocity; this.mDeceleration = SplineOverScroller.getDeceleration(this.mVelocity); this.mStartTime += this.mDuration; this.onEdgeReached(); } else { // Normal stop, no need to continue return false; } break; case SplineOverScroller.BALLISTIC: this.mStartTime += this.mDuration; this.startSpringback(this.mFinal, this.mStart, 0); break; case SplineOverScroller.CUBIC: return false; } this.update(); return true; } update():boolean { const time = SystemClock.uptimeMillis(); const currentTime = time - this.mStartTime; if (currentTime > this.mDuration) { return false; } let distance = 0; switch (this.mState) { case SplineOverScroller.SPLINE: { const t = currentTime / this.mSplineDuration; const index = Math.floor(SplineOverScroller.NB_SAMPLES * t); let distanceCoef = 1; let velocityCoef = 0; if (index < SplineOverScroller.NB_SAMPLES) { const t_inf = index / SplineOverScroller.NB_SAMPLES; const t_sup = (index + 1) / SplineOverScroller.NB_SAMPLES; const d_inf = SplineOverScroller.SPLINE_POSITION[index]; const d_sup = SplineOverScroller.SPLINE_POSITION[index + 1]; velocityCoef = (d_sup - d_inf) / (t_sup - t_inf); distanceCoef = d_inf + (t - t_inf) * velocityCoef; } distance = distanceCoef * this.mSplineDistance; this.mCurrVelocity = velocityCoef * this.mSplineDistance / this.mSplineDuration * 1000; break; } case SplineOverScroller.BALLISTIC: { const t = currentTime / 1000; this.mCurrVelocity = this.mVelocity + this.mDeceleration * t; distance = this.mVelocity * t + this.mDeceleration * t * t / 2; break; } case SplineOverScroller.CUBIC: { const t = (currentTime) / this.mDuration; const t2 = t * t; const sign = Math_signum(this.mVelocity); distance = sign * this.mOver * (3 * t2 - 2 * t * t2); this.mCurrVelocity = sign * this.mOver * 6 * (- t + t2); break; } } this.mCurrentPosition = this.mStart + Math.round(distance); return true; } } function Math_signum(value:number):number{ if(value === 0 || Number.isNaN(value)) return value; return Math.abs(value)===value ? 1 : -1; } let sViscousFluidScale = 8; // must be set to 1.0 (used in viscousFluid()) let sViscousFluidNormalize = 1; function Scroller_viscousFluid(x:number):number{ x *= sViscousFluidScale; if (x < 1) { x -= (1 - Math.exp(-x)); } else { let start = 0.36787944117; // 1/e == exp(-1) x = 1 - Math.exp(1 - x); x = start + x * (1 - start); } x *= sViscousFluidNormalize; return x; } sViscousFluidNormalize = 1 / Scroller_viscousFluid(1); }
the_stack
import { Nullable } from "../types"; import { Scene } from "../scene"; import { AbstractMesh } from "../Meshes/abstractMesh"; import { Mesh } from "../Meshes/mesh"; import { CreateBox } from "../Meshes/Builders/boxBuilder"; import { CreateSphere } from "../Meshes/Builders/sphereBuilder"; import { Quaternion, Vector3 } from "../Maths/math.vector"; import { Color3 } from '../Maths/math.color'; import { Material } from "../Materials/material"; import { EngineStore } from "../Engines/engineStore"; import { StandardMaterial } from "../Materials/standardMaterial"; import { IPhysicsEnginePlugin } from "../Physics/IPhysicsEngine"; import { PhysicsImpostor } from "../Physics/physicsImpostor"; import { UtilityLayerRenderer } from "../Rendering/utilityLayerRenderer"; import { CreateCylinder } from '../Meshes/Builders/cylinderBuilder'; import { CreateCapsule, ICreateCapsuleOptions } from '../Meshes/Builders/capsuleBuilder'; /** * Used to show the physics impostor around the specific mesh */ export class PhysicsViewer { /** @hidden */ protected _impostors: Array<Nullable<PhysicsImpostor>> = []; /** @hidden */ protected _meshes: Array<Nullable<AbstractMesh>> = []; /** @hidden */ protected _scene: Nullable<Scene>; /** @hidden */ protected _numMeshes = 0; /** @hidden */ protected _physicsEnginePlugin: Nullable<IPhysicsEnginePlugin>; private _renderFunction: () => void; private _utilityLayer: Nullable<UtilityLayerRenderer>; private _debugBoxMesh: Mesh; private _debugSphereMesh: Mesh; private _debugCapsuleMesh: Mesh; private _debugCylinderMesh: Mesh; private _debugMaterial: StandardMaterial; private _debugMeshMeshes = new Array<Mesh>(); /** * Creates a new PhysicsViewer * @param scene defines the hosting scene */ constructor(scene: Scene) { this._scene = scene || EngineStore.LastCreatedScene; let physicEngine = this._scene.getPhysicsEngine(); if (physicEngine) { this._physicsEnginePlugin = physicEngine.getPhysicsPlugin(); } this._utilityLayer = new UtilityLayerRenderer(this._scene, false); this._utilityLayer.pickUtilitySceneFirst = false; this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true; } /** @hidden */ protected _updateDebugMeshes(): void { var plugin = this._physicsEnginePlugin; for (var i = 0; i < this._numMeshes; i++) { let impostor = this._impostors[i]; if (!impostor) { continue; } if (impostor.isDisposed) { this.hideImpostor(this._impostors[i--]); } else { if (impostor.type === PhysicsImpostor.MeshImpostor) { continue; } let mesh = this._meshes[i]; if (mesh && plugin) { plugin.syncMeshWithImpostor(mesh, impostor); } } } } /** * Renders a specified physic impostor * @param impostor defines the impostor to render * @param targetMesh defines the mesh represented by the impostor * @returns the new debug mesh used to render the impostor */ public showImpostor(impostor: PhysicsImpostor, targetMesh?: Mesh): Nullable<AbstractMesh> { if (!this._scene) { return null; } for (var i = 0; i < this._numMeshes; i++) { if (this._impostors[i] == impostor) { return null; } } var debugMesh = this._getDebugMesh(impostor, targetMesh); if (debugMesh) { this._impostors[this._numMeshes] = impostor; this._meshes[this._numMeshes] = debugMesh; if (this._numMeshes === 0) { this._renderFunction = this._updateDebugMeshes.bind(this); this._scene.registerBeforeRender(this._renderFunction); } this._numMeshes++; } return debugMesh; } /** * Hides a specified physic impostor * @param impostor defines the impostor to hide */ public hideImpostor(impostor: Nullable<PhysicsImpostor>) { if (!impostor || !this._scene || !this._utilityLayer) { return; } var removed = false; const utilityLayerScene = this._utilityLayer.utilityLayerScene; for (var i = 0; i < this._numMeshes; i++) { if (this._impostors[i] == impostor) { let mesh = this._meshes[i]; if (!mesh) { continue; } utilityLayerScene.removeMesh(mesh); mesh.dispose(); let index = this._debugMeshMeshes.indexOf(mesh as Mesh); if (index > -1) { this._debugMeshMeshes.splice(index, 1); } this._numMeshes--; if (this._numMeshes > 0) { this._meshes[i] = this._meshes[this._numMeshes]; this._impostors[i] = this._impostors[this._numMeshes]; this._meshes[this._numMeshes] = null; this._impostors[this._numMeshes] = null; } else { this._meshes[0] = null; this._impostors[0] = null; } removed = true; break; } } if (removed && this._numMeshes === 0) { this._scene.unregisterBeforeRender(this._renderFunction); } } private _getDebugMaterial(scene: Scene): Material { if (!this._debugMaterial) { this._debugMaterial = new StandardMaterial('', scene); this._debugMaterial.wireframe = true; this._debugMaterial.emissiveColor = Color3.White(); this._debugMaterial.disableLighting = true; } return this._debugMaterial; } private _getDebugBoxMesh(scene: Scene): AbstractMesh { if (!this._debugBoxMesh) { this._debugBoxMesh = CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene); this._debugBoxMesh.rotationQuaternion = Quaternion.Identity(); this._debugBoxMesh.material = this._getDebugMaterial(scene); this._debugBoxMesh.setEnabled(false); } return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance'); } private _getDebugSphereMesh(scene: Scene): AbstractMesh { if (!this._debugSphereMesh) { this._debugSphereMesh = CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene); this._debugSphereMesh.rotationQuaternion = Quaternion.Identity(); this._debugSphereMesh.material = this._getDebugMaterial(scene); this._debugSphereMesh.setEnabled(false); } return this._debugSphereMesh.createInstance('physicsBodySphereViewInstance'); } private _getDebugCapsuleMesh(scene: Scene): AbstractMesh { if (!this._debugCapsuleMesh) { this._debugCapsuleMesh = CreateCapsule('physicsBodyCapsuleViewMesh', { height: 1 } as ICreateCapsuleOptions, scene); this._debugCapsuleMesh.rotationQuaternion = Quaternion.Identity(); this._debugCapsuleMesh.material = this._getDebugMaterial(scene); this._debugCapsuleMesh.setEnabled(false); } return this._debugCapsuleMesh.createInstance('physicsBodyCapsuleViewInstance'); } private _getDebugCylinderMesh(scene: Scene): AbstractMesh { if (!this._debugCylinderMesh) { this._debugCylinderMesh = CreateCylinder('physicsBodyCylinderViewMesh', { diameterTop: 1, diameterBottom: 1, height: 1 }, scene); this._debugCylinderMesh.rotationQuaternion = Quaternion.Identity(); this._debugCylinderMesh.material = this._getDebugMaterial(scene); this._debugCylinderMesh.setEnabled(false); } return this._debugCylinderMesh.createInstance('physicsBodyCylinderViewInstance'); } private _getDebugMeshMesh(mesh: Mesh, scene: Scene): AbstractMesh { var wireframeOver = new Mesh(mesh.name, scene, null, mesh); wireframeOver.position = Vector3.Zero(); wireframeOver.setParent(mesh); wireframeOver.material = this._getDebugMaterial(scene); this._debugMeshMeshes.push(wireframeOver); return wireframeOver; } private _getDebugMesh(impostor: PhysicsImpostor, targetMesh?: Mesh): Nullable<AbstractMesh> { if (!this._utilityLayer) { return null; } // Only create child impostor debug meshes when evaluating the parent if (targetMesh && targetMesh.parent && (targetMesh.parent as Mesh).physicsImpostor) { return null; } var mesh: Nullable<AbstractMesh> = null; const utilityLayerScene = this._utilityLayer.utilityLayerScene; switch (impostor.type) { case PhysicsImpostor.BoxImpostor: mesh = this._getDebugBoxMesh(utilityLayerScene); impostor.getBoxSizeToRef(mesh.scaling); break; case PhysicsImpostor.SphereImpostor: mesh = this._getDebugSphereMesh(utilityLayerScene); var radius = impostor.getRadius(); mesh.scaling.x = radius * 2; mesh.scaling.y = radius * 2; mesh.scaling.z = radius * 2; break; case PhysicsImpostor.CapsuleImpostor: mesh = this._getDebugCapsuleMesh(utilityLayerScene); var bi = impostor.object.getBoundingInfo(); mesh.scaling.x = (bi.boundingBox.maximum.x - bi.boundingBox.minimum.x) * 2 * impostor.object.scaling.x; mesh.scaling.y = (bi.boundingBox.maximum.y - bi.boundingBox.minimum.y) * impostor.object.scaling.y; mesh.scaling.z = (bi.boundingBox.maximum.z - bi.boundingBox.minimum.z) * 2 * impostor.object.scaling.z; break; case PhysicsImpostor.MeshImpostor: if (targetMesh) { mesh = this._getDebugMeshMesh(targetMesh, utilityLayerScene); } break; case PhysicsImpostor.NoImpostor: if (targetMesh) { // Handle compound impostors var childMeshes = targetMesh.getChildMeshes().filter((c) => { return c.physicsImpostor ? 1 : 0; }); childMeshes.forEach((m) => { if (m.physicsImpostor && m.getClassName() === "Mesh") { const boundingInfo = m.getBoundingInfo(); const min = boundingInfo.boundingBox.minimum; const max = boundingInfo.boundingBox.maximum; switch (m.physicsImpostor.type) { case PhysicsImpostor.BoxImpostor: mesh = this._getDebugBoxMesh(utilityLayerScene); mesh.position.copyFrom(min); mesh.position.addInPlace(max); mesh.position.scaleInPlace(0.5); break; case PhysicsImpostor.SphereImpostor: mesh = this._getDebugSphereMesh(utilityLayerScene); break; case PhysicsImpostor.CylinderImpostor: mesh = this._getDebugCylinderMesh(utilityLayerScene); break; default: mesh = null; break; } if (mesh) { mesh.scaling.x = max.x - min.x; mesh.scaling.y = max.y - min.y; mesh.scaling.z = max.z - min.z; mesh.parent = m; } } }); } mesh = null; break; case PhysicsImpostor.CylinderImpostor: mesh = this._getDebugCylinderMesh(utilityLayerScene); var bi = impostor.object.getBoundingInfo(); mesh.scaling.x = (bi.boundingBox.maximum.x - bi.boundingBox.minimum.x) * impostor.object.scaling.x; mesh.scaling.y = (bi.boundingBox.maximum.y - bi.boundingBox.minimum.y) * impostor.object.scaling.y; mesh.scaling.z = (bi.boundingBox.maximum.z - bi.boundingBox.minimum.z) * impostor.object.scaling.z; break; } return mesh; } /** Releases all resources */ public dispose() { let count = this._numMeshes; for (var index = 0; index < count; index++) { this.hideImpostor(this._impostors[0]); } if (this._debugBoxMesh) { this._debugBoxMesh.dispose(); } if (this._debugSphereMesh) { this._debugSphereMesh.dispose(); } if (this._debugCylinderMesh) { this._debugCylinderMesh.dispose(); } if (this._debugMaterial) { this._debugMaterial.dispose(); } this._impostors.length = 0; this._scene = null; this._physicsEnginePlugin = null; if (this._utilityLayer) { this._utilityLayer.dispose(); this._utilityLayer = null; } } }
the_stack
import { AnimationClip, Component, Node, Vec2, Vec3, warnID } from '../../cocos/core'; import { AnimationBlend1D, AnimationBlend2D, Condition, InvalidTransitionError, VariableNotDefinedError, __getDemoGraphs, ClipMotion, AnimationBlendDirect, VariableType } from '../../cocos/core/animation/marionette/asset-creation'; import { LayerBlending, AnimationGraph, StateMachine, Transition, isAnimationTransition, AnimationTransition } from '../../cocos/core/animation/marionette/animation-graph'; import { createEval } from '../../cocos/core/animation/marionette/create-eval'; import { VariableTypeMismatchedError } from '../../cocos/core/animation/marionette/errors'; import { AnimationGraphEval, StateStatus, ClipStatus } from '../../cocos/core/animation/marionette/graph-eval'; import { createGraphFromDescription } from '../../cocos/core/animation/marionette/__tmp__/graph-from-description'; import gAnyTransition from './graphs/any-transition'; import gUnspecifiedCondition from './graphs/unspecified-condition'; import glUnspecifiedConditionOnEntryNode from './graphs/unspecified-condition-for-non-entry-node'; import gSuccessiveSatisfaction from './graphs/successive-satisfaction'; import gVariableNotFoundInCondition from './graphs/variable-not-found-in-condition'; import gVariableNotFoundInAnimationBlend from './graphs/variable-not-found-in-pose-blend'; import gAnimationBlendRequiresNumbers from './graphs/pose-blend-requires-numbers'; import gInfinityLoop from './graphs/infinity-loop'; import gZeroTimePiece from './graphs/zero-time-piece'; import { blend1D } from '../../cocos/core/animation/marionette/blend-1d'; import '../utils/matcher-deep-close-to'; import { BinaryCondition, UnaryCondition, TriggerCondition } from '../../cocos/core/animation/marionette/condition'; import { AnimationController } from '../../cocos/core/animation/marionette/animation-controller'; import { StateMachineComponent } from '../../cocos/core/animation/marionette/state-machine-component'; import { VectorTrack } from '../../cocos/core/animation/animation'; describe('NewGen Anim', () => { const demoGraphs = __getDemoGraphs(); test('Defaults', () => { const graph = new AnimationGraph(); expect(graph.layers).toHaveLength(0); const layer = graph.addLayer(); expect(layer.blending).toBe(LayerBlending.additive); expect(layer.mask).toBeNull(); expect(layer.weight).toBe(1.0); const layerGraph = layer.stateMachine; testGraphDefaults(layerGraph); const animState = layerGraph.addMotion(); expect(animState.name).toBe(''); expect(animState.speed.variable).toBe(''); expect(animState.speed.value).toBe(1.0); expect(animState.motion).toBeNull(); testGraphDefaults(layerGraph.addSubStateMachine().stateMachine); const clipMotion = new ClipMotion(); expect(clipMotion.clip).toBeNull(); const animationBlend1D = new AnimationBlend1D(); expect(Array.from(animationBlend1D.items)).toHaveLength(0); expect(animationBlend1D.param.variable).toBe(''); expect(animationBlend1D.param.value).toBe(0.0); const animationBlend2D = new AnimationBlend2D(); expect(animationBlend2D.algorithm).toBe(AnimationBlend2D.Algorithm.SIMPLE_DIRECTIONAL); expect(Array.from(animationBlend2D.items)).toHaveLength(0); expect(animationBlend2D.paramX.variable).toBe(''); expect(animationBlend2D.paramX.value).toBe(0.0); expect(animationBlend2D.paramY.variable).toBe(''); expect(animationBlend2D.paramY.value).toBe(0.0); const animationBlendDirect = new AnimationBlendDirect(); expect(Array.from(animationBlendDirect.items)).toHaveLength(0); const transition = layerGraph.connect(layerGraph.entryState, animState); testTransitionDefaults(transition); const animTransition = layerGraph.connect(animState, animState); testTransitionDefaults(animTransition); expect(animTransition.duration).toBe(0.3); expect(animTransition.exitConditionEnabled).toBe(true); expect(animTransition.exitCondition).toBe(1.0); function testGraphDefaults(graph: StateMachine) { expect(Array.from(graph.states())).toStrictEqual(expect.arrayContaining([ graph.entryState, graph.exitState, graph.anyState, ])); expect(graph.entryState.name).toBe('Entry'); expect(graph.exitState.name).toBe('Exit'); expect(graph.anyState.name).toBe('Any'); expect(Array.from(graph.transitions())).toHaveLength(0); } function testTransitionDefaults (transition: Transition) { expect(transition.conditions).toHaveLength(0); } }); describe('Asset transition API', () => { const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; const n1 = layerGraph.addMotion(); const n2 = layerGraph.addMotion(); const trans1 = layerGraph.connect(n1, n2); expect([...layerGraph.getOutgoings(n1)].map((t) => t.to)).toContain(n2); expect([...layerGraph.getIncomings(n2)].map((t) => t.from)).toContain(n1); // There may be multiple transitions between two nodes. const trans2 = layerGraph.connect(n1, n2); expect(trans2).not.toBe(trans1); expect([...layerGraph.getTransition(n1, n2)]).toEqual(expect.arrayContaining([trans1, trans2])); // Self transitions are also allowed. const n3 = layerGraph.addMotion(); const selfTransition = layerGraph.connect(n3, n3); expect([...layerGraph.getTransition(n3, n3)]).toMatchObject([selfTransition]); test('Remove transition by transition object', () => { const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; const n1 = layerGraph.addMotion(); const n2 = layerGraph.addMotion(); const n3 = layerGraph.addMotion(); const n4 = layerGraph.addMotion(); layerGraph.connect(n1, n3); const trans1 = layerGraph.connect(n1, n2); const trans2 = layerGraph.connect(n1, n2); const trans3 = layerGraph.connect(n1, n2); layerGraph.connect(n1, n4); layerGraph.removeTransition(trans2); { const transitions = Array.from(layerGraph.getTransition(n1, n2)); expect(transitions).toHaveLength(2); expect(transitions[0]).toBe(trans1); expect(transitions[1]).toBe(trans3); } layerGraph.removeTransition(trans1); { const transitions = Array.from(layerGraph.getTransition(n1, n2)); expect(transitions).toHaveLength(1); expect(transitions[0]).toBe(trans3); } layerGraph.removeTransition(trans3); { const transitions = Array.from(layerGraph.getTransition(n1, n2)); expect(transitions).toHaveLength(0); } }); }); describe('Transitions', () => { test('Could not transition to entry node', () => { const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; expect(() => layerGraph.connect(layerGraph.addMotion(), layerGraph.entryState)).toThrowError(InvalidTransitionError); }); test('Could not transition from exit node', () => { const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; expect(() => layerGraph.connect(layerGraph.exitState, layerGraph.addMotion())).toThrowError(InvalidTransitionError); }); test('Zero time piece', () => { // SPEC: Whenever zero time piece is encountered, // no matter the time piece is generated since originally passed to `update()`, // or was exhausted and left zero. // The following updates at that time would still steadily proceed: // - The graph is in transition state and the transition specified 0 duration, then the switch will happened; // - The graph is in node state and a transition is judged to be happened, then the graph will run in transition state. const graphEval = createAnimationGraphEval(createGraphFromDescription(gZeroTimePiece), new Node()); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'SubStateMachineNode1' }, }); }); test(`Transition: anim -> anim`, () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const node1 = graph.addMotion(); node1.motion = createClipMotionPositionX(1.0, 2.0); const node2 = graph.addMotion(); node2.motion = createClipMotionPositionX(1.0, 3.0); graph.connect(graph.entryState, node1); const transition = graph.connect(node1, node2); transition.duration = 0.3; transition.exitConditionEnabled = true; transition.exitCondition = 0.0; const rootNode = new Node(); const graphEval = createAnimationGraphEval(animationGraph, rootNode); graphEval.update(0.15); expect(rootNode.position).toBeDeepCloseTo(new Vec3(2.5)); }); test('Condition not specified', () => { const graphEval = createAnimationGraphEval(createGraphFromDescription(gUnspecifiedCondition), new Node()); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'asd' }, }); }); test('Condition not specified for non-entry node', () => { const graphEval = createAnimationGraphEval(createGraphFromDescription(glUnspecifiedConditionOnEntryNode), new Node()); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'Node1' }, transition: { nextNode: { __DEBUG_ID__: 'Node2' }, }, }); graphEval.update(0.32); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'Node2' }, }); }); test('Successive transitions', () => { const graphEval = createAnimationGraphEval(createGraphFromDescription(gSuccessiveSatisfaction), new Node()); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'Node2' }, }); }); test('Infinity loop', () => { const warnMockInstance = warnID as unknown as jest.MockInstance<ReturnType<typeof warnID>, Parameters<typeof warnID>>; warnMockInstance.mockClear(); const graphEval = createAnimationGraphEval(createGraphFromDescription(gInfinityLoop), new Node()); graphEval.update(0.0); expect(warnMockInstance).toBeCalledTimes(1); expect(warnMockInstance.mock.calls[0]).toHaveLength(2); expect(warnMockInstance.mock.calls[0][0]).toStrictEqual(14000); expect(warnMockInstance.mock.calls[0][1]).toStrictEqual(100); }); test('Self transition', () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const animState = graph.addMotion(); animState.name = 'Node'; const anim = animState.motion = createClipMotionPositionXLinear(1.0, 0.3, 1.4); const clip = anim.clip!; graph.connect(graph.entryState, animState); const selfTransition = graph.connect(animState, animState); selfTransition.exitConditionEnabled = true; selfTransition.exitCondition = 0.9; selfTransition.duration = 0.3; const node = new Node(); const graphEval = createAnimationGraphEval(animationGraph, node); graphEval.update(0.7); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip, weight: 1.0, }, }); expect(node.position.x).toBeCloseTo(0.3 + (1.4 - 0.3) * 0.7); graphEval.update(0.25); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip, weight: 0.83333, }, transition: { time: 0.05, next: { clip, weight: 0.16667, }, }, }); expect(node.position.x).toBeCloseTo( (0.3 + (1.4 - 0.3) * 0.95) * 0.83333 + (0.3 + (1.4 - 0.3) * 0.05) * 0.16667 ); }); test('Subgraph transitions are selected only when subgraph exited', () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const subStateMachine = graph.addSubStateMachine(); subStateMachine.name = 'Subgraph'; const subgraphEntryToExit = subStateMachine.stateMachine.connect(subStateMachine.stateMachine.entryState, subStateMachine.stateMachine.exitState); const [subgraphEntryToExitCondition] = subgraphEntryToExit.conditions = [new TriggerCondition()]; animationGraph.addVariable('subgraphExitTrigger', VariableType.TRIGGER, false); subgraphEntryToExitCondition.trigger = 'subgraphExitTrigger'; graph.connect(graph.entryState, subStateMachine); const node = graph.addMotion(); node.name = 'Node'; const subgraphToNode = graph.connect(subStateMachine, node); const [triggerCondition] = subgraphToNode.conditions = [new TriggerCondition()]; animationGraph.addVariable('trigger', VariableType.TRIGGER); triggerCondition.trigger = 'trigger'; const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: null, }); graphEval.setValue('trigger', true); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: null, }); graphEval.setValue('subgraphExitTrigger', true); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'Node', }, }); }); test(`In single frame: exit condition just satisfied or satisfied and remain time`, () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const animState1 = graph.addMotion(); animState1.name = 'AnimState'; const animState1Clip = animState1.motion = createClipMotionPositionX(1.0, 2.0, 'AnimState1Clip'); const animState2 = graph.addMotion(); animState2.name = 'AnimState'; const animState2Clip = animState2.motion = createClipMotionPositionX(1.0, 2.0, 'AnimState2Clip'); graph.connect(graph.entryState, animState1); const node1To2 = graph.connect(animState1, animState2); node1To2.duration = 0.0; node1To2.exitConditionEnabled = true; node1To2.exitCondition = 1.0; { const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update(animState1Clip.clip!.duration); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: animState2Clip.clip!, weight: 1.0, }, }); } { const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update(animState1Clip.clip!.duration + 0.1); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: animState2Clip.clip!, weight: 1.0, }, }); } }); test(`Exit time > 1`, () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const animState1 = graph.addMotion(); animState1.name = 'AnimState'; const animState1Clip = animState1.motion = createClipMotionPositionX(1.0, 2.0, 'AnimState1Clip'); const animState2 = graph.addMotion(); animState2.name = 'AnimState'; const animState2Clip = animState2.motion = createClipMotionPositionX(1.0, 2.0, 'AnimState2Clip'); graph.connect(graph.entryState, animState1); const node1To2 = graph.connect(animState1, animState2); node1To2.duration = 0.3; node1To2.exitConditionEnabled = true; node1To2.exitCondition = 2.7; const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update(animState1Clip.clip!.duration * 1.1); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: animState1Clip.clip!, weight: 1.0, }, }); graphEval.update(animState1Clip.clip!.duration * 1.8); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: animState1Clip.clip!, weight: 0.333333, }, transition: { time: 0.2, next: { clip: animState2Clip.clip!, weight: 0.666667, }, }, }); }); test(`Transition into subgraph`, () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const animState = graph.addMotion(); animState.name = 'AnimState'; const animClip = animState.motion = createClipMotionPositionX(1.0, 2.0, 'AnimStateClip'); const subStateMachine = graph.addSubStateMachine(); subStateMachine.name = 'Subgraph'; const subStateMachineAnimState = subStateMachine.stateMachine.addMotion(); subStateMachineAnimState.name = 'SubgraphAnimState'; const subStateMachineAnimStateClip = subStateMachineAnimState.motion = createClipMotionPositionX(1.0, 3.0, 'SubgraphAnimStateClip'); subStateMachine.stateMachine.connect(subStateMachine.stateMachine.entryState, subStateMachineAnimState); const subStateMachineAnimState2 = subStateMachine.stateMachine.addMotion(); subStateMachineAnimState2.name = 'SubgraphAnimState2'; const subgraphAnimState2Clip = subStateMachineAnimState2.motion = createClipMotionPositionX(0.1, 3.0, 'SubgraphAnimState2Clip'); const animToStateMachineAnim1ToAnim2 = subStateMachine.stateMachine.connect(subStateMachineAnimState, subStateMachineAnimState2); animToStateMachineAnim1ToAnim2.duration = 0.3; animToStateMachineAnim1ToAnim2.exitConditionEnabled = true; animToStateMachineAnim1ToAnim2.exitCondition = 1.0; graph.connect(graph.entryState, animState); const animToStateMachine = graph.connect(animState, subStateMachine); animToStateMachine.duration = 0.3; animToStateMachine.exitConditionEnabled = true; animToStateMachine.exitCondition = 0.0; const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update(0.2); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: animClip.clip!, weight: 0.33333, }, transition: { time: 0.2, next: { clip: subStateMachineAnimStateClip.clip!, weight: 0.66667, }, }, }); graphEval.update(0.1); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: subStateMachineAnimStateClip.clip!, weight: 1.0, }, }); graphEval.update(subStateMachineAnimStateClip.clip!.duration - 0.3 + 0.1); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: subStateMachineAnimStateClip.clip!, weight: 0.66667, }, transition: { time: 0.1, next: { clip: subgraphAnimState2Clip.clip!, weight: 0.33333, }, }, }); }); test('Transition from sub-state machine', () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const animState = graph.addMotion(); animState.name = 'AnimState'; const animClip = animState.motion = createClipMotionPositionX(1.0, 2.0, 'AnimStateClip'); const { subgraph, subStateMachineAnimStateClip, } = (() => { const subStateMachine = graph.addSubStateMachine(); subStateMachine.name = 'Subgraph'; const subStateMachineAnimState = subStateMachine.stateMachine.addMotion(); subStateMachineAnimState.name = 'SubgraphAnimState'; const subStateMachineAnimStateClip = subStateMachineAnimState.motion = createClipMotionPositionX(1.0, 3.0, 'SubgraphAnimStateClip'); subStateMachine.stateMachine.connect(subStateMachine.stateMachine.entryState, subStateMachineAnimState); const subStateMachineAnimStateToExit = subStateMachine.stateMachine.connect(subStateMachineAnimState, subStateMachine.stateMachine.exitState); subStateMachineAnimStateToExit.duration = 0.3; subStateMachineAnimStateToExit.exitConditionEnabled = true; subStateMachineAnimStateToExit.exitCondition = 1.0; return { subgraph: subStateMachine, subStateMachineAnimStateClip: subStateMachineAnimStateClip, }; })(); graph.connect(graph.entryState, subgraph); graph.connect(subgraph, animState); const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update( // exit condition + duration subStateMachineAnimStateClip.clip!.duration + 0.2, ); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: subStateMachineAnimStateClip.clip!, weight: 0.33333, }, transition: { time: 0.2, next: { clip: animClip.clip!, weight: 0.66667, }, }, }); graphEval.update( 0.10001, ); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: animClip.clip!, }, }); }); test('Transition from sub-state machine to sub-state machine', () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const createSubgraph = (name: string) => { const subStateMachine = graph.addSubStateMachine(); subStateMachine.name = name; const subStateMachineAnimState = subStateMachine.stateMachine.addMotion(); subStateMachineAnimState.name = `${name}AnimState`; const subStateMachineAnimStateClip = subStateMachineAnimState.motion = createClipMotionPositionX(1.0, 3.0, `${name}AnimStateClip`); subStateMachine.stateMachine.connect(subStateMachine.stateMachine.entryState, subStateMachineAnimState); const subgraphAnimStateToExit = subStateMachine.stateMachine.connect(subStateMachineAnimState, subStateMachine.stateMachine.exitState); subgraphAnimStateToExit.duration = 0.3; subgraphAnimStateToExit.exitConditionEnabled = true; subgraphAnimStateToExit.exitCondition = 1.0; return { subgraph: subStateMachine, subStateMachineAnimStateClip, }; }; const { subgraph: subgraph1, subStateMachineAnimStateClip: subgraph1AnimStateClip, } = createSubgraph('Subgraph1'); const { subgraph: subgraph2, subStateMachineAnimStateClip: subgraph2AnimStateClip, } = createSubgraph('Subgraph2'); graph.connect(graph.entryState, subgraph1); graph.connect(subgraph1, subgraph2); const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update( // exit condition + duration subgraph1AnimStateClip.clip!.duration + 0.2, ); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: subgraph1AnimStateClip.clip!, weight: 0.33333, }, transition: { time: 0.2, next: { clip: subgraph2AnimStateClip.clip!, weight: 0.66667, }, }, }); graphEval.update( 0.10001, ); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: subgraph2AnimStateClip.clip!, }, }); }); describe('Condition', () => { function createAnimationGraphForConditionTest(conditions: Condition[]) { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const node1 = graph.addMotion(); node1.name = 'FalsyBranchNode'; const node2 = graph.addMotion(); node2.name = 'TruthyBranchNode'; graph.connect(graph.entryState, node1); const transition = graph.connect(node1, node2, conditions); transition.duration = 0.0; transition.exitConditionEnabled = false; return animationGraph; } test.each([ ['Be truthy', UnaryCondition.Operator.TRUTHY, [ [true, true], [false, false] ]], ['Be falsy', UnaryCondition.Operator.FALSY, [ [true, false], [false, true], ]], ] as [ title: string, op: UnaryCondition.Operator, samples: [input: boolean, output: boolean][] ][])(`Unary: %s`, (_title, op, samples) => { for (const [input, output] of samples) { const condition = new UnaryCondition(); condition.operator = op; condition.operand.value = input; const graph = createAnimationGraphForConditionTest([condition]); const graphEval = createAnimationGraphEval(graph, new Node()); graphEval.update(0.0); if (output) { expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'TruthyBranchNode' }, }); } else { expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'FalsyBranchNode' }, }); } } }); test.each([ ['Equal to', BinaryCondition.Operator.EQUAL_TO, [ [0.2, 0.2, true], [0.2, 0.3, false], ]], ['Not equal to', BinaryCondition.Operator.NOT_EQUAL_TO, [ [0.2, 0.2, false], [0.2, 0.3, true], ]], ['Greater than', BinaryCondition.Operator.GREATER_THAN, [ [0.2, 0.2, false], [0.2, 0.3, false], [0.3, 0.2, true], ]], ['Less than', BinaryCondition.Operator.LESS_THAN, [ [0.2, 0.2, false], [0.2, 0.3, true], [0.3, 0.2, false], ]], ['Greater than or equal to', BinaryCondition.Operator.GREATER_THAN_OR_EQUAL_TO, [ [0.2, 0.2, true], [0.2, 0.3, false], [0.3, 0.2, true], ]], ['Less than or equal to', BinaryCondition.Operator.LESS_THAN_OR_EQUAL_TO, [ [0.2, 0.2, true], [0.2, 0.3, true], [0.3, 0.2, false], ]], ] as [ title: string, op: BinaryCondition.Operator, samples: [lhs: number, rhs: number, output: boolean][] ][])(`Binary: %s`, (_title, op, samples) => { for (const [lhs, rhs, output] of samples) { const condition = new BinaryCondition(); condition.operator = op; condition.lhs.value = lhs; condition.rhs.value = rhs; const graph = createAnimationGraphForConditionTest([condition]); const graphEval = createAnimationGraphEval(graph, new Node()); graphEval.update(0.0); if (output) { expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'TruthyBranchNode' }, }); } else { expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'FalsyBranchNode' }, }); } } }); test(`Trigger condition`, () => { const condition = new TriggerCondition(); condition.trigger = 'theTrigger'; const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const node1 = graph.addMotion(); node1.name = 'FalsyBranchNode'; const node2 = graph.addMotion(); node2.name = 'TruthyBranchNode'; const node3 = graph.addMotion(); node3.name = 'ExtraNode'; graph.connect(graph.entryState, node1); const transition = graph.connect(node1, node2, [condition]); transition.duration = 0.0; transition.exitConditionEnabled = false; const transition2 = graph.connect(node2, node3, [condition]); transition2.duration = 0.0; transition2.exitConditionEnabled = false; animationGraph.addVariable('theTrigger', VariableType.TRIGGER); const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'FalsyBranchNode' }, }); graphEval.setValue('theTrigger', true); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'TruthyBranchNode' }, }); expect(graphEval.getValue('theTrigger')).toBe(false); }); }); test('Exit transition shall not consume triggers', () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const motionState = graph.addMotion(); motionState.name = 'motionState'; motionState.motion = createEmptyClipMotion(1.0); const sm0 = graph.addSubStateMachine(); { const sm1 = sm0.stateMachine.addSubStateMachine(); sm1.name = 'subStateMachine'; const subStateMachineMotionState = sm1.stateMachine.addMotion(); subStateMachineMotionState.name = 'subStateMachineMotionState'; subStateMachineMotionState.motion = createEmptyClipMotion(1.0); sm1.stateMachine.connect(sm1.stateMachine.entryState, subStateMachineMotionState); { const subStateMachineExitTransition = sm1.stateMachine.connect( subStateMachineMotionState, sm1.stateMachine.exitState); subStateMachineExitTransition.duration = 0.3; subStateMachineExitTransition.exitConditionEnabled = false; const [subStateMachineExitTransitionTriggerCondition] = subStateMachineExitTransition.conditions = [new TriggerCondition()]; subStateMachineExitTransitionTriggerCondition.trigger = 't'; } sm0.stateMachine.connect(sm0.stateMachine.entryState, sm1); { const [triggerCondition] = sm0.stateMachine.connect(sm1, sm0.stateMachine.exitState).conditions = [new TriggerCondition()]; triggerCondition.trigger = 't'; } } graph.connect(graph.entryState, sm0); { const transition = graph.connect(sm0, motionState); const [triggerCondition] = transition.conditions = [new TriggerCondition()]; triggerCondition.trigger = 't'; } animationGraph.addVariable('t', VariableType.TRIGGER); const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update(0.4); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'subStateMachineMotionState' } }); graphEval.setValue('t', true); graphEval.update(0.31); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'motionState' } }); }); test('All triggers along the transition path should be reset', () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const subStateMachine1 = graph.addSubStateMachine(); subStateMachine1.name = 'Subgraph1'; const subStateMachine1_1 = subStateMachine1.stateMachine.addSubStateMachine(); subStateMachine1_1.name = 'Subgraph1_1'; const subStateMachine1_2 = subStateMachine1.stateMachine.addSubStateMachine(); subStateMachine1_2.name = 'Subgraph1_2'; const subgraph1_2AnimState = subStateMachine1_2.stateMachine.addMotion(); subgraph1_2AnimState.name = 'Subgraph1_2AnimState'; let nTriggers = 0; const addTriggerCondition = (transition: Transition) => { const [condition] = transition.conditions = [new TriggerCondition()]; condition.trigger = `trigger${nTriggers}`; animationGraph.addVariable(`trigger${nTriggers}`, VariableType.TRIGGER); ++nTriggers; }; addTriggerCondition( subStateMachine1_2.stateMachine.connect(subStateMachine1_2.stateMachine.entryState, subgraph1_2AnimState), ); addTriggerCondition( subStateMachine1.stateMachine.connect(subStateMachine1.stateMachine.entryState, subStateMachine1_1), ); subStateMachine1_1.stateMachine.connect(subStateMachine1_1.stateMachine.entryState, subStateMachine1_1.stateMachine.exitState); addTriggerCondition( subStateMachine1.stateMachine.connect(subStateMachine1_1, subStateMachine1_2), ); addTriggerCondition( graph.connect(graph.entryState, subStateMachine1), ); const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: null }); for (let i = 0; i < nTriggers; ++i) { graphEval.setValue(`trigger${i}`, true); } graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'Subgraph1_2AnimState', }, }); const triggerStates = Array.from({ length: nTriggers }, (_, iTrigger) => graphEval.getValue(`trigger${iTrigger}`)); expect(triggerStates).toStrictEqual(new Array(nTriggers).fill(false)); }); describe(`Transition priority`, () => { test('Transitions to different nodes, use the first-connected and first-matched transition', () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const animState1 = graph.addMotion(); animState1.name = 'Node1'; animState1.motion = createEmptyClipMotion(1.0); const animState2 = graph.addMotion(); animState2.name = 'Node2'; animState2.motion = createEmptyClipMotion(1.0); const animState3 = graph.addMotion(); animState3.name = 'Node3'; animState3.motion = createEmptyClipMotion(1.0); const transition1 = graph.connect(animState1, animState2); transition1.exitConditionEnabled = true; transition1.exitCondition = 0.8; const [ transition1Condition ] = transition1.conditions = [ new UnaryCondition() ]; transition1Condition.operator = UnaryCondition.Operator.TRUTHY; transition1Condition.operand.variable = 'switch1'; const transition2 = graph.connect(animState1, animState3); transition2.exitConditionEnabled = true; transition2.exitCondition = 0.8; const [ transition2Condition ] = transition2.conditions = [ new UnaryCondition() ]; transition2Condition.operator = UnaryCondition.Operator.TRUTHY; transition2Condition.operand.variable = 'switch2'; graph.connect(graph.entryState, animState1); animationGraph.addVariable('switch1', VariableType.BOOLEAN, false); animationGraph.addVariable('switch2', VariableType.BOOLEAN, false); // #region Both satisfied { const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.setValue('switch1', true); graphEval.setValue('switch2', true); graphEval.update(0.9); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'Node1' }, transition: { time: 0.1, nextNode: { __DEBUG_ID__: 'Node2' }, }, }); } // #endregion // #region The later satisfied { const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.setValue('switch1', false); graphEval.setValue('switch2', true); graphEval.update(0.9); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'Node1' }, transition: { time: 0.1, nextNode: { __DEBUG_ID__: 'Node3' }, }, }); } // #endregion }); }); test(`Transition duration: in seconds`, () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const animState1 = graph.addMotion(); animState1.name = 'Node1'; const { clip: animState1Clip } = animState1.motion = createEmptyClipMotion(4.0); const animState2 = graph.addMotion(); animState2.name = 'Node2'; const { clip: animState2Clip } = animState2.motion = createEmptyClipMotion(1.0); graph.connect(graph.entryState, animState1); const transition = graph.connect(animState1, animState2); transition.exitConditionEnabled = true; transition.exitCondition = 0.1; transition.duration = 0.3; transition.relativeDuration = false; const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update(0.1 * animState1Clip.duration + 0.1); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: animState1Clip!, weight: 0.666667, }, transition: { duration: 0.3, time: 0.1, next: { clip: animState2Clip!, weight: 0.33333, }, }, }); }); test(`Transition duration: normalized`, () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const animState1 = graph.addMotion(); animState1.name = 'Node1'; const { clip: animState1Clip } = animState1.motion = createEmptyClipMotion(4.0); const animState2 = graph.addMotion(); animState2.name = 'Node2'; const { clip: animState2Clip } = animState2.motion = createEmptyClipMotion(1.0); graph.connect(graph.entryState, animState1); const transition = graph.connect(animState1, animState2); transition.exitConditionEnabled = true; transition.exitCondition = 0.1; transition.duration = 0.3; transition.relativeDuration = true; const graphEval = createAnimationGraphEval(animationGraph, new Node()); const animState1Duration = animState1Clip.duration; graphEval.update(0.1 * animState1Duration + 0.1 * animState1Duration); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: animState1Clip!, weight: 0.666667, }, transition: { duration: 0.3 * animState1Duration, time: 0.1 * animState1Duration, next: { clip: animState2Clip!, weight: 0.33333, }, }, }); }); test(`Ran into entry/exit node`, () => { const animationGraph = new AnimationGraph(); const layer = animationGraph.addLayer(); const graph = layer.stateMachine; const animState = graph.addMotion(); animState.name = 'AnimState'; const animClip = animState.motion = createClipMotionPositionX(1.0, 2.0, 'AnimStateClip'); const subStateMachine = graph.addSubStateMachine(); subStateMachine.name = 'SubStateMachine'; const subStateMachineAnimState = subStateMachine.stateMachine.addMotion(); subStateMachineAnimState.name = 'SubStateMachineAnimState'; const subStateMachineAnimStateClip = subStateMachineAnimState.motion = createClipMotionPositionX(1.0, 3.0, 'SubStateMachineAnimStateClip'); subStateMachine.stateMachine.connect(subStateMachine.stateMachine.entryState, subStateMachineAnimState); const subStateMachineAnimStateToExit = subStateMachine.stateMachine.connect( subStateMachineAnimState, subStateMachine.stateMachine.exitState); subStateMachineAnimStateToExit.exitConditionEnabled = true; subStateMachineAnimStateToExit.exitCondition = 1.0; graph.connect(graph.entryState, subStateMachine); const subStateMachineToAnimState = graph.connect(subStateMachine, animState); const [ triggerCondition ] = subStateMachineToAnimState.conditions = [new TriggerCondition()]; triggerCondition.trigger = 'trigger'; animationGraph.addVariable('trigger', VariableType.TRIGGER); const graphEval = createAnimationGraphEval(animationGraph, new Node()); graphEval.update(0.5); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: subStateMachineAnimStateClip.clip!, weight: 1.0, }, }); graphEval.update(0.6); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: subStateMachineAnimStateClip.clip!, weight: 1.0, }, }); // Still halt graphEval.update(5.0); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: subStateMachineAnimStateClip.clip!, weight: 1.0, }, }); graphEval.setValue('trigger', true); graphEval.update(0.1); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: subStateMachineAnimStateClip.clip!, weight: 0.6666667, }, transition: { time: 0.1, next: { clip: animClip.clip!, weight: 0.333333, }, }, }); }); }); describe(`Any state`, () => { test('Could not transition to any node', () => { const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; expect(() => layerGraph.connect(layerGraph.addMotion(), layerGraph.anyState)).toThrowError(InvalidTransitionError); }); test('Transition from any state node is a kind of anim transition', () => { const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; const animState = layerGraph.addMotion(); const anyTransition = layerGraph.connect(layerGraph.anyState, animState); expect(isAnimationTransition(anyTransition)).toBe(true); }); test('Any transition', () => { const graphEval = createAnimationGraphEval(createGraphFromDescription(gAnyTransition), new Node()); graphEval.update(0.0); expectAnimationGraphEvalStatusLayer0(graphEval, { currentNode: { __DEBUG_ID__: 'Node1' }, }); }); test('Inheritance', () => { const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; const animState = layerGraph.addMotion(); const animClip = animState.motion = createClipMotionPositionX(1.0, 0.5, 'AnimStateClip'); const subStateMachine = layerGraph.addSubStateMachine(); subStateMachine.name = 'Subgraph'; const subStateMachineAnimState = subStateMachine.stateMachine.addMotion(); const subStateMachineAnimStateClip = subStateMachineAnimState.motion = createClipMotionPositionX(1.0, 0.7, 'SubgraphAnimStateClip'); subStateMachine.stateMachine.connect(subStateMachine.stateMachine.entryState, subStateMachineAnimState); layerGraph.connect(layerGraph.entryState, subStateMachine); const anyTransition = layerGraph.connect(layerGraph.anyState, animState) as AnimationTransition; anyTransition.duration = 0.3; anyTransition.exitConditionEnabled = true; anyTransition.exitCondition = 0.1; const [ triggerCondition ] = anyTransition.conditions = [new TriggerCondition()]; triggerCondition.trigger = 'trigger'; graph.addVariable('trigger', VariableType.TRIGGER, true); const graphEval = createAnimationGraphEval(graph, new Node()); graphEval.update(0.2); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: subStateMachineAnimStateClip.clip!, weight: 0.666667, }, transition: { time: 0.1, next: { clip: animClip.clip!, weight: 0.333333, }, }, }); graphEval.update(0.2); expectAnimationGraphEvalStatusLayer0(graphEval, { current: { clip: animClip.clip!, weight: 1.0, }, }); }); }); test('State events', () => { type Invocation = { kind: 'onEnter', id: string, args: Parameters<StateMachineComponent['onEnter']>; } | { kind: 'onExit', id: string, args: Parameters<StateMachineComponent['onExit']>; }; class Recorder extends Component { public record = jest.fn<void, [Invocation]>(); public clear () { this.record.mockClear(); } } class StatsComponent extends StateMachineComponent { public id: string = ''; onEnter (...args: Parameters<StateMachineComponent['onEnter']>) { this._getRecorder(args[0]).record({ kind: 'onEnter', id: this.id, args, }); } onExit (...args: Parameters<StateMachineComponent['onExit']>) { this._getRecorder(args[0]).record({ kind: 'onExit', id: this.id, args, }); } private _getRecorder(newGenAnim: AnimationController): Recorder { const receiver = newGenAnim.node.getComponent(Recorder) as Recorder | null; expect(receiver).not.toBeNull(); return receiver!; } } const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; const animState = layerGraph.addMotion(); const animStateStats = animState.addComponent(StatsComponent); animStateStats.id = 'AnimState'; animState.motion = createClipMotionPositionX(1.0, 0.5, 'AnimStateClip'); const animState2 = layerGraph.addMotion(); const animState2Stats = animState2.addComponent(StatsComponent); animState2Stats.id = 'AnimState2'; animState2.motion = createClipMotionPositionX(1.0, 0.5, 'AnimState2Clip'); const animState3 = layerGraph.addMotion(); const animState3Stats = animState3.addComponent(StatsComponent); animState3Stats.id = 'AnimState3'; animState3.motion = createClipMotionPositionX(1.0, 0.5, 'AnimState3Clip'); const subStateMachine = layerGraph.addSubStateMachine(); const subgraphStats = subStateMachine.addComponent(StatsComponent); subgraphStats.id = 'Subgraph'; const subStateMachineAnimState = subStateMachine.stateMachine.addMotion(); const subgraphAnimStateStats = subStateMachineAnimState.addComponent(StatsComponent); subgraphAnimStateStats.id = 'SubgraphAnimState'; subStateMachineAnimState.motion = createClipMotionPositionX(1.0, 0.5, 'SubgraphAnimStateClip'); subStateMachine.stateMachine.connect(subStateMachine.stateMachine.entryState, subStateMachineAnimState); const subgraphTransition = subStateMachine.stateMachine.connect(subStateMachineAnimState, subStateMachine.stateMachine.exitState); subgraphTransition.duration = 0.3; subgraphTransition.exitConditionEnabled = true; subgraphTransition.exitCondition = 0.7; layerGraph.connect(layerGraph.entryState, animState); const transition = layerGraph.connect(animState, animState2); transition.duration = 0.3; transition.exitConditionEnabled = true; transition.exitCondition = 0.7; layerGraph.connect(animState2, subStateMachine); layerGraph.connect(subStateMachine, animState3); const node = new Node(); const recorder = node.addComponent(Recorder) as Recorder; const { graphEval, newGenAnim } = createAnimationGraphEval2(graph, node); graphEval.update(0.1); expect(recorder.record).toHaveBeenCalledTimes(1); expect(recorder.record).toHaveBeenNthCalledWith(1, { kind: 'onEnter', id: 'AnimState', args: [ newGenAnim, ], }); recorder.clear(); graphEval.update(1.1); expect(recorder.record).toHaveBeenCalledTimes(2); expect(recorder.record).toHaveBeenNthCalledWith(1, { kind: 'onEnter', id: 'AnimState2', args: [ newGenAnim, ], }); expect(recorder.record).toHaveBeenNthCalledWith(2, { kind: 'onExit', id: 'AnimState', args: [ newGenAnim, ], }); recorder.clear(); graphEval.update(1.0); expect(recorder.record).toHaveBeenCalledTimes(3); expect(recorder.record).toHaveBeenNthCalledWith(1, { kind: 'onEnter', id: 'Subgraph', args: [ newGenAnim, ], }); expect(recorder.record).toHaveBeenNthCalledWith(2, { kind: 'onEnter', id: 'SubgraphAnimState', args: [ newGenAnim, ], }); expect(recorder.record).toHaveBeenNthCalledWith(3, { kind: 'onExit', id: 'AnimState2', args: [ newGenAnim, ], }); recorder.clear(); graphEval.update(1.0); expect(recorder.record).toHaveBeenCalledTimes(3); expect(recorder.record).toHaveBeenNthCalledWith(1, { kind: 'onEnter', id: 'AnimState3', args: [ newGenAnim, ], }); expect(recorder.record).toHaveBeenNthCalledWith(2, { kind: 'onExit', id: 'SubgraphAnimState', args: [ newGenAnim, ], }); expect(recorder.record).toHaveBeenNthCalledWith(3, { kind: 'onExit', id: 'Subgraph', args: [ newGenAnim, ], }); recorder.clear(); }); describe('Animation properties', () => { describe('Speed', () => { test(`Constant`, () => { const graph = new AnimationGraph(); expect(graph.layers).toHaveLength(0); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; const animState = layerGraph.addMotion(); animState.motion = createClipMotionPositionXLinear(1.0, 0.3, 1.7); animState.speed.value = 1.2; layerGraph.connect(layerGraph.entryState, animState); const node = new Node(); const animationGraphEval = createAnimationGraphEval(graph, node); animationGraphEval.update(0.2); expect(node.position.x).toBeCloseTo( 0.3 + (1.7 - 0.3) * (0.2 * 1.2 / 1.0), ); }); test(`Variable`, () => { const graph = new AnimationGraph(); expect(graph.layers).toHaveLength(0); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; const animState = layerGraph.addMotion(); animState.motion = createClipMotionPositionXLinear(1.0, 0.3, 1.7); animState.speed.variable = 'speed'; animState.speed.value = 1.2; graph.addVariable('speed', VariableType.FLOAT, 0.5); layerGraph.connect(layerGraph.entryState, animState); const node = new Node(); const animationGraphEval = createAnimationGraphEval(graph, node); animationGraphEval.update(0.2); expect(node.position.x).toBeCloseTo( 0.3 + (1.7 - 0.3) * (0.2 * 0.5 / 1.0), ); animationGraphEval.setValue('speed', 1.2); animationGraphEval.update(0.2); expect(node.position.x).toBeCloseTo( 0.3 + (1.7 - 0.3) * ((0.2 * 0.5 + 0.2 * 1.2) / 1.0), ); }); }); }); describe('Removing nodes', () => { test('Could not remove special nodes', () => { const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; layerGraph.remove(layerGraph.entryState); layerGraph.remove(layerGraph.exitState); layerGraph.remove(layerGraph.anyState); expect([...layerGraph.states()]).toEqual(expect.arrayContaining([ layerGraph.entryState, layerGraph.exitState, layerGraph.anyState, ])); }); test('Also erase referred transitions', () => { const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; const node1 = layerGraph.addMotion(); const node2 = layerGraph.addMotion(); const node3 = layerGraph.addMotion(); layerGraph.connect(node1, node2); layerGraph.connect(node3, node1); layerGraph.remove(node2); expect([...layerGraph.getOutgoings(node1)]).toHaveLength(0); layerGraph.remove(node3); expect([...layerGraph.getIncomings(node1)]).toHaveLength(0); }); }); describe('Exotic nodes', () => { test('Removed nodes are dangling', () => { const graph = new AnimationGraph(); const layer = graph.addLayer(); const layerGraph = layer.stateMachine; const node = layerGraph.addMotion(); layerGraph.remove(node); expect(() => layerGraph.remove(node)).toThrow(); expect(() => layerGraph.getIncomings(node)).toThrow(); expect(() => layerGraph.connect(layerGraph.entryState, node)).toThrow(); }); test('Nodes in different layers are isolated', () => { const graph = new AnimationGraph(); const layer1 = graph.addLayer(); const layerGraph1 = layer1.stateMachine; const layer2 = graph.addLayer(); const layerGraph2 = layer2.stateMachine; const node1 = layerGraph1.addMotion(); const node2 = layerGraph2.addMotion(); expect(() => layerGraph2.connect(node2, node1)).toThrow(); }); }); describe('Blender 1D', () => { test('Thresholds should have been sorted', () => { const createBlend1DItemWithWeight = (threshold: number) => { const item = new AnimationBlend1D.Item(); item.threshold = threshold; return item; }; const blender1D = new AnimationBlend1D(); blender1D.items = [createBlend1DItemWithWeight(0.3), createBlend1DItemWithWeight(0.2)]; expect([...blender1D.items].map(({ threshold }) => threshold)).toStrictEqual([0.2, 0.3]); blender1D.items = [createBlend1DItemWithWeight(0.9), createBlend1DItemWithWeight(-0.2)]; expect([...blender1D.items].map(({ threshold }) => threshold)).toStrictEqual([-0.2, 0.9]); }); test('1D Blending', () => { const thresholds = [0.1, 0.3] as const; const weights = new Array<number>(thresholds.length).fill(0); blend1D(weights, thresholds, 0.4); expect(weights).toBeDeepCloseTo([0.0, 1.0]); blend1D(weights, thresholds, 0.1); expect(weights).toBeDeepCloseTo([1.0, 0.0]); blend1D(weights, thresholds, 0.3); expect(weights).toBeDeepCloseTo([0.0, 1.0]); blend1D(weights, thresholds, 0.2); expect(weights).toBeDeepCloseTo([0.5, 0.5]); }); }); describe('Variable not found error', () => { test('Missed in conditions', () => { expect(() => createAnimationGraphEval(createGraphFromDescription(gVariableNotFoundInCondition), new Node())).toThrowError(VariableNotDefinedError); }); test('Missed in animation blend', () => { expect(() => createAnimationGraphEval(createGraphFromDescription(gVariableNotFoundInAnimationBlend), new Node())).toThrowError(VariableNotDefinedError); }); }); describe('Variable type mismatch error', () => { test('animation blend requires numbers', () => { expect(() => createAnimationGraphEval(createGraphFromDescription(gAnimationBlendRequiresNumbers), new Node())).toThrowError(VariableTypeMismatchedError); }); }); describe('Property binding', () => { }); }); function createEmptyClipMotion (duration: number, name = '') { const clip = new AnimationClip(); clip.name = name; clip.enableTrsBlending = true; clip.duration = duration; const clipMotion = new ClipMotion(); clipMotion.clip = clip; return clipMotion; } function createClipMotionPositionX(duration: number, value: number, name = '') { const clip = new AnimationClip(); clip.name = name; clip.enableTrsBlending = true; clip.duration = duration; const track = new VectorTrack(); track.componentsCount = 3; track.path.toProperty('position'); track.channels()[0].curve.assignSorted([[0.0, value]]); clip.addTrack(track); const clipMotion = new ClipMotion(); clipMotion.clip = clip; return clipMotion; } function createClipMotionPositionXLinear(duration: number, from: number, to: number, name = '') { const clip = new AnimationClip(); clip.name = name; clip.enableTrsBlending = true; clip.duration = duration; const track = new VectorTrack(); track.componentsCount = 3; track.path.toProperty('position'); track.channels()[0].curve.assignSorted([ [0.0, from], [duration, to], ]); clip.addTrack(track); const clipMotion = new ClipMotion(); clipMotion.clip = clip; return clipMotion; } type MayBeArray<T> = T | T[]; function expectAnimationGraphEvalStatusLayer0 (graphEval: AnimationGraphEval, status: { currentNode?: Parameters<typeof expectStateStatus>[1]; current?: Parameters<typeof expectClipStatuses>[1]; transition?: { time?: number; duration?: number; nextNode?: Parameters<typeof expectStateStatus>[1]; next?: Parameters<typeof expectClipStatuses>[1]; }; }) { if (status.currentNode) { expectStateStatus(graphEval.getCurrentStateStatus(0), status.currentNode); } if (status.current) { const currentClipStatuses = Array.from(graphEval.getCurrentClipStatuses(0)); expectClipStatuses(currentClipStatuses, status.current); } const currentTransition = graphEval.getCurrentTransition(0); if (!status.transition) { expect(currentTransition).toBeNull(); } else { expect(currentTransition).not.toBeNull(); if (typeof status.transition.time === 'number') { expect(currentTransition.time).toBeCloseTo(status.transition.time, 5); } if (typeof status.transition.duration === 'number') { expect(currentTransition.duration).toBeCloseTo(status.transition.duration, 5); } if (status.transition.nextNode) { expectStateStatus(graphEval.getNextStateStatus(0), status.transition.nextNode); } if (status.transition.next) { expectClipStatuses(Array.from(graphEval.getNextClipStatuses(0)), status.transition.next); } } } function expectStateStatus (stateStatus: Readonly<StateStatus> | null, expected: null | { __DEBUG_ID__?: string; }) { if (!expected) { expect(stateStatus).toBeNull(); } else { expect(stateStatus).not.toBeNull(); expect(stateStatus.__DEBUG_ID__).toBe(expected.__DEBUG_ID__); } } function expectClipStatuses (clipStatuses: ClipStatus[], expected: MayBeArray<{ clip?: AnimationClip; weight?: number; }>) { const expects = Array.isArray(expected) ? expected : [expected]; expect(clipStatuses).toHaveLength(expects.length); for (let i = 0; i < expects.length; ++i) { const { clip, weight = 1.0 } = expects[i]; if (clip) { expect(clipStatuses[i].clip).toBe(clip); } expect(clipStatuses[i].weight).toBeCloseTo(weight, 5); } } function createAnimationGraphEval (animationGraph: AnimationGraph, node: Node): AnimationGraphEval { const newGenAnim = node.addComponent(AnimationController) as AnimationController; const graphEval = new AnimationGraphEval( animationGraph, node, newGenAnim, ); // @ts-expect-error HACK newGenAnim._graphEval = graphEval; return graphEval; } function createAnimationGraphEval2 (animationGraph: AnimationGraph, node: Node) { const newGenAnim = node.addComponent(AnimationController) as AnimationController; const graphEval = new AnimationGraphEval( animationGraph, node, newGenAnim, ); // @ts-expect-error HACK newGenAnim._graphEval = graphEval; return { graphEval, newGenAnim, }; }
the_stack
// Arrays of colours should have pillar colors first // e.g. for sport: // const [sport300, sport400, sport500, sport600, sport800] = colors.blue const colors = { reds: [ '#660505', //news-100 '#8B0000', //news-200 '#AB0613', //news-300 '#C70000', //news-400, error-400 '#FF5943', //news-500 '#FF9081', //news-550, error-500 '#FFBAC8', //news-600 '#FFF4F2', //news-800 ], oranges: [ '#672005', //opinion-100 '#8D2700', //opinion-200 '#C74600', //opinion-300 '#E05E00', //opinion-400 '#FF7F0F', //opinion-500 '#FF9941', //opinion-550 '#F9B376', //opinion-600 '#FEF9F5', //opinion-800 ], blues: [ '#003C60', //sport-100 '#004E7C', //sport-200 '#005689', //sport-300 '#0077B6', //sport-400 '#00B2FF', //sport-500 '#90DCFF', //sport-600 '#F1F8FC', //sport-800 '#001536', //brand-100 '#041F4A', //brand-300 '#052962', //brand-400 '#007ABC', //brand-500 '#506991', //brand-600 '#C1D8FC', //brand-800 '#0093E0', //focus-400 ], browns: [ '#2B2625', //culture-50 '#3E3323', //culture-100 '#574835', //culture-200 '#6B5840', //culture-300 '#866D50', //culture-350 '#A1845C', //culture-400 '#EACCA0', //culture-500 '#E7D4B9', //culture-600 '#EFE8DD', //culture-700 '#FBF6EF', //culture-800 ], pinks: [ '#510043', //lifestyle-100 '#650054', //lifestyle-200 '#7D0068', //lifestyle-300 '#BB3B80', //lifestyle-400 '#FFABDB', //lifestyle-500 '#FEC8D3', //lifestyle-600 '#FEEEF7', //lifestyle-800 ], yellows: [ '#F3C100', //brandAlt-200 '#FFD900', //brandAlt-300 '#FFE500', //brandAlt-400 ], greens: [ '#185E36', //green-300 '#22874D', //green-400, success-400 '#58D08B', //green-500, success-500 '#4B8878', //labs-200 '#65A897', //labs-300 '#69D1CA', //labs-400 ], grays: [ '#000000', //neutral-0 '#121212', //neutral-7 '#1A1A1A', //neutral-10 '#333333', //neutral-20 '#707070', //neutral-46 '#999999', //neutral-60 '#DCDCDC', //neutral-86 '#EDEDED', //neutral-93 '#F6F6F6', //neutral-97 '#FFFFFF', //neutral-100 '#222527', //specialReport-100 '#303538', //specialReport-200 '#3F464A', //specialReport-300 '#595C5F', //specialReport-400 '#9DA0A2', //specialReport-450 '#ABC2C9', //specialReport-500 '#E4E5E8', //specialReport-700 '#EFF1F2', //specialReport-800 ], } as const; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/66411c) * * Our core brand colour – `brand[400]` – and extended brand colours */ export const brand = { 100: colors.blues[7], 300: colors.blues[8], 400: colors.blues[9], 500: colors.blues[10], 600: colors.blues[11], 800: colors.blues[12], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/32d461) * * Our alternative brand colours */ export const brandAlt = { 200: colors.yellows[0], 300: colors.yellows[1], 400: colors.yellows[2], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/70dd5c) * * Neutral colours */ export const neutral = { 0: colors.grays[0], 7: colors.grays[1], 10: colors.grays[2], 20: colors.grays[3], 46: colors.grays[4], 60: colors.grays[5], 86: colors.grays[6], 93: colors.grays[7], 97: colors.grays[8], 100: colors.grays[9], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/98b901) * * Error colours */ export const error = { 400: colors.reds[3], 500: colors.reds[5], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/82798f) * * Success colours */ export const success = { 400: colors.greens[1], 500: colors.greens[2], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/97d77e) * * News colours */ export const news = { 100: colors.reds[0], 200: colors.reds[1], 300: colors.reds[2], 400: colors.reds[3], 500: colors.reds[4], 550: colors.reds[5], 600: colors.reds[6], 800: colors.reds[7], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/0539ef) * * Opinion colours */ export const opinion = { 100: colors.oranges[0], 200: colors.oranges[1], 300: colors.oranges[2], 400: colors.oranges[3], 500: colors.oranges[4], 550: colors.oranges[5], 600: colors.oranges[6], 800: colors.oranges[7], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/957a45) * * Sport colours */ export const sport = { 100: colors.blues[0], 200: colors.blues[1], 300: colors.blues[2], 400: colors.blues[3], 500: colors.blues[4], 600: colors.blues[5], 800: colors.blues[6], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/068eb2) * * Culture colours */ export const culture = { 50: colors.browns[0], 100: colors.browns[1], 200: colors.browns[2], 300: colors.browns[3], 350: colors.browns[4], 400: colors.browns[5], 500: colors.browns[6], 600: colors.browns[7], 700: colors.browns[8], 800: colors.browns[9], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/2236b4) * * Lifestyle colours */ export const lifestyle = { 100: colors.pinks[0], 200: colors.pinks[1], 300: colors.pinks[2], 400: colors.pinks[3], 500: colors.pinks[4], 600: colors.pinks[5], 800: colors.pinks[6], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/59b08c) * * Labs colours */ export const labs = { 200: colors.greens[3], 300: colors.greens[4], 400: colors.greens[5], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/31c634) * * Special report colours */ export const specialReport = { 100: colors.grays[10], 200: colors.grays[11], 300: colors.grays[12], 400: colors.grays[13], 450: colors.grays[14], 500: colors.grays[15], 700: colors.grays[16], 800: colors.grays[17], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/492a30-light-palette/t/188e86) * * Focus state colour */ export const focus = { 400: colors.blues[13], }; // Hover colours are snowflakes as they are manipulations of colours from the // main palette. /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/9280ee) * * Default theme background colours */ export const background = { primary: neutral[100], secondary: neutral[97], inverse: neutral[10], ctaPrimary: brand[400], ctaPrimaryHover: '#234B8A', ctaSecondary: brand[800], ctaSecondaryHover: '#ACC9F7', ctaTertiaryHover: '#E5E5E5', input: neutral[100], inputChecked: brand[500], } as const; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/63cc10) * * Brand theme background colours */ export const brandBackground = { primary: brand[400], inputChecked: neutral[100], ctaPrimary: neutral[100], ctaPrimaryHover: '#E0E0E0', ctaSecondary: brand[600], ctaSecondaryHover: '#234B8A', ctaTertiaryHover: brand[300], } as const; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/743232) * * Alternative brand theme background colours */ export const brandAltBackground = { primary: brandAlt[400], ctaPrimary: neutral[7], ctaPrimaryHover: '#454545', ctaSecondary: brandAlt[200], ctaSecondaryHover: '#F2AE00', ctaTertiaryHover: '#FFD213', } as const; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/69c92f) * * Default theme border colours */ export const border = { primary: neutral[60], secondary: neutral[86], success: success[400], error: error[400], ctaTertiary: brand[400], input: neutral[60], inputChecked: brand[500], inputHover: brand[500], inputActive: brand[500], focusHalo: focus[400], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/04883b) * * Brand theme border colours */ export const brandBorder = { primary: brand[600], secondary: brand[600], success: success[500], error: error[500], ctaTertiary: neutral[100], input: brand[800], inputChecked: neutral[100], inputHover: neutral[100], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/b/21c6cc) * * Alternative brand theme border colours */ export const brandAltBorder = { ctaTertiary: neutral[7], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/593cc9) * * Default theme line colours */ export const line = { primary: neutral[86], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/66455d) * * Brand theme line colours */ export const brandLine = { primary: brand[600], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/89955e) * * Alternative brand theme line colours */ export const brandAltLine = { primary: neutral[7], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/85d3b0) * * Default theme text colours */ export const text = { primary: neutral[7], supporting: neutral[46], success: success[400], error: error[400], ctaPrimary: neutral[100], ctaSecondary: brand[400], ctaTertiary: brand[400], anchorPrimary: brand[500], anchorSecondary: neutral[7], userInput: neutral[7], inputLabel: neutral[7], inputError: neutral[7], inputLabelSupporting: neutral[46], inputChecked: brand[400], //choice card only inputHover: brand[400], //choice card only groupLabel: neutral[7], groupLabelSupporting: neutral[46], newsInverse: news[550], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/244480) * * Brand theme text colours */ export const brandText = { primary: neutral[100], supporting: brand[800], success: success[500], error: error[500], ctaPrimary: brand[400], ctaSecondary: neutral[100], ctaTertiary: neutral[100], anchorPrimary: neutral[100], anchorPrimaryHover: brandAlt[400], userInput: neutral[100], inputLabel: neutral[100], inputLabelSupporting: brand[800], }; /** * [Storybook](https://guardian.github.io/source/?path=/docs/source-v4-source-foundations-colour--page) • * [Design System](https://theguardian.design/2a1e5182b/p/1377a6-tokens/t/11d5fd) * * Alternative brand theme text colours */ export const brandAltText = { primary: neutral[7], supporting: neutral[60], ctaPrimary: neutral[100], ctaSecondary: neutral[7], ctaTertiary: neutral[7], anchorPrimary: neutral[7], };
the_stack
import { PluginEndpointDiscovery } from '@backstage/backend-common'; import { decodeProtectedHeader, exportJWK, generateKeyPair, SignJWT, } from 'jose'; import { cloneDeep } from 'lodash'; import { rest } from 'msw'; import { setupServer } from 'msw/node'; import { v4 as uuid } from 'uuid'; import { IdentityClient } from './IdentityClient'; interface AnyJWK extends Record<string, string> { use: 'sig'; alg: string; kid: string; kty: string; } // Simplified copy of TokenFactory in @backstage/plugin-auth-backend class FakeTokenFactory { private readonly keys = new Array<AnyJWK>(); constructor( private readonly options: { issuer: string; keyDurationSeconds: number; }, ) {} async issueToken(params: { claims: { sub: string; ent?: string[]; }; }): Promise<string> { const pair = await generateKeyPair('ES256'); const publicKey = await exportJWK(pair.publicKey); const kid = uuid(); publicKey.kid = kid; this.keys.push(publicKey as AnyJWK); const iss = this.options.issuer; const sub = params.claims.sub; const ent = params.claims.ent; const aud = 'backstage'; const iat = Math.floor(Date.now() / 1000); const exp = iat + this.options.keyDurationSeconds; return new SignJWT({ iss, sub, aud, iat, exp, ent, kid }) .setProtectedHeader({ alg: 'ES256', ent: ent, kid: kid }) .setIssuer(iss) .setAudience(aud) .setSubject(sub) .setIssuedAt(iat) .setExpirationTime(exp) .sign(pair.privateKey); } async listPublicKeys(): Promise<{ keys: AnyJWK[] }> { return { keys: this.keys }; } } function jwtKid(jwt: string): string { const header = decodeProtectedHeader(jwt); return header.kid ?? ''; } const server = setupServer(); const mockBaseUrl = 'http://backstage:9191/i-am-a-mock-base'; const discovery: PluginEndpointDiscovery = { async getBaseUrl() { return mockBaseUrl; }, async getExternalBaseUrl() { return mockBaseUrl; }, }; describe('IdentityClient', () => { let client: IdentityClient; let factory: FakeTokenFactory; const keyDurationSeconds = 5; beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); afterAll(() => server.close()); afterEach(() => server.resetHandlers()); beforeEach(() => { client = IdentityClient.create({ discovery, issuer: mockBaseUrl }); factory = new FakeTokenFactory({ issuer: mockBaseUrl, keyDurationSeconds, }); }); describe('identity client configuration', () => { beforeEach(() => { server.use( rest.get( `${mockBaseUrl}/.well-known/jwks.json`, async (_, res, ctx) => { const keys = await factory.listPublicKeys(); return res(ctx.json(keys)); }, ), ); }); it('should defaults to ES256 when no algorithm is supplied', async () => { const identityClient = IdentityClient.create({ discovery, issuer: mockBaseUrl, }); const token = await factory.issueToken({ claims: { sub: 'foo' } }); const response = await identityClient.authenticate(token); // expect that the authenticate is able to validate a token with ES256, which is the one set to FakeTokenFactory. // This means that IdentityClient set ES256 by default. expect(response).toEqual({ token: token, identity: { type: 'user', userEntityRef: 'foo', ownershipEntityRefs: [], }, }); }); it('should throw error on empty algorithms array', async () => { const identityClient = IdentityClient.create({ discovery, issuer: mockBaseUrl, algorithms: [''], }); const token = await factory.issueToken({ claims: { sub: 'foo' } }); return expect( async () => await identityClient.authenticate(token), ).rejects.toThrow(); }); it('should throw error on empty algorithm string', async () => { const identityClient = IdentityClient.create({ discovery, issuer: mockBaseUrl, algorithms: [], }); const token = await factory.issueToken({ claims: { sub: 'foo' } }); return expect( async () => await identityClient.authenticate(token), ).rejects.toThrow(); }); }); describe('authenticate', () => { beforeEach(() => { server.use( rest.get( `${mockBaseUrl}/.well-known/jwks.json`, async (_, res, ctx) => { const keys = await factory.listPublicKeys(); return res(ctx.json(keys)); }, ), ); }); it('should throw on undefined header', async () => { return expect(async () => { await client.authenticate(undefined); }).rejects.toThrow(); }); it('should accept fresh token', async () => { const token = await factory.issueToken({ claims: { sub: 'foo' } }); const response = await client.authenticate(token); expect(response).toEqual({ token: token, identity: { type: 'user', userEntityRef: 'foo', ownershipEntityRefs: [], }, }); }); it('should decode claims correctly', async () => { const token = await factory.issueToken({ claims: { sub: 'foo', ent: ['entity1', 'entity2'] }, }); const response = await client.authenticate(token); expect(response).toEqual({ token: token, identity: { type: 'user', userEntityRef: 'foo', ownershipEntityRefs: ['entity1', 'entity2'], }, }); }); it('should throw on incorrect issuer', async () => { const hackerFactory = new FakeTokenFactory({ issuer: 'hacker', keyDurationSeconds, }); return expect(async () => { const token = await hackerFactory.issueToken({ claims: { sub: 'foo' }, }); await client.authenticate(token); }).rejects.toThrow(); }); it('should throw on expired token', async () => { return expect(async () => { const fixedTime = Date.now(); jest .spyOn(Date, 'now') .mockImplementation(() => fixedTime - keyDurationSeconds * 1000 * 2); const token = await factory.issueToken({ claims: { sub: 'foo' }, }); jest.spyOn(Date, 'now').mockImplementation(() => fixedTime); await client.authenticate(token); }).rejects.toThrow(); }); it('should throw on incorrect signing key', async () => { const hackerFactory = new FakeTokenFactory({ issuer: mockBaseUrl, keyDurationSeconds, }); return expect(async () => { const token = await hackerFactory.issueToken({ claims: { sub: 'foo' }, }); await client.authenticate(token); }).rejects.toThrow(); }); it('should accept token from new key', async () => { const fixedTime = Date.now(); jest .spyOn(Date, 'now') .mockImplementation(() => fixedTime - keyDurationSeconds * 1000 * 2); const token1 = await factory.issueToken({ claims: { sub: 'foo1' } }); try { // This throws as token has already expired await client.authenticate(token1); } catch (_err) { // Ignore thrown error } // Move forward in time where the signing key has been rotated and the // cooldown period to look up a new public key has elapsed. jest .spyOn(Date, 'now') .mockImplementation( () => fixedTime + 30 * keyDurationSeconds * 1000 + 2, ); const token = await factory.issueToken({ claims: { sub: 'foo' } }); const response = await client.authenticate(token); expect(response).toEqual({ token: token, identity: { type: 'user', userEntityRef: 'foo', ownershipEntityRefs: [], }, }); }); it('should not be fooled by the none algorithm', async () => { return expect(async () => { const token = await factory.issueToken({ claims: { sub: 'foo' } }); const header = btoa( JSON.stringify({ alg: 'none', kid: jwtKid(token) }), ); const payload = btoa( JSON.stringify({ iss: mockBaseUrl, sub: 'foo', aud: 'backstage', iat: Date.now() / 1000, exp: Date.now() / 1000 + 60000, }), ); const fakeToken = `${header}.${payload}.`; return await client.authenticate(fakeToken); }).rejects.toThrow(); }); it('should use an updated endpoint when the key is not found', async () => { const updatedURL = 'http://backstage:9191/an-updated-base'; const getBaseUrl = discovery.getBaseUrl; const getExternalBaseUrl = discovery.getExternalBaseUrl; // Generate a key and sign a token with it await factory.issueToken({ claims: { sub: 'foo' } }); // Only return the key from a single token const singleKey = cloneDeep(await factory.listPublicKeys()); server.use( rest.get( `${mockBaseUrl}/.well-known/jwks.json`, async (_, res, ctx) => { return res(ctx.json(singleKey)); }, ), ); // Update the discovery endpoint to point to a new URL discovery.getBaseUrl = async () => { return updatedURL; }; discovery.getExternalBaseUrl = async () => { return updatedURL; }; let calledUpdatedEndpoint = false; server.use( rest.get(`${updatedURL}/.well-known/jwks.json`, async (_, res, ctx) => { const keys = await factory.listPublicKeys(); calledUpdatedEndpoint = true; return res(ctx.json(keys)); }), ); // Advance time const future_11s = Date.now() + 11 * 1000; const dateSpy = jest .spyOn(Date, 'now') .mockImplementation(() => future_11s); // Issue a new token const token = await factory.issueToken({ claims: { sub: 'foo2' } }); const response = await client.authenticate(token); // Verify that the endpoint was updated. expect(calledUpdatedEndpoint).toBeTruthy(); expect(response).toEqual({ token: token, identity: { type: 'user', userEntityRef: 'foo2', ownershipEntityRefs: [], }, }); // Restore the discovery endpoint and time discovery.getBaseUrl = getBaseUrl; discovery.getExternalBaseUrl = getExternalBaseUrl; dateSpy.mockClear(); }); }); });
the_stack
import { Component, DebugElement, NO_ERRORS_SCHEMA, TemplateRef, ViewChild } from '@angular/core'; import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NotifierAnimationData } from '../models/notifier-animation.model'; import { NotifierConfig } from '../models/notifier-config.model'; import { NotifierNotification } from '../models/notifier-notification.model'; import { NotifierConfigToken } from '../notifier.tokens'; import { NotifierService } from '../services/notifier.service'; import { NotifierAnimationService } from '../services/notifier-animation.service'; import { NotifierTimerService } from '../services/notifier-timer.service'; import { NotifierNotificationComponent } from './notifier-notification.component'; /** * Notifier Notification Component - Unit Test */ describe('Notifier Notification Component', () => { const fakeAnimation: any = { onfinish: () => null, // We only need this property to be actually mocked away }; const testNotification: NotifierNotification = new NotifierNotification({ id: 'ID_FAKE', message: 'Lorem ipsum dolor sit amet.', type: 'SUCCESS', }); let componentFixture: ComponentFixture<NotifierNotificationComponent>; let componentInstance: NotifierNotificationComponent; let timerService: MockNotifierTimerService; it('should instantiate', () => { // Setup test module beforeEachWithConfig(new NotifierConfig()); expect(componentInstance).toBeDefined(); }); describe('(render)', () => { it('should render', () => { // Setup test module beforeEachWithConfig(new NotifierConfig()); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Check the calculated values expect(componentInstance.getConfig()).toEqual(new NotifierConfig()); expect(componentInstance.getHeight()).toBe(componentFixture.nativeElement.offsetHeight); expect(componentInstance.getWidth()).toBe(componentFixture.nativeElement.offsetWidth); expect(componentInstance.getShift()).toBe(0); // Check the template const messageElement: DebugElement = componentFixture.debugElement.query(By.css('.notifier__notification-message')); expect(messageElement.nativeElement.textContent).toContain(componentInstance.notification.message); const dismissButtonElement: DebugElement = componentFixture.debugElement.query(By.css('.notifier__notification-button')); expect(dismissButtonElement).not.toBeNull(); // Check the class names const classNameType = `notifier__notification--${componentInstance.notification.type}`; expect(componentFixture.nativeElement.classList.contains(classNameType)).toBeTruthy(); const classNameTheme = `notifier__notification--${componentInstance.getConfig().theme}`; expect(componentFixture.nativeElement.classList.contains(classNameTheme)).toBeTruthy(); }); it('should render the custom template if provided by the user', async(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ position: { horizontal: { distance: 10, position: 'left', }, vertical: { distance: 10, gap: 4, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig, false); const template = `<ng-template #tpl let-notificationData="notification"><div class="custom-notification-body">{{notificationData.message}}</div></ng-template>`; const testcmp = createTestComponent(template); // associate the templateref const myTestNotification = { ...testNotification, template: testcmp.componentInstance.currentTplRef, }; expect(testcmp.componentInstance.currentTplRef).toBeDefined(); componentFixture = TestBed.createComponent(NotifierNotificationComponent); componentInstance = componentFixture.componentInstance; componentInstance.notification = myTestNotification; componentFixture.detectChanges(); // // assert expect(componentFixture.debugElement.query(By.css('div.custom-notification-body'))).not.toBeNull(); expect(componentFixture.debugElement.query(By.css('div.custom-notification-body')).nativeElement.innerHTML).toBe( myTestNotification.message, ); })); it('should render on the left', () => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ position: { horizontal: { distance: 10, position: 'left', }, vertical: { distance: 10, gap: 4, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Check position expect(componentFixture.debugElement.styles['left']).toBe(`${testNotifierConfig.position.horizontal.distance}px`); }); it('should render on the right', () => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ position: { horizontal: { distance: 10, position: 'right', }, vertical: { distance: 10, gap: 4, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Check position expect(componentFixture.debugElement.styles['right']).toBe(`${testNotifierConfig.position.horizontal.distance}px`); }); it('should render in the middle', () => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ position: { horizontal: { distance: 10, position: 'middle', }, vertical: { distance: 10, gap: 4, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Check position expect(componentFixture.debugElement.styles['left']).toBe('50%'); expect(componentFixture.debugElement.styles['transform']).toBe('translate3d( -50%, 0, 0 )'); }); it('should render on the top', () => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ position: { horizontal: { distance: 10, position: 'left', }, vertical: { distance: 10, gap: 4, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Check position expect(componentFixture.debugElement.styles['top']).toBe(`${testNotifierConfig.position.vertical.distance}px`); }); it('should render on the bottom', () => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ position: { horizontal: { distance: 10, position: 'left', }, vertical: { distance: 10, gap: 4, position: 'bottom', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Check position expect(componentFixture.debugElement.styles['bottom']).toBe(`${testNotifierConfig.position.vertical.distance}px`); }); }); describe('(show)', () => { it('should show', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, }, }), ); componentInstance.notification = testNotification; componentFixture.detectChanges(); const showCallback = jest.fn(); componentInstance.show().then(showCallback); tick(); expect(componentFixture.debugElement.styles['visibility']).toBe('visible'); expect(showCallback).toHaveBeenCalled(); })); it('should show (with animations)', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ behaviour: { autoHide: false, }, }), ); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Mock away the Web Animations API jest.spyOn(componentFixture.nativeElement, 'animate').mockImplementation(() => { componentFixture.debugElement.styles['opacity'] = '1'; // Fake animation result return fakeAnimation; }); const showCallback = jest.fn(); componentInstance.show().then(showCallback); fakeAnimation.onfinish(); tick(); expect(componentFixture.debugElement.styles['visibility']).toBe('visible'); expect(componentFixture.debugElement.styles['opacity']).toBe('1'); expect(showCallback).toHaveBeenCalled(); })); }); describe('(hide)', () => { it('should hide', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, }, }), ); componentInstance.notification = testNotification; componentFixture.detectChanges(); const hideCallback = jest.fn(); componentInstance.hide().then(hideCallback); tick(); expect(hideCallback).toHaveBeenCalled(); })); it('should hide (with animations)', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ behaviour: { autoHide: false, }, }), ); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Mock away the Web Animations API jest.spyOn(componentFixture.nativeElement, 'animate').mockImplementation(() => { componentFixture.debugElement.styles['opacity'] = '0'; // Fake animation result return fakeAnimation; }); const hideCallback = jest.fn(); componentInstance.hide().then(hideCallback); fakeAnimation.onfinish(); tick(); expect(componentFixture.debugElement.styles['opacity']).toBe('0'); expect(hideCallback).toHaveBeenCalled(); })); }); describe('(shift)', () => { it('should shift to make place on top', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, }, position: { horizontal: { distance: 12, position: 'left', }, vertical: { distance: 12, gap: 10, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); const shiftCallback = jest.fn(); const shiftDistance = 100; componentInstance.shift(shiftDistance, true).then(shiftCallback); tick(); expect(componentFixture.debugElement.styles['transform']).toBe( `translate3d( 0, ${shiftDistance + testNotifierConfig.position.vertical.gap}px, 0 )`, ); expect(shiftCallback).toHaveBeenCalled(); })); it('should shift to make place on top (with animations)', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ behaviour: { autoHide: false, }, position: { horizontal: { distance: 12, position: 'left', }, vertical: { distance: 12, gap: 10, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); const shiftDistance = 100; // Mock away the Web Animations API jest.spyOn(componentFixture.nativeElement, 'animate').mockImplementation(() => { componentFixture.debugElement.styles['transform'] = `translate3d( 0, ${ shiftDistance + testNotifierConfig.position.vertical.gap }px, 0 )`; // Fake animation result return fakeAnimation; }); const shiftCallback = jest.fn(); componentInstance.shift(shiftDistance, true).then(shiftCallback); fakeAnimation.onfinish(); tick(); expect(componentFixture.debugElement.styles['transform']).toBe( `translate3d( 0, ${shiftDistance + testNotifierConfig.position.vertical.gap}px, 0 )`, ); expect(shiftCallback).toHaveBeenCalled(); })); it('should shift to make place on bottom', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, }, position: { horizontal: { distance: 12, position: 'left', }, vertical: { distance: 12, gap: 10, position: 'bottom', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); const shiftCallback = jest.fn(); const shiftDistance = 100; componentInstance.shift(shiftDistance, true).then(shiftCallback); tick(); expect(componentFixture.debugElement.styles['transform']).toBe( `translate3d( 0, ${-shiftDistance - testNotifierConfig.position.vertical.gap}px, 0 )`, ); expect(shiftCallback).toHaveBeenCalled(); })); it('should shift to make place on bottom (with animations)', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ behaviour: { autoHide: false, }, position: { horizontal: { distance: 12, position: 'left', }, vertical: { distance: 12, gap: 10, position: 'bottom', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Mock away the Web Animations API const shiftDistance = 100; jest.spyOn(componentFixture.nativeElement, 'animate').mockImplementation(() => { componentFixture.debugElement.styles['transform'] = `translate3d( 0, ${ -shiftDistance - testNotifierConfig.position.vertical.gap }px, 0 )`; // Fake animation result return fakeAnimation; }); const shiftCallback = jest.fn(); componentInstance.shift(shiftDistance, true).then(shiftCallback); fakeAnimation.onfinish(); tick(); expect(componentFixture.debugElement.styles['transform']).toBe( `translate3d( 0, ${-shiftDistance - testNotifierConfig.position.vertical.gap}px, 0 )`, ); expect(shiftCallback).toHaveBeenCalled(); })); it('should shift to fill place on top', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, }, position: { horizontal: { distance: 12, position: 'left', }, vertical: { distance: 12, gap: 10, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); const shiftCallback = jest.fn(); const shiftDistance = 100; componentInstance.shift(shiftDistance, false).then(shiftCallback); tick(); expect(componentFixture.debugElement.styles['transform']).toBe( `translate3d( 0, ${-shiftDistance - testNotifierConfig.position.vertical.gap}px, 0 )`, ); expect(shiftCallback).toHaveBeenCalled(); })); it('should shift to fill place on top (with animations)', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ behaviour: { autoHide: false, }, position: { horizontal: { distance: 12, position: 'left', }, vertical: { distance: 12, gap: 10, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Mock away the Web Animations API const shiftDistance = 100; jest.spyOn(componentFixture.nativeElement, 'animate').mockImplementation(() => { componentFixture.debugElement.styles['transform'] = `translate3d( 0, ${ -shiftDistance - testNotifierConfig.position.vertical.gap }px, 0 )`; // Fake animation result return fakeAnimation; }); const shiftCallback = jest.fn(); componentInstance.shift(shiftDistance, false).then(shiftCallback); fakeAnimation.onfinish(); tick(); expect(componentFixture.debugElement.styles['transform']).toBe( `translate3d( 0, ${0 - shiftDistance - testNotifierConfig.position.vertical.gap}px, 0 )`, ); expect(shiftCallback).toHaveBeenCalled(); })); it('should shift to fill place on bottom', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, }, position: { horizontal: { distance: 12, position: 'left', }, vertical: { distance: 12, gap: 10, position: 'bottom', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); const shiftCallback = jest.fn(); const shiftDistance = 100; componentInstance.shift(shiftDistance, false).then(shiftCallback); tick(); expect(componentFixture.debugElement.styles['transform']).toBe( `translate3d( 0, ${shiftDistance + testNotifierConfig.position.vertical.gap}px, 0 )`, ); expect(shiftCallback).toHaveBeenCalled(); })); it('should shift to fill place on bottom (with animations)', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ behaviour: { autoHide: false, }, position: { horizontal: { distance: 12, position: 'left', }, vertical: { distance: 12, gap: 10, position: 'bottom', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Mock away the Web Animations API const shiftDistance = 100; jest.spyOn(componentFixture.nativeElement, 'animate').mockImplementation(() => { componentFixture.debugElement.styles['transform'] = `translate3d( 0, ${ shiftDistance + testNotifierConfig.position.vertical.gap }px, 0 )`; // Fake animation result return fakeAnimation; }); const shiftCallback = jest.fn(); componentInstance.shift(shiftDistance, false).then(shiftCallback); fakeAnimation.onfinish(); tick(); expect(componentFixture.debugElement.styles['transform']).toBe( `translate3d( 0, ${shiftDistance + testNotifierConfig.position.vertical.gap}px, 0 )`, ); expect(shiftCallback).toHaveBeenCalled(); })); it('should shift to make place in the middle', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, }, position: { horizontal: { distance: 12, position: 'middle', }, vertical: { distance: 12, gap: 10, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); const shiftCallback = jest.fn(); const shiftDistance = 100; componentInstance.shift(shiftDistance, true).then(shiftCallback); tick(); expect(componentFixture.debugElement.styles['transform']).toBe( `translate3d( -50%, ${shiftDistance + testNotifierConfig.position.vertical.gap}px, 0 )`, ); expect(shiftCallback).toHaveBeenCalled(); })); it('should shift to make place in the middle (with animations)', fakeAsync(() => { // Setup test module const testNotifierConfig: NotifierConfig = new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, }, position: { horizontal: { distance: 12, position: 'middle', }, vertical: { distance: 12, gap: 10, position: 'top', }, }, }); beforeEachWithConfig(testNotifierConfig); componentInstance.notification = testNotification; componentFixture.detectChanges(); // Mock away the Web Animations API const shiftDistance = 100; jest.spyOn(componentFixture.nativeElement, 'animate').mockImplementation(() => { componentFixture.debugElement.styles['transform'] = `translate3d( -50%, ${ shiftDistance + testNotifierConfig.position.vertical.gap }px, 0 )`; // Fake animation result return fakeAnimation; }); const shiftCallback = jest.fn(); componentInstance.shift(shiftDistance, true).then(shiftCallback); fakeAnimation.onfinish(); tick(); expect(componentFixture.debugElement.styles['transform']).toBe( `translate3d( -50%, ${shiftDistance + testNotifierConfig.position.vertical.gap}px, 0 )`, ); expect(shiftCallback).toHaveBeenCalled(); })); }); describe('(behaviour)', () => { it('should hide automatically after timeout', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: 5000, }, }), ); componentInstance.notification = testNotification; componentFixture.detectChanges(); componentInstance.show(); jest.spyOn(componentInstance, 'onClickDismiss'); tick(); timerService.finishManually(); tick(); expect(componentInstance.onClickDismiss).toHaveBeenCalled(); })); it('should hide after clicking the dismiss button', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, showDismissButton: true, }, }), ); componentInstance.notification = testNotification; componentFixture.detectChanges(); componentInstance.show(); jest.spyOn(componentInstance, 'onClickDismiss'); const dismissButtonElement: DebugElement = componentFixture.debugElement.query(By.css('.notifier__notification-button')); dismissButtonElement.nativeElement.click(); // Emulate click event componentFixture.detectChanges(); expect(componentInstance.onClickDismiss).toHaveBeenCalled(); })); it('should hide after clicking on the notification', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, onClick: 'hide', }, }), ); componentInstance.notification = testNotification; componentFixture.detectChanges(); componentInstance.show(); jest.spyOn(componentInstance, 'onClickDismiss'); componentFixture.nativeElement.click(); // Emulate click event componentFixture.detectChanges(); expect(componentInstance.onClickDismiss).toHaveBeenCalled(); })); it('should not hide after clicking on the notification', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: false, onClick: false, }, }), ); componentInstance.notification = testNotification; componentFixture.detectChanges(); componentInstance.show(); jest.spyOn(componentInstance, 'onClickDismiss'); componentFixture.nativeElement.click(); // Emulate click event componentFixture.detectChanges(); expect(componentInstance.onClickDismiss).not.toHaveBeenCalled(); })); it('should pause the autoHide timer on mouseover, and resume again on mouseout', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: 5000, onMouseover: 'pauseAutoHide', }, }), ); componentInstance.notification = testNotification; componentFixture.detectChanges(); componentInstance.show(); jest.spyOn(componentInstance, 'onClickDismiss'); jest.spyOn(timerService, 'pause'); jest.spyOn(timerService, 'continue'); componentInstance.onNotificationMouseover(); expect(timerService.pause).toHaveBeenCalled(); componentInstance.onNotificationMouseout(); expect(timerService.continue).toHaveBeenCalled(); timerService.finishManually(); tick(); expect(componentInstance.onClickDismiss).toHaveBeenCalled(); })); it('should restart the autoHide timer on mouseover', fakeAsync(() => { // Setup test module beforeEachWithConfig( new NotifierConfig({ animations: { enabled: false, }, behaviour: { autoHide: 5000, onMouseover: 'resetAutoHide', }, }), ); componentInstance.notification = testNotification; componentFixture.detectChanges(); componentInstance.show(); jest.spyOn(componentInstance, 'onClickDismiss'); jest.spyOn(timerService, 'stop'); jest.spyOn(timerService, 'start'); componentInstance.onNotificationMouseover(); expect(timerService.stop).toHaveBeenCalled(); componentInstance.onNotificationMouseout(); expect(timerService.start).toHaveBeenCalled(); timerService.finishManually(); tick(); expect(componentInstance.onClickDismiss).toHaveBeenCalled(); })); }); /** * Helper for upfront configuration */ function beforeEachWithConfig(testNotifierConfig: NotifierConfig, extractServices = true): void { TestBed.configureTestingModule({ declarations: [NotifierNotificationComponent, TestComponent], providers: [ { provide: NotifierService, useValue: { getConfig: () => testNotifierConfig, }, }, { // No idea why this is *actually* necessary -- it shouldn't be ... provide: NotifierConfigToken, useValue: {}, }, { provide: NotifierAnimationService, useClass: MockNotifierAnimationService, }, ], }).overrideComponent(NotifierNotificationComponent, { set: { providers: [ // Override component-specific providers { provide: NotifierTimerService, useClass: MockNotifierTimerService, }, ], }, }); if (extractServices) { componentFixture = TestBed.createComponent(NotifierNotificationComponent); componentInstance = componentFixture.componentInstance; // Get the service from the component's local injector timerService = <MockNotifierTimerService>componentFixture.debugElement.injector.get(NotifierTimerService); } } }); /** * Mock notifier animation service, always returning the animation */ class MockNotifierAnimationService extends NotifierAnimationService { /** * Get animation data * * @param {'show' | 'hide'} direction Animation direction, either in or out * @returns {NotifierAnimationData} Animation information * * @override */ public getAnimationData(direction: 'show' | 'hide'): NotifierAnimationData { if (direction === 'show') { return { keyframes: [ { opacity: '0', }, { opacity: '1', }, ], options: { duration: 300, easing: 'ease', fill: 'forwards', }, }; } else { return { keyframes: [ { opacity: '1', }, { opacity: '0', }, ], options: { duration: 300, easing: 'ease', fill: 'forwards', }, }; } } } /** * Mock Notifier Timer Service */ class MockNotifierTimerService extends NotifierTimerService { /** * Temp resolve function * * @override */ private resolveFunction: () => void; /** * Start (or resume) the timer - doing nothing here * * @param {number} duration Timer duration, in ms * @returns {Promise<undefined>} Promise, resolved once the timer finishes * * @override */ public start(): Promise<void> { return new Promise<void>((resolve: () => void) => { this.resolveFunction = resolve; }); } /** * Pause the timer - doing nothing here */ public pause(): void { // Do nothing } /** * Continue the timer - doing nothing here */ public continue(): void { // Do nothing } /** * Stop the timer - doing nothing here */ public stop(): void { // Do nothing } /** * Finish the timer manually, from outside */ public finishManually(): void { this.resolveFunction(); } } @Component({ selector: 'test-cmp', template: '' }) class TestComponent { @ViewChild('tpl', { static: true }) currentTplRef: TemplateRef<any>; } function createTestComponent(template: string): ComponentFixture<TestComponent> { return TestBed.overrideComponent(TestComponent, { set: { template: template } }) .configureTestingModule({ schemas: [NO_ERRORS_SCHEMA] }) .createComponent(TestComponent); }
the_stack
declare namespace core { function seed(value: number | string): void; function float(max: number): number; function float(min: number, max: number): number; // tslint:disable-line unified-signatures function float(min: number, max: number, n: number): number[]; function int(max: number): number; function int(min: number, max: number): number; // tslint:disable-line unified-signatures function int(min: number, max: number, n: number): number[]; function choice(): undefined; function choice<T>(values: ReadonlyArray<T>): T; function choice<T>(values: ReadonlyArray<T>, n: number): T[]; function char(): undefined; function char(values: string): string; function char(values: string, n: number): string[]; function shuffle<T>(values: ReadonlyArray<T>): T[]; function coin<T, U>(head: T, tail: U, p?: number): T | U; function coin<T, U>(head: T, tail: U, p: number, n: number): Array<T | U>; } declare namespace _dist { const stateBrand: unique symbol; interface State<T> { [stateBrand]: T; } interface Distribution<T> { type(): 'discrete' | 'continuous'; support(): Array<{ value: number; closed: boolean; }>; seed(value: number | string): this; save(): State<T>; load(state: State<T>): this; sample(): number; sample(n: number): number[]; pdf(x: number): number; cdf(x: number): number; q(p: number): number | undefined; survival(x: number): number; hazard(x: number): number; cHazard(x: number): number; logPdf(x: number): number; lnL(data: readonly number[]): number; aic(data: readonly number[]): number; bic(data: readonly number[]): number; test( values: readonly number[], ): { statistics: number; passed: boolean; }; } abstract class Distribution<T> {} } declare namespace dist { type State<T> = _dist.State<T>; type Distribution<T = any> = _dist.Distribution<T>; class Alpha extends _dist.Distribution<'Alpha'> { constructor(alpha?: number); } class Anglit extends _dist.Distribution<'Anglit'> {} class Arcsine extends _dist.Distribution<'Arcsine'> { constructor(a?: number, b?: number); } class BaldingNichols extends _dist.Distribution<'BaldingNichols'> { constructor(F?: number, p?: number); } class Bates extends _dist.Distribution<'Bates'> { constructor(n?: number, a?: number, b?: number); } class Benini extends _dist.Distribution<'Benini'> { constructor(alpha?: number, beta?: number, sigma?: number); } class BenktanderII extends _dist.Distribution<'BenktanderII'> { constructor(a?: number, b?: number); } class Bernoulli extends _dist.Distribution<'Bernoulli'> { constructor(p?: number); } class BetaBinomial extends _dist.Distribution<'BetaBinomial'> { constructor(n?: number, alpha?: number, beta?: number); } class BetaPrime extends _dist.Distribution<'BetaPrime'> { constructor(alpha?: number, beta?: number); } class BetaRectangular extends _dist.Distribution<'BetaRectangular'> { constructor(alpha?: number, beta?: number, theta?: number, a?: number, b?: number); } class Beta extends _dist.Distribution<'Beta'> { constructor(alpha?: number, beta?: number); } class Binomial extends _dist.Distribution<'Binomial'> { constructor(n?: number, p?: number); } class BirnbaumSaunders extends _dist.Distribution<'BirnbaumSaunders'> { constructor(mu?: number, beta?: number, gamma?: number); } class BorelTanner extends _dist.Distribution<'BorelTanner'> { constructor(mu?: number, n?: number); } class Borel extends _dist.Distribution<'Borel'> { constructor(mu?: number); } class BoundedPareto extends _dist.Distribution<'BoundedPareto'> { constructor(L?: number, H?: number, alpha?: number); } class Bradford extends _dist.Distribution<'Bradford'> { constructor(c?: number); } class Burr extends _dist.Distribution<'Burr'> { constructor(c?: number, k?: number); } class Categorical extends _dist.Distribution<'Categorical'> { constructor(weights?: readonly number[], min?: number); } class Cauchy extends _dist.Distribution<'Cauchy'> { constructor(x0?: number, gamma?: number); } class Chi extends _dist.Distribution<'Chi'> { constructor(k?: number); } class Chi2 extends _dist.Distribution<'Chi2'> { constructor(k?: number); } class Dagum extends _dist.Distribution<'Dagum'> { constructor(p?: number, a?: number, b?: number); } class Degenerate extends _dist.Distribution<'Degenerate'> { constructor(x0?: number); } class Delaporte extends _dist.Distribution<'Delaporte'> { constructor(alpha?: number, beta?: number, lambda?: number); } class DiscreteUniform extends _dist.Distribution<'DiscreteUniform'> { constructor(xmin?: number, xmax?: number); } class DiscreteWeibull extends _dist.Distribution<'DiscreteWeibull'> { constructor(q?: number, beta?: number); } class DoubleGamma extends _dist.Distribution<'DoubleGamma'> { constructor(alpha?: number, beta?: number); } class DoubleWeibull extends _dist.Distribution<'DoubleWeibull'> { constructor(lambda?: number, k?: number); } class DoublyNoncentralBeta extends _dist.Distribution<'DoublyNoncentralBeta'> { constructor(alpha?: number, meta?: number, lambda1?: number, lambda2?: number); } class DoublyNoncentralF extends _dist.Distribution<'DoublyNoncentralF'> { constructor(d1?: number, d2?: number, lambda1?: number, lambda2?: number); } class DoublyNoncentralT extends _dist.Distribution<'DoublyNoncentralT'> { constructor(nu?: number, mu?: number, theta?: number); } class Erlang extends _dist.Distribution<'Erlang'> { constructor(k?: number, lambda?: number); } class ExponentialLogarithmic extends _dist.Distribution<'ExponentialLogarithmic'> { constructor(p?: number, beta?: number); } class Exponential extends _dist.Distribution<'Exponential'> { constructor(lambda?: number); } class F extends _dist.Distribution<'F'> { constructor(d1?: number, d2?: number); } class FlorySchulz extends _dist.Distribution<'FlorySchulz'> { constructor(a?: number); } class Frechet extends _dist.Distribution<'Frechet'> { constructor(alpha?: number, s?: number, m?: number); } class FisherZ extends _dist.Distribution<'FisherZ'> { constructor(d1?: number, d2?: number); } class Gamma extends _dist.Distribution<'Gamma'> { constructor(alpha?: number, beta?: number); } class GammaGompertz extends _dist.Distribution<'GammaGompertz'> { constructor(b?: number, s?: number, beta?: number); } class GeneralizedExponential extends _dist.Distribution<'GeneralizedExponential'> { constructor(a?: number, b?: number, c?: number); } class GeneralizedExtremeValue extends _dist.Distribution<'GeneralizedExtremeValue'> { constructor(c?: number); } class GeneralizedGamma extends _dist.Distribution<'GeneralizedGamma'> { constructor(a?: number, d?: number, p?: number); } class GeneralizedHermite extends _dist.Distribution<'GeneralizedHermite'> { constructor(a1?: number, am?: number, m?: number); } class GeneralizedLogistic extends _dist.Distribution<'GeneralizedLogistic'> { constructor(mu?: number, s?: number, c?: number); } class GeneralizedNormal extends _dist.Distribution<'GeneralizedNormal'> { constructor(mu?: number, alpha?: number, beta?: number); } class GeneralizedPareto extends _dist.Distribution<'GeneralizedPareto'> { constructor(mu?: number, sigma?: number, xi?: number); } class Geometric extends _dist.Distribution<'Geometric'> { constructor(p?: number); } class Gilbrat extends _dist.Distribution<'Gilbrat'> { constructor(); } class Gompertz extends _dist.Distribution<'Gompertz'> { constructor(eta?: number, beta?: number); } class Gumbel extends _dist.Distribution<'Gumbel'> { constructor(mu?: number, beta?: number); } class HalfGeneralizedNormal extends _dist.Distribution<'HalfGeneralizedNormal'> { constructor(alpha?: number, beta?: number); } class HalfLogistic extends _dist.Distribution<'HalfLogistic'> { constructor(); } class HalfNormal extends _dist.Distribution<'HalfNormal'> { constructor(sigma?: number); } class HeadsMinusTails extends _dist.Distribution<'HeadsMinusTails'> { constructor(n?: number); } class Hoyt extends _dist.Distribution<'Hoyt'> { constructor(q?: number, omega?: number); } class HyperbolicSecant extends _dist.Distribution<'HyperbolicSecant'> { constructor(); } class Hyperexponential extends _dist.Distribution<'Hyperexponential'> { constructor(parameters?: Array<{ weight: number; rate: number }>); } class Hypergeometric extends _dist.Distribution<'Hypergeometric'> { constructor(N?: number, K?: number, n?: number); } class InverseChi2 extends _dist.Distribution<'InverseChi'> { constructor(nu?: number); } class InverseGamma extends _dist.Distribution<'InverseGamma'> { constructor(alpha?: number, beta?: number); } class InverseGaussian extends _dist.Distribution<'InverseGaussian'> { constructor(mu?: number, lambda?: number); } class InvertedWeibull extends _dist.Distribution<'InvertedWeibull'> { constructor(c?: number); } class IrwinHall extends _dist.Distribution<'IrwinHall'> { constructor(n?: number); } class JohnsonSB extends _dist.Distribution<'JohnsonSB'> { constructor(gamma?: number, delta?: number, lambda?: number, xi?: number); } class JohnsonSU extends _dist.Distribution<'JohnsonSU'> { constructor(gamma?: number, delta?: number, lambda?: number, xi?: number); } class Kumaraswamy extends _dist.Distribution<'Kumaraswamy'> { constructor(alpha?: number, beta?: number); } class Laplace extends _dist.Distribution<'Laplace'> { constructor(mu?: number, b?: number); } class Levy extends _dist.Distribution<'Levy'> { constructor(mu?: number, c?: number); } class Lindley extends _dist.Distribution<'Lindley'> { constructor(theta?: number); } class Logarithmic extends _dist.Distribution<'Logarithmic'> { constructor(a?: number, b?: number); } class LogCauchy extends _dist.Distribution<'LogCauchy'> { constructor(mu?: number, sigma?: number); } class LogGamma extends _dist.Distribution<'LogGamma'> { constructor(alpha?: number, beta?: number, mu?: number); } class Logistic extends _dist.Distribution<'Logistic'> { constructor(mu?: number, s?: number); } class LogisticExponential extends _dist.Distribution<'LogisticExponential'> { constructor(lambda?: number, kappa?: number); } class LogitNormal extends _dist.Distribution<'LogitNormal'> { constructor(mu?: number, sigma?: number); } class LogLaplace extends _dist.Distribution<'LogLaplace'> { constructor(mu?: number, b?: number); } class LogLogistic extends _dist.Distribution<'LogLogistic'> { constructor(alpha?: number, beta?: number); } class LogNormal extends _dist.Distribution<'LogNormal'> { constructor(mu?: number, sigma?: number); } class LogSeries extends _dist.Distribution<'LogSeries'> { constructor(p?: number); } class Lomax extends _dist.Distribution<'Lomax'> { constructor(lambda?: number, alpha?: number); } class Makeham extends _dist.Distribution<'Makeham'> { constructor(alpha?: number, beta?: number, lambda?: number); } class MaxwellBoltzmann extends _dist.Distribution<'MaxwellBoltzmann'> { constructor(a?: number); } class Mielke extends _dist.Distribution<'Mielke'> { constructor(k?: number, s?: number); } class Moyal extends _dist.Distribution<'Moyal'> { constructor(mu?: number, sigma?: number); } class Nakagami extends _dist.Distribution<'Nakagami'> { constructor(m?: number, omega?: number); } class NegativeBinomial extends _dist.Distribution<'NegativeBinomial'> { constructor(r?: number, p?: number); } class NegativeHypergeometric extends _dist.Distribution<'NegativeHypergeometric'> { constructor(N?: number, K?: number, r?: number); } class NeymanA extends _dist.Distribution<'NeymanA'> { constructor(lambda?: number, theta?: number); } class NoncentralBeta extends _dist.Distribution<'NoncentralBeta'> { constructor(alpha?: number, beta?: number, lambda?: number); } class NoncentralChi extends _dist.Distribution<'NoncentralChi'> { constructor(k?: number, lambda?: number); } class NoncentralChi2 extends _dist.Distribution<'NoncentralChi'> { constructor(k?: number, lambda?: number); } class NoncentralF extends _dist.Distribution<'NoncentralF'> { constructor(d1?: number, d2?: number, lambda?: number); } class NoncentralT extends _dist.Distribution<'NoncentralT'> { constructor(nu?: number, mu?: number); static fnm(nu: number, mu: number, x: number): number; } class Normal extends _dist.Distribution<'Normal'> { constructor(mu?: number, sigma?: number); } class Pareto extends _dist.Distribution<'Pareto'> { constructor(xmin?: number, alpha?: number); } class PERT extends _dist.Distribution<'PERT'> { constructor(a?: number, b?: number, c?: number); } class Poisson extends _dist.Distribution<'Poisson'> { constructor(lambda?: number); } class PolyaAeppli extends _dist.Distribution<'PolyaAeppli'> { constructor(lambda?: number, theta?: number); } class Power extends _dist.Distribution<'Power'> { constructor(a?: number); } class QExponential extends _dist.Distribution<'QExponential'> { constructor(q?: number, lambda?: number); } class R extends _dist.Distribution<'R'> { constructor(c?: number); } class Rademacher extends _dist.Distribution<'Rademacher'> { constructor(); } class RaisedCosine extends _dist.Distribution<'RaisedCosine'> { constructor(mu?: number, s?: number); } class Rayleigh extends _dist.Distribution<'Rayleigh'> { constructor(sigma?: number); } class Reciprocal extends _dist.Distribution<'Reciprocal'> { constructor(a?: number, b?: number); } class ReciprocalInverseGaussian extends _dist.Distribution<'ReciprocalInverseGaussian'> { constructor(mu?: number, lambda?: number); } class Rice extends _dist.Distribution<'Rice'> { constructor(nu?: number, sigma?: number); } class ShiftedLogLogistic extends _dist.Distribution<'ShiftedLogLogistic'> { constructor(mu?: number, sigma?: number, xi?: number); } class Skellam extends _dist.Distribution<'Skellam'> { constructor(mu1?: number, mu2?: number); } class SkewNormal extends _dist.Distribution<'SkewNormal'> { constructor(xi?: number, omega?: number, alpha?: number); } class Slash extends _dist.Distribution<'Slash'> { constructor(); } class Soliton extends _dist.Distribution<'Soliton'> { constructor(N?: number); } class StudentT extends _dist.Distribution<'StudentT'> { constructor(nu?: number); } class StudentZ extends _dist.Distribution<'StudentZ'> { constructor(n?: number); } class Trapezoidal extends _dist.Distribution<'Trapezoidal'> { constructor(a?: number, b?: number, c?: number, d?: number); } class Triangular extends _dist.Distribution<'Triangular'> { constructor(a?: number, b?: number, c?: number); } class TukeyLambda extends _dist.Distribution<'TukeyLambda'> { constructor(lambda?: number); } class Uniform extends _dist.Distribution<'Uniform'> { constructor(xmin?: number, xmax?: number); } class UQuadratic extends _dist.Distribution<'UQuadratic'> { constructor(a?: number, b?: number); } class VonMises extends _dist.Distribution<'VonMises'> { constructor(kappa?: number); } class Weibull extends _dist.Distribution<'Weibull'> { constructor(lambda?: number, k?: number); } class Wigner extends _dist.Distribution<'Wigner'> { constructor(R?: number); } class YuleSimon extends _dist.Distribution<'YuleSimon'> { constructor(rho?: number); } class Zeta extends _dist.Distribution<'Zeta'> { constructor(s?: number); } class Zipf extends _dist.Distribution<'Zipf'> { constructor(s?: number, N?: number); } } declare namespace la { class Vector { constructor(arg?: number | readonly number[] | Vector); v(): number[]; i(i: number): number; i(i: number, value: number): void; f(func: (d: number) => number): Vector; scale(s: number): Vector; add(vec: Vector): Vector; dot(vec: Vector): number; } class Matrix { constructor(arg?: number | ReadonlyArray<ReadonlyArray<number>> | Matrix); m(): number[][]; ij(i: number, j: number): number; ij(i: number, j: number, value: number): void; f(func: (d: number) => number): Matrix; scale(s: number): Matrix; add(mat: Matrix): Matrix; mult(max: Matrix): Matrix; t(): Matrix; act(vec: Vector): Vector; ldl(): { D: Matrix; L: Matrix }; } } declare namespace _mc { enum State {} interface MCMC { state(): State; statistics(): Array<{ mean: number; std: number; cv: number; }>; ar(): number; ac(): number[]; iterate( callback?: (x: number[], accepted: boolean) => void, warmUp?: boolean, ): { x: number[]; accepted: boolean; }; warmUp(progress?: (percentage: number) => void, maxBatches?: number): void; sample(progress?: (percentage: number) => void, size?: number): number[][]; } abstract class MCMC {} } declare namespace mc { type State = _mc.State; type MCMC = _mc.MCMC; function gr(samples: ReadonlyArray<ReadonlyArray<ReadonlyArray<number>>>, maxLength?: number): number[][]; class RWM extends _mc.MCMC { constructor( logDensity: (x: number[]) => number, config?: { dim?: number | undefined; maxHistory?: number | undefined; }, initialState?: State, ); } } declare namespace test { function bartlett(dataSets: ReadonlyArray<ReadonlyArray<number>>, alpha: number): { chi2: number; passed: boolean }; function mannWhitney(dataSets: ReadonlyArray<ReadonlyArray<number>>, alpha: number): { U: number; passed: boolean }; } declare namespace _ts { interface Commons { reset(): void; update(x: readonly number[]): void; } abstract class Commons {} } declare namespace ts { class Cov extends _ts.Commons { constructor(dimension?: number); compute(): la.Matrix; } class AC extends _ts.Commons { constructor(dimension?: number, range?: number, maxSize?: number); compute(): number[][]; } } export { core, dist, la, mc, test, ts }; export as namespace ranjs;
the_stack
import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; import * as Root from '../../core/root/root.js'; import * as SDK from '../../core/sdk/sdk.js'; import * as Bindings from '../../models/bindings/bindings.js'; import * as TimelineModel from '../../models/timeline_model/timeline_model.js'; import * as PerfUI from '../../ui/legacy/components/perf_ui/perf_ui.js'; import * as UI from '../../ui/legacy/legacy.js'; import {CountersGraph} from './CountersGraph.js'; import type {PerformanceModel, WindowChangedEvent} from './PerformanceModel.js'; import {Events as PerformanceModelEvents} from './PerformanceModel.js'; import {TimelineDetailsView} from './TimelineDetailsView.js'; import {TimelineRegExp} from './TimelineFilters.js'; import {Events as TimelineFlameChartDataProviderEvents, TimelineFlameChartDataProvider} from './TimelineFlameChartDataProvider.js'; import {TimelineFlameChartNetworkDataProvider} from './TimelineFlameChartNetworkDataProvider.js'; import type {TimelineModeViewDelegate} from './TimelinePanel.js'; import {TimelineSelection} from './TimelinePanel.js'; import {AggregatedTimelineTreeView} from './TimelineTreeView.js'; import type {TimelineMarkerStyle} from './TimelineUIUtils.js'; import {TimelineUIUtils} from './TimelineUIUtils.js'; import {WebVitalsIntegrator} from './WebVitalsTimelineUtils.js'; const UIStrings = { /** *@description Text in Timeline Flame Chart View of the Performance panel *@example {Frame} PH1 *@example {10ms} PH2 */ sAtS: '{PH1} at {PH2}', }; const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineFlameChartView.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); class MainSplitWidget extends UI.SplitWidget.SplitWidget { private webVitals!: WebVitalsIntegrator; private model!: PerformanceModel|null; constructor( isVertical: boolean, secondIsSidebar: boolean, settingName?: string, defaultSidebarWidth?: number, defaultSidebarHeight?: number, constraintsInDip?: boolean) { super(isVertical, secondIsSidebar, settingName, defaultSidebarWidth, defaultSidebarHeight, constraintsInDip); } setWebVitals(webVitals: WebVitalsIntegrator): void { /** @type {!WebVitalsIntegrator} */ this.webVitals = webVitals; this.webVitals.setMinimumSize(0, 120); } setWindowTimes(left: number, right: number, animate: boolean): void { if (!this.webVitals) { return; } const startTime = left - (this.model ? this.model.timelineModel().minimumRecordTime() : 0); this.webVitals.chartViewport.setWindowTimes(left, right, animate); this.webVitals.webVitalsTimeline.data = { startTime: startTime, duration: right - left, fcps: undefined, lcps: undefined, layoutShifts: undefined, longTasks: undefined, mainFrameNavigations: undefined, maxDuration: undefined, }; } setModelAndUpdateBoundaries(model: PerformanceModel|null): void { this.model = model; if (!this.webVitals || !model) { return; } const left = model.window().left; const right = model.window().right; const timelineModel = model.timelineModel(); const events: SDK.TracingModel.Event[] = timelineModel.tracks().reduce((prev, curr) => prev.concat(curr.events), ([] as SDK.TracingModel.Event[])); const minimumBoundary = model.timelineModel().minimumRecordTime(); const prepareEvents = (filterFunction: (arg0: SDK.TracingModel.Event) => boolean): number[] => events.filter(filterFunction).map(e => e.startTime - minimumBoundary); const lcpEvents = events.filter(e => timelineModel.isLCPCandidateEvent(e) || timelineModel.isLCPInvalidateEvent(e)); const lcpEventsByNavigationId = new Map<string, SDK.TracingModel.Event>(); for (const e of lcpEvents) { const navigationId = e.args['data']['navigationId']; const previousLastEvent = lcpEventsByNavigationId.get(navigationId); if (!previousLastEvent || previousLastEvent.args['data']['candidateIndex'] < e.args['data']['candidateIndex']) { lcpEventsByNavigationId.set(navigationId, e); } } const latestLcpCandidatesByNavigationId = Array.from(lcpEventsByNavigationId.values()); const latestLcpEvents = latestLcpCandidatesByNavigationId.filter(e => timelineModel.isLCPCandidateEvent(e)); const longTasks = events.filter(e => SDK.TracingModel.TracingModel.isCompletePhase(e.phase) && timelineModel.isLongRunningTask(e)) .map(e => ({start: e.startTime - minimumBoundary, duration: e.duration || 0})); this.webVitals.chartViewport.setBoundaries(left, right - left); this.webVitals.chartViewport.setWindowTimes(left, right); const startTime = left - (this.model ? this.model.timelineModel().minimumRecordTime() : 0); this.webVitals.webVitalsTimeline.data = { startTime: startTime, duration: right - left, maxDuration: timelineModel.maximumRecordTime(), fcps: events.filter(e => timelineModel.isFCPEvent(e)).map(e => ({timestamp: e.startTime - minimumBoundary, e})), lcps: latestLcpEvents.map(e => e.startTime).map(t => ({timestamp: t - minimumBoundary})), layoutShifts: prepareEvents(e => timelineModel.isLayoutShiftEvent(e)).map(t => ({timestamp: t})), longTasks, mainFrameNavigations: prepareEvents(e => timelineModel.isMainFrameNavigationStartEvent(e)), }; } } export class TimelineFlameChartView extends UI.Widget.VBox implements PerfUI.FlameChart.FlameChartDelegate, UI.SearchableView.Searchable { private readonly delegate: TimelineModeViewDelegate; private model: PerformanceModel|null; private searchResults!: number[]|undefined; private eventListeners: Common.EventTarget.EventDescriptor[]; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any private readonly showMemoryGraphSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any private readonly showWebVitalsSetting: Common.Settings.Setting<any>; private readonly networkSplitWidget: UI.SplitWidget.SplitWidget; private mainDataProvider: TimelineFlameChartDataProvider; private readonly mainFlameChart: PerfUI.FlameChart.FlameChart; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any private readonly networkFlameChartGroupExpansionSetting: Common.Settings.Setting<any>; private networkDataProvider: TimelineFlameChartNetworkDataProvider; private readonly networkFlameChart: PerfUI.FlameChart.FlameChart; private readonly networkPane: UI.Widget.VBox; private readonly splitResizer: HTMLElement; private readonly webVitals: WebVitalsIntegrator; private readonly mainSplitWidget: MainSplitWidget; private readonly chartSplitWidget: UI.SplitWidget.SplitWidget; private readonly countersView: CountersGraph; private readonly detailsSplitWidget: UI.SplitWidget.SplitWidget; private readonly detailsView: TimelineDetailsView; private readonly onMainEntrySelected: (event: Common.EventTarget.EventTargetEvent<number>) => void; private readonly onNetworkEntrySelected: (event: Common.EventTarget.EventTargetEvent<number>) => void; private nextExtensionIndex: number; private readonly boundRefresh: () => void; private selectedTrack: TimelineModel.TimelineModel.Track|null; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any private readonly groupBySetting: Common.Settings.Setting<any>; private searchableView!: UI.SearchableView.SearchableView; private urlToColorCache?: Map<string, string>; private needsResizeToPreferredHeights?: boolean; private selectedSearchResult?: number; private searchRegex?: RegExp; constructor(delegate: TimelineModeViewDelegate) { super(); this.element.classList.add('timeline-flamechart'); this.delegate = delegate; this.model = null; this.eventListeners = []; this.showMemoryGraphSetting = Common.Settings.Settings.instance().createSetting('timelineShowMemory', false); this.showWebVitalsSetting = Common.Settings.Settings.instance().createSetting('timelineWebVitals', false); // Create main and network flamecharts. this.networkSplitWidget = new UI.SplitWidget.SplitWidget(false, false, 'timelineFlamechartMainView', 150); // Ensure that the network panel & resizer appears above the web vitals / main thread. this.networkSplitWidget.sidebarElement().style.zIndex = '120'; const mainViewGroupExpansionSetting = Common.Settings.Settings.instance().createSetting('timelineFlamechartMainViewGroupExpansion', {}); this.mainDataProvider = new TimelineFlameChartDataProvider(); this.mainDataProvider.addEventListener( TimelineFlameChartDataProviderEvents.DataChanged, () => this.mainFlameChart.scheduleUpdate()); this.mainFlameChart = new PerfUI.FlameChart.FlameChart(this.mainDataProvider, this, mainViewGroupExpansionSetting); this.mainFlameChart.alwaysShowVerticalScroll(); this.mainFlameChart.enableRuler(false); this.networkFlameChartGroupExpansionSetting = Common.Settings.Settings.instance().createSetting('timelineFlamechartNetworkViewGroupExpansion', {}); this.networkDataProvider = new TimelineFlameChartNetworkDataProvider(); this.networkFlameChart = new PerfUI.FlameChart.FlameChart(this.networkDataProvider, this, this.networkFlameChartGroupExpansionSetting); this.networkFlameChart.alwaysShowVerticalScroll(); this.networkFlameChart.disableRangeSelection(); this.networkPane = new UI.Widget.VBox(); this.networkPane.setMinimumSize(23, 23); this.networkFlameChart.show(this.networkPane.element); this.splitResizer = this.networkPane.element.createChild('div', 'timeline-flamechart-resizer'); this.networkSplitWidget.hideDefaultResizer(true); this.networkSplitWidget.installResizer(this.splitResizer); this.webVitals = new WebVitalsIntegrator(this); this.mainSplitWidget = new MainSplitWidget(false, false, 'timelineFlamechartMainAndVitalsView', undefined, 120); this.mainSplitWidget.setWebVitals(this.webVitals); this.mainSplitWidget.setMainWidget(this.mainFlameChart); this.mainSplitWidget.setSidebarWidget(this.webVitals); this.toggleWebVitalsLane(); this.networkSplitWidget.setMainWidget(this.mainSplitWidget); this.networkSplitWidget.setSidebarWidget(this.networkPane); // Create counters chart splitter. this.chartSplitWidget = new UI.SplitWidget.SplitWidget(false, true, 'timelineCountersSplitViewState'); this.countersView = new CountersGraph(this.delegate); this.chartSplitWidget.setMainWidget(this.networkSplitWidget); this.chartSplitWidget.setSidebarWidget(this.countersView); this.chartSplitWidget.hideDefaultResizer(); this.chartSplitWidget.installResizer((this.countersView.resizerElement() as Element)); this.updateCountersGraphToggle(); // Create top level properties splitter. this.detailsSplitWidget = new UI.SplitWidget.SplitWidget(false, true, 'timelinePanelDetailsSplitViewState'); this.detailsSplitWidget.element.classList.add('timeline-details-split'); this.detailsView = new TimelineDetailsView(delegate); this.detailsSplitWidget.installResizer(this.detailsView.headerElement()); this.detailsSplitWidget.setMainWidget(this.chartSplitWidget); this.detailsSplitWidget.setSidebarWidget(this.detailsView); this.detailsSplitWidget.show(this.element); this.onMainEntrySelected = this.onEntrySelected.bind(this, this.mainDataProvider); this.onNetworkEntrySelected = this.onEntrySelected.bind(this, this.networkDataProvider); this.mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected, this.onMainEntrySelected, this); this.mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryInvoked, this.onMainEntrySelected, this); this.networkFlameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected, this.onNetworkEntrySelected, this); this.networkFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryInvoked, this.onNetworkEntrySelected, this); this.mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryHighlighted, this.onEntryHighlighted, this); this.nextExtensionIndex = 0; this.boundRefresh = this.refresh.bind(this); this.selectedTrack = null; this.mainDataProvider.setEventColorMapping(TimelineUIUtils.eventColor); this.groupBySetting = Common.Settings.Settings.instance().createSetting( 'timelineTreeGroupBy', AggregatedTimelineTreeView.GroupBy.None); this.groupBySetting.addChangeListener(this.updateColorMapper, this); this.updateColorMapper(); } toggleWebVitalsLane(): void { if (this.showWebVitalsSetting.get()) { this.mainSplitWidget.showBoth(); this.mainSplitWidget.setSidebarSize(120); this.mainSplitWidget.setResizable(false); this.mainSplitWidget.hideDefaultResizer(true); } else { this.mainSplitWidget.hideSidebar(); } } private updateColorMapper(): void { this.urlToColorCache = new Map(); if (!this.model) { return; } this.mainDataProvider.setEventColorMapping(TimelineUIUtils.eventColor); this.mainFlameChart.update(); } private onWindowChanged(event: Common.EventTarget.EventTargetEvent<WindowChangedEvent>): void { const {window, animate} = event.data; this.mainFlameChart.setWindowTimes(window.left, window.right, animate); this.networkFlameChart.setWindowTimes(window.left, window.right, animate); this.networkDataProvider.setWindowTimes(window.left, window.right); this.mainSplitWidget.setWindowTimes(window.left, window.right, Boolean(animate)); this.updateSearchResults(false, false); } windowChanged(windowStartTime: number, windowEndTime: number, animate: boolean): void { if (this.model) { this.model.setWindow({left: windowStartTime, right: windowEndTime}, animate); } } updateRangeSelection(startTime: number, endTime: number): void { this.delegate.select(TimelineSelection.fromRange(startTime, endTime)); } updateSelectedGroup(flameChart: PerfUI.FlameChart.FlameChart, group: PerfUI.FlameChart.Group|null): void { if (flameChart !== this.mainFlameChart) { return; } const track = group ? this.mainDataProvider.groupTrack(group) : null; this.selectedTrack = track; this.updateTrack(); } setModel(model: PerformanceModel|null): void { if (model === this.model) { return; } Common.EventTarget.removeEventListeners(this.eventListeners); this.model = model; this.selectedTrack = null; this.mainDataProvider.setModel(this.model); this.networkDataProvider.setModel(this.model); if (this.model) { this.eventListeners = [ this.model.addEventListener(PerformanceModelEvents.WindowChanged, this.onWindowChanged, this), this.model.addEventListener(PerformanceModelEvents.ExtensionDataAdded, this.appendExtensionData, this), ]; const window = this.model.window(); this.mainFlameChart.setWindowTimes(window.left, window.right); this.networkFlameChart.setWindowTimes(window.left, window.right); this.networkDataProvider.setWindowTimes(window.left, window.right); this.mainSplitWidget.setModelAndUpdateBoundaries(model); this.updateSearchResults(false, false); } this.updateColorMapper(); this.updateTrack(); this.nextExtensionIndex = 0; this.appendExtensionData(); this.refresh(); } private updateTrack(): void { this.countersView.setModel(this.model, this.selectedTrack); this.detailsView.setModel(this.model, this.selectedTrack); } private refresh(): void { if (this.networkDataProvider.isEmpty()) { this.mainFlameChart.enableRuler(true); this.networkSplitWidget.hideSidebar(); } else { this.mainFlameChart.enableRuler(false); this.networkSplitWidget.showBoth(); this.resizeToPreferredHeights(); } this.mainFlameChart.reset(); this.networkFlameChart.reset(); this.updateSearchResults(false, false); } private appendExtensionData(): void { if (!this.model) { return; } const extensions = this.model.extensionInfo(); while (this.nextExtensionIndex < extensions.length) { this.mainDataProvider.appendExtensionEvents(extensions[this.nextExtensionIndex++]); } this.mainFlameChart.scheduleUpdate(); } private onEntryHighlighted(commonEvent: Common.EventTarget.EventTargetEvent<number>): void { SDK.OverlayModel.OverlayModel.hideDOMNodeHighlight(); const entryIndex = commonEvent.data; const event = this.mainDataProvider.eventByIndex(entryIndex); if (!event) { return; } const target = this.model && this.model.timelineModel().targetByEvent(event); if (!target) { return; } const timelineData = TimelineModel.TimelineModel.TimelineData.forEvent(event); const backendNodeIds = timelineData.backendNodeIds; if (!backendNodeIds) { return; } for (let i = 0; i < backendNodeIds.length; ++i) { new SDK.DOMModel.DeferredDOMNode(target, backendNodeIds[i]).highlight(); } } highlightEvent(event: SDK.TracingModel.Event|null): void { const entryIndex = event ? this.mainDataProvider.entryIndexForSelection(TimelineSelection.fromTraceEvent(event)) : -1; if (entryIndex >= 0) { this.mainFlameChart.highlightEntry(entryIndex); } else { this.mainFlameChart.hideHighlight(); } } willHide(): void { this.networkFlameChartGroupExpansionSetting.removeChangeListener(this.resizeToPreferredHeights, this); this.showMemoryGraphSetting.removeChangeListener(this.updateCountersGraphToggle, this); Bindings.IgnoreListManager.IgnoreListManager.instance().removeChangeListener(this.boundRefresh); } wasShown(): void { this.networkFlameChartGroupExpansionSetting.addChangeListener(this.resizeToPreferredHeights, this); this.showMemoryGraphSetting.addChangeListener(this.updateCountersGraphToggle, this); Bindings.IgnoreListManager.IgnoreListManager.instance().addChangeListener(this.boundRefresh); if (this.needsResizeToPreferredHeights) { this.resizeToPreferredHeights(); } this.mainFlameChart.scheduleUpdate(); this.networkFlameChart.scheduleUpdate(); } private updateCountersGraphToggle(): void { if (this.showMemoryGraphSetting.get()) { this.chartSplitWidget.showBoth(); } else { this.chartSplitWidget.hideSidebar(); } } setSelection(selection: TimelineSelection|null): void { let index = this.mainDataProvider.entryIndexForSelection(selection); this.mainFlameChart.setSelectedEntry(index); index = this.networkDataProvider.entryIndexForSelection(selection); this.networkFlameChart.setSelectedEntry(index); if (this.detailsView) { this.detailsView.setSelection(selection); } } private onEntrySelected( dataProvider: PerfUI.FlameChart.FlameChartDataProvider, event: Common.EventTarget.EventTargetEvent<number>): void { const entryIndex = event.data; if (Root.Runtime.experiments.isEnabled('timelineEventInitiators') && dataProvider === this.mainDataProvider) { if (this.mainDataProvider.buildFlowForInitiator(entryIndex)) { this.mainFlameChart.scheduleUpdate(); } } this.delegate.select((dataProvider as TimelineFlameChartNetworkDataProvider).createSelection(entryIndex)); } resizeToPreferredHeights(): void { if (!this.isShowing()) { this.needsResizeToPreferredHeights = true; return; } this.needsResizeToPreferredHeights = false; this.networkPane.element.classList.toggle( 'timeline-network-resizer-disabled', !this.networkDataProvider.isExpanded()); this.networkSplitWidget.setSidebarSize( this.networkDataProvider.preferredHeight() + this.splitResizer.clientHeight + PerfUI.FlameChart.HeaderHeight + 2); } setSearchableView(searchableView: UI.SearchableView.SearchableView): void { this.searchableView = searchableView; } // UI.SearchableView.Searchable implementation jumpToNextSearchResult(): void { if (!this.searchResults || !this.searchResults.length) { return; } const index = typeof this.selectedSearchResult !== 'undefined' ? this.searchResults.indexOf(this.selectedSearchResult) : -1; this.selectSearchResult(Platform.NumberUtilities.mod(index + 1, this.searchResults.length)); } jumpToPreviousSearchResult(): void { if (!this.searchResults || !this.searchResults.length) { return; } const index = typeof this.selectedSearchResult !== 'undefined' ? this.searchResults.indexOf(this.selectedSearchResult) : 0; this.selectSearchResult(Platform.NumberUtilities.mod(index - 1, this.searchResults.length)); } supportsCaseSensitiveSearch(): boolean { return true; } supportsRegexSearch(): boolean { return true; } private selectSearchResult(index: number): void { this.searchableView.updateCurrentMatchIndex(index); if (this.searchResults) { this.selectedSearchResult = this.searchResults[index]; this.delegate.select(this.mainDataProvider.createSelection(this.selectedSearchResult)); } } private updateSearchResults(shouldJump: boolean, jumpBackwards?: boolean): void { const oldSelectedSearchResult = (this.selectedSearchResult as number); delete this.selectedSearchResult; this.searchResults = []; if (!this.searchRegex || !this.model) { return; } const regExpFilter = new TimelineRegExp(this.searchRegex); const window = this.model.window(); this.searchResults = this.mainDataProvider.search(window.left, window.right, regExpFilter); this.searchableView.updateSearchMatchesCount(this.searchResults.length); if (!shouldJump || !this.searchResults.length) { return; } let selectedIndex = this.searchResults.indexOf(oldSelectedSearchResult); if (selectedIndex === -1) { selectedIndex = jumpBackwards ? this.searchResults.length - 1 : 0; } this.selectSearchResult(selectedIndex); } searchCanceled(): void { if (typeof this.selectedSearchResult !== 'undefined') { this.delegate.select(null); } delete this.searchResults; delete this.selectedSearchResult; delete this.searchRegex; } performSearch(searchConfig: UI.SearchableView.SearchConfig, shouldJump: boolean, jumpBackwards?: boolean): void { this.searchRegex = searchConfig.toSearchRegex(); this.updateSearchResults(shouldJump, jumpBackwards); } } export class Selection { timelineSelection: TimelineSelection; entryIndex: number; constructor(selection: TimelineSelection, entryIndex: number) { this.timelineSelection = selection; this.entryIndex = entryIndex; } } export const FlameChartStyle = { textColor: '#333', }; export class TimelineFlameChartMarker implements PerfUI.FlameChart.FlameChartMarker { private readonly startTimeInternal: number; private readonly startOffset: number; private style: TimelineMarkerStyle; constructor(startTime: number, startOffset: number, style: TimelineMarkerStyle) { this.startTimeInternal = startTime; this.startOffset = startOffset; this.style = style; } startTime(): number { return this.startTimeInternal; } color(): string { return this.style.color; } title(): string|null { if (this.style.lowPriority) { return null; } const startTime = i18n.TimeUtilities.millisToString(this.startOffset); return i18nString(UIStrings.sAtS, {PH1: this.style.title, PH2: startTime}); } draw(context: CanvasRenderingContext2D, x: number, height: number, pixelsPerMillisecond: number): void { const lowPriorityVisibilityThresholdInPixelsPerMs = 4; if (this.style.lowPriority && pixelsPerMillisecond < lowPriorityVisibilityThresholdInPixelsPerMs) { return; } context.save(); if (this.style.tall) { context.strokeStyle = this.style.color; context.lineWidth = this.style.lineWidth; context.translate(this.style.lineWidth < 1 || (this.style.lineWidth & 1) ? 0.5 : 0, 0.5); context.beginPath(); context.moveTo(x, 0); context.setLineDash(this.style.dashStyle); context.lineTo(x, context.canvas.height); context.stroke(); } context.restore(); } } // TODO(crbug.com/1167717): Make this a const enum again // eslint-disable-next-line rulesdir/const_enum export enum ColorBy { URL = 'URL', }
the_stack
import * as path from 'path'; import chai, { expect } from 'chai'; import Helper from '../../src/e2e-helper/e2e-helper'; import { statusFailureMsg } from '../../src/cli/commands/public-cmds/status-cmd'; import { OVERRIDE_COMPONENT_PREFIX, OVERRIDE_FILE_PREFIX } from '../../src/constants'; import { MISSING_PACKAGES_FROM_OVERRIDES_LABEL, componentIssuesLabels } from '../../src/cli/templates/component-issues-template'; chai.use(require('chai-fs')); describe('workspace config', function() { this.timeout(0); let helper: Helper; before(() => { helper = new Helper(); helper.command.setFeatures('legacy-workspace-config'); }); after(() => { helper.scopeHelper.destroy(); }); describe('when the config exists in both bit.json and package.json', () => { let localScope; before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fixtures.createComponentBarFoo(); helper.fixtures.addComponentBarFoo(); helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.npm.initNpm(); const packageJson = helper.packageJson.read(); packageJson.bit = { env: {}, componentsDefaultDirectory: 'components/{name}', packageManager: 'npm' }; helper.packageJson.write(packageJson); localScope = helper.scopeHelper.cloneLocalScope(); }); describe('when the config conflicts between bit.json and package.json', () => { before(() => { const bitJson = helper.bitJson.read(); bitJson.componentsDefaultDirectory = 'customBitJson/{name}'; helper.bitJson.write(bitJson); const packageJson = helper.packageJson.read(); packageJson.bit.componentsDefaultDirectory = 'customPackageJson/{name}'; helper.packageJson.write(packageJson); }); it('should use the config from bit.json and not from package.json', () => { helper.command.importComponent('bar/foo'); expect(path.join(helper.scopes.localPath, 'customBitJson')).to.be.a.directory(); expect(path.join(helper.scopes.localPath, 'customPackageJson')).to.not.be.a.path(); }); }); describe('when Bit writes config data', () => { before(() => { helper.scopeHelper.getClonedLocalScope(localScope); helper.command.importComponent('bar/foo -c'); }); it('should write the config data to both bit.json and package.json', () => { const bitJson = helper.bitJson.read(); expect(bitJson.env).to.have.property('compiler'); expect(bitJson.env.compiler).to.equal(`${helper.scopes.remote}/bar/foo@0.0.1`); const packageJson = helper.packageJson.read(); expect(packageJson.bit.env).to.have.property('compiler'); expect(packageJson.bit.env.compiler).to.equal(`${helper.scopes.remote}/bar/foo@0.0.1`); }); }); }); describe('overrides components', () => { describe('changing component dependencies versions', () => { let localScope; before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fs.createFile('', 'foo.js'); helper.fs.createFile('', 'bar.js', "require('./foo');"); helper.command.addComponent('foo.js'); helper.command.addComponent('bar.js'); helper.command.tagAllComponents(); helper.command.tagScope('2.0.0'); localScope = helper.scopeHelper.cloneLocalScope(); }); describe('from bit.json', () => { before(() => { const overrides = { bar: { dependencies: { [`${OVERRIDE_COMPONENT_PREFIX}foo`]: '0.0.1' } } }; helper.bitJson.addOverrides(overrides); }); it('bit diff should show the tagged dependency version vs the version from overrides', () => { const diff = helper.command.diff('bar'); expect(diff).to.have.string('- [ foo@2.0.0 ]'); expect(diff).to.have.string('+ [ foo@0.0.1 ]'); }); it('should not duplicate the dependencies or add anything to the package dependencies', () => { const bar = helper.command.showComponentParsed('bar'); expect(bar.dependencies).to.have.lengthOf(1); expect(Object.keys(bar.packageDependencies)).to.have.lengthOf(0); }); describe('tagging the component', () => { before(() => { helper.command.tagAllComponents(); }); it('should save the overridden dependency version', () => { const bar = helper.command.catComponent('bar@latest'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(bar.dependencies[0].id.version).to.equal('0.0.1'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(bar.flattenedDependencies[0].version).to.equal('0.0.1'); }); }); }); describe('from package.json', () => { before(() => { helper.scopeHelper.getClonedLocalScope(localScope); helper.fs.deletePath('bit.json'); helper.npm.initNpm(); helper.scopeHelper.initWorkspace(); const packageJson = helper.packageJson.read(); expect(packageJson).to.have.property('bit'); packageJson.bit.overrides = { bar: { dependencies: { [`${OVERRIDE_COMPONENT_PREFIX}foo`]: '0.0.1' } } }; helper.packageJson.write(packageJson); }); it('bit status should not delete "bit.overrides" property of package.json', () => { helper.command.status(); const packageJson = helper.packageJson.read(); expect(packageJson).to.have.property('bit'); expect(packageJson.bit).to.have.property('overrides'); }); it('bit diff should show the tagged dependency version vs the version from overrides', () => { const diff = helper.command.diff('bar'); expect(diff).to.have.string('- [ foo@2.0.0 ]'); expect(diff).to.have.string('+ [ foo@0.0.1 ]'); }); describe('tagging the component', () => { before(() => { helper.command.tagAllComponents(); }); it('should save the overridden dependency version', () => { const bar = helper.command.catComponent('bar@latest'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(bar.dependencies[0].id.version).to.equal('0.0.1'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(bar.flattenedDependencies[0].version).to.equal('0.0.1'); }); }); }); }); describe('changing packages dependencies versions', () => { before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fixtures.createComponentBarFoo('require("chai");'); helper.fixtures.addComponentBarFoo(); helper.npm.addNpmPackage('chai', '2.2.0'); const overrides = { 'bar/foo': { dependencies: { chai: '4.0.0' } } }; helper.bitJson.addOverrides(overrides); }); it('should show the overridden package version', () => { const bar = helper.command.showComponentParsed('bar/foo'); expect(Object.keys(bar.packageDependencies)).to.have.lengthOf(1); expect(bar.packageDependencies).to.deep.equal({ chai: '4.0.0' }); }); describe('tagging the component', () => { before(() => { helper.command.tagAllComponents(); }); it('should save the overridden package version', () => { const bar = helper.command.catComponent('bar/foo@latest'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(bar.packageDependencies).to.deep.equal({ chai: '4.0.0' }); }); }); }); describe('ignoring files and components dependencies', () => { let scopeAfterAdding; let remoteScopeEmpty; before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fs.createFile('foo-dir', 'foo1.js'); helper.fs.createFile('foo-dir', 'foo2.js'); helper.fs.createFile('bar-dir', 'bar.js', "require('../foo-dir/foo1'); require('../foo-dir/foo2'); "); helper.command.addComponent('foo-dir/foo1.js', { i: 'utils/foo/foo1' }); helper.command.addComponent('foo-dir/foo2.js', { i: 'utils/foo/foo2' }); helper.command.addComponent('bar-dir/bar.js', { i: 'bar' }); scopeAfterAdding = helper.scopeHelper.cloneLocalScope(); remoteScopeEmpty = helper.scopeHelper.cloneRemoteScope(); }); describe('ignoring the component file altogether', () => { let showBar; before(() => { const overrides = { bar: { dependencies: { [`${OVERRIDE_FILE_PREFIX}bar-dir/bar.js`]: '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('should show a warning saying that this feature is deprecated', () => { const status = helper.command.status(); expect(status).to.have.string( 'warning: file overrides (using "file://") is deprecated and will be removed on the next major version' ); }); it('should not add any dependency to the component', () => { expect(showBar.dependencies).to.have.lengthOf(0); }); it('should show the component file as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include('bar-dir/bar.js'); }); }); describe('ignoring a dependency file', () => { let showBar; before(() => { const overrides = { bar: { dependencies: { [`${OVERRIDE_FILE_PREFIX}foo-dir/foo2.js`]: '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('should not add the removed dependency to the component', () => { expect(showBar.dependencies).to.have.lengthOf(1); expect(showBar.dependencies[0].id).to.not.have.string('foo2'); }); it('should show the dependency file as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include('foo-dir/foo2.js'); }); describe('when running from an inner directory', () => { before(() => { const showBarStr = helper.command.runCmd( 'bit show bar --json', path.join(helper.scopes.localPath, 'bar-dir') ); showBar = JSON.parse(showBarStr); }); it('should behave the same as if was running from consumer root', () => { expect(showBar.dependencies).to.have.lengthOf(1); expect(showBar.dependencies[0].id).to.not.have.string('foo2'); expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include('foo-dir/foo2.js'); }); }); }); describe('ignoring a dependencies files with a glob pattern', () => { let showBar; before(() => { const overrides = { bar: { dependencies: { [`${OVERRIDE_FILE_PREFIX}foo-dir/*`]: '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('should remove all dependencies matching the glob pattern', () => { expect(showBar.dependencies).to.have.lengthOf(0); }); it('should show the dependencies files as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include('foo-dir/foo2.js'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include('foo-dir/foo1.js'); }); }); describe('ignoring a dependency component', () => { describe('when requiring with relative path', () => { before(() => { const overrides = { bar: { dependencies: { [`${OVERRIDE_COMPONENT_PREFIX}utils/foo/foo1`]: '-' } } }; helper.bitJson.addOverrides(overrides); }); it('should throw an error', () => { const showCmd = () => helper.command.showComponentParsed('bar'); expect(showCmd).to.throw(); }); }); describe('when requiring with module path', () => { let showBar; before(() => { helper.scopeHelper.getClonedLocalScope(scopeAfterAdding); helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.fs.createFile( 'bar-dir', 'bar.js', `require('@bit/${helper.scopes.remote}.utils.foo.foo1'); require('@bit/${helper.scopes.remote}.utils.foo.foo2'); ` ); const overrides = { bar: { dependencies: { [`${OVERRIDE_COMPONENT_PREFIX}utils/foo/foo1`]: '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('should not add the removed dependency to the component', () => { expect(showBar.dependencies).to.have.lengthOf(1); expect(showBar.dependencies[0].id).to.not.equal('foo1'); }); it('should show the dependency component as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include( `${helper.scopes.remote}/utils/foo/foo1` ); }); }); describe('when adding the component as devDependency without removing it', () => { before(() => { helper.scopeHelper.getClonedLocalScope(scopeAfterAdding); helper.scopeHelper.reInitRemoteScope(); helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.fs.createFile( 'bar-dir', 'bar.js', `require('@bit/${helper.scopes.remote}.utils.foo.foo1'); require('@bit/${helper.scopes.remote}.utils.foo.foo2'); ` ); const overrides = { bar: { devDependencies: { [`${OVERRIDE_COMPONENT_PREFIX}utils/foo/foo1`]: '+' } } }; helper.bitJson.addOverrides(overrides); }); // todo: make a decision about the desired behavior. see #2061 it.skip('should not show the component twice as dependency and as devDependencies', () => { const showBar = helper.command.showComponentParsed('bar'); expect(showBar.dependencies).to.have.lengthOf(1); }); it('should not allow tagging the component', () => { const tagFunc = () => helper.command.tagAllComponents(); expect(tagFunc).to.throw('some dependencies are duplicated'); }); }); }); describe('ignoring a dependencies components by wildcards', () => { let showBar; before(() => { helper.scopeHelper.getClonedLocalScope(scopeAfterAdding); const overrides = { bar: { dependencies: { [`${OVERRIDE_COMPONENT_PREFIX}utils/foo/*`]: '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('should not ignore the dependencies as we do not support ignoring dependencies components by wildcards', () => { expect(showBar.dependencies).to.have.lengthOf(2); }); it('should not show the dependencies component as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.deep.equal({}); }); }); describe('ignoring a missing file', () => { let showBar; before(() => { helper.fs.createFile( 'bar-dir', 'bar.js', "require('../foo-dir/foo1'); require('../foo-dir/foo2'); require('../foo-dir/foo3')" ); // an intermediate step, make sure bit status shows the component with an issue of a missing file helper.command.linkAndRewire(); const status = helper.command.status(); expect(status).to.have.string(statusFailureMsg); const overrides = { bar: { dependencies: { [`${OVERRIDE_FILE_PREFIX}foo-dir/foo3*`]: '-' // we don't enter the entire file foo-dir/foo3.js because the require string doesn't have the extension } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('bit status should not show the component as missing files', () => { const status = helper.command.status(); expect(status).to.not.have.string(statusFailureMsg); }); it('should show the dependency file as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include(path.normalize('foo-dir/foo3')); }); }); describe('ignoring a missing component', () => { let showBar; before(() => { helper.scopeHelper.getClonedLocalScope(scopeAfterAdding); helper.fs.createFile( 'bar-dir', 'bar.js', "require('../foo-dir/foo1'); require('../foo-dir/foo2'); require('@bit/bit.utils.is-string')" ); // an intermediate step, make sure bit status shows the component with an issue of a missing file const status = helper.command.status(); expect(status).to.have.string(statusFailureMsg); const overrides = { bar: { dependencies: { [`${OVERRIDE_COMPONENT_PREFIX}bit.utils/is-string`]: '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('bit status should not show the component as missing component', () => { helper.command.linkAndRewire(); const status = helper.command.status(); expect(status).to.not.have.string(statusFailureMsg); }); it('should show the component as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include('bit.utils/is-string'); }); }); describe('ignoring an existing component required as a package', () => { let showBar; before(() => { helper.scopeHelper.getClonedLocalScope(scopeAfterAdding); helper.scopeHelper.getClonedRemoteScope(remoteScopeEmpty); helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.fs.createFile( 'bar-dir', 'bar.js', `require('@bit/${helper.scopes.remote}.utils.foo.foo1'); require('../foo-dir/foo2');` ); const overrides = { bar: { dependencies: { [`${OVERRIDE_COMPONENT_PREFIX}utils/foo/foo1`]: '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('should ignore the specified component dependency', () => { expect(showBar.dependencies).to.have.lengthOf(1); expect(showBar.dependencies[0].id).to.have.string('foo2'); }); it('should show the component dependency as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include(`${helper.scopes.remote}/utils/foo/foo1`); }); }); }); describe('ignoring packages dependencies', () => { describe('ignoring a missing package', () => { let showBar; before(() => { helper.scopeHelper.reInitLocalScope(); helper.fs.createFile('bar-dir', 'bar.js', "require('non-exist-package')"); helper.command.addComponent('bar-dir/bar.js', { i: 'bar' }); // an intermediate step, make sure bit status shows the component with an issue of a missing file const status = helper.command.status(); expect(status).to.have.string(statusFailureMsg); const overrides = { bar: { dependencies: { 'non-exist-package': '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('bit status should not show the component as missing packages', () => { const status = helper.command.status(); expect(status).to.not.have.string(statusFailureMsg); }); it('should show the package as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include('non-exist-package'); }); }); describe('ignoring an existing package', () => { let showBar; before(() => { helper.scopeHelper.reInitLocalScope(); helper.npm.addNpmPackage('existing-package'); helper.npm.addNpmPackage('another-existing-package'); helper.fs.createFile( 'bar-dir', 'bar.js', "require('existing-package'); require('another-existing-package');" ); helper.command.addComponent('bar-dir/bar.js', { i: 'bar' }); const overrides = { bar: { dependencies: { 'existing-package': '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('should ignore the specified package but keep other packages intact', () => { expect(Object.keys(showBar.packageDependencies)).to.have.lengthOf(1); expect(Object.keys(showBar.packageDependencies)[0]).to.equal('another-existing-package'); }); it('should show the package as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include('existing-package'); }); }); describe('ignoring an existing devDependency package', () => { let showBar; before(() => { helper.scopeHelper.reInitLocalScope(); helper.npm.addNpmPackage('existing-package'); helper.npm.addNpmPackage('another-existing-package'); helper.fs.createFile('bar-dir', 'bar.js'); helper.fs.createFile( 'bar-dir', 'bar.spec.js', "require('existing-package'); require('another-existing-package');" ); helper.command.addComponent('bar-dir/*', { i: 'bar', m: 'bar-dir/bar.js', t: 'bar-dir/bar.spec.js' }); const overrides = { bar: { devDependencies: { 'existing-package': '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('should ignore the specified package but keep other packages intact', () => { expect(Object.keys(showBar.packageDependencies)).to.have.lengthOf(0); expect(Object.keys(showBar.devPackageDependencies)).to.have.lengthOf(1); expect(Object.keys(showBar.devPackageDependencies)[0]).to.equal('another-existing-package'); }); it('should show the package as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('devDependencies'); expect(showBar.manuallyRemovedDependencies.devDependencies).to.include('existing-package'); }); it('should not confuse ignore of dependencies with ignore of devDependencies', () => { expect(showBar.manuallyRemovedDependencies).to.not.have.property('dependencies'); }); }); describe('ignoring an existing peerDependency package', () => { let showBar; before(() => { // keep in mind that the 'chai' dependency is a regular package dependency, which // also saved as a peerDependency helper.scopeHelper.reInitLocalScope(); helper.fixtures.createComponentBarFoo("import chai from 'chai';"); helper.npm.addNpmPackage('chai', '2.2.0'); helper.packageJson.create({ peerDependencies: { chai: '>= 2.1.2 < 5' } }); helper.fixtures.addComponentBarFoo(); const overrides = { 'bar/foo': { peerDependencies: { chai: '-' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar/foo'); }); it('should ignore the specified peer package', () => { expect(Object.keys(showBar.peerPackageDependencies)).to.have.lengthOf(0); }); it('should keep the dependency package intact', () => { expect(Object.keys(showBar.packageDependencies)).to.have.lengthOf(1); }); it('should show the package as ignored', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('peerDependencies'); expect(showBar.manuallyRemovedDependencies.peerDependencies).to.include('chai'); }); it('should not confuse ignore of dependencies/devDependencies with ignore of peerDependencies', () => { expect(showBar.manuallyRemovedDependencies).to.not.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies).to.not.have.property('devDependencies'); }); }); }); describe('ignoring dependencies components entire flow', () => { before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fs.createFile('', 'foo1.js'); helper.fs.createFile('', 'foo2.js'); helper.fs.createFile('', 'bar.js'); helper.command.addComponent('foo1.js'); helper.command.addComponent('foo2.js'); helper.command.addComponent('bar.js'); helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.fs.createFile( '', 'bar.js', `require('@bit/${helper.scopes.remote}.foo1'); require('@bit/${helper.scopes.remote}.foo2');` ); const overrides = { bar: { dependencies: { [`${OVERRIDE_COMPONENT_PREFIX}foo2`]: '-' } } }; helper.bitJson.addOverrides(overrides); }); describe('tagging the component', () => { let output; let catBar; before(() => { output = helper.general.runWithTryCatch('bit tag bar'); catBar = helper.command.catComponent('bar@latest'); }); it('should be able to tag successfully', () => { expect(output).to.have.string('1 component(s) tagged'); }); it('should remove the dependency from the model', () => { expect(catBar.dependencies).to.have.lengthOf(1); }); it('should save the overrides data into the model', () => { expect(catBar).to.have.property('overrides'); expect(catBar.overrides).to.have.property('dependencies'); expect(catBar.overrides.dependencies).to.have.property(`${OVERRIDE_COMPONENT_PREFIX}foo2`); expect(catBar.overrides.dependencies[`${OVERRIDE_COMPONENT_PREFIX}foo2`]).to.equal('-'); }); it('should not show the component as modified', () => { const status = helper.command.status(); expect(status).to.not.have.string('modified components'); }); describe('importing the component', () => { let barRoot; before(() => { barRoot = path.join(helper.scopes.localPath, 'components/bar/'); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar'); }); it('should write the overrides data into the package.json of the component', () => { const packageJson = helper.packageJson.read(barRoot); expect(packageJson).to.have.property('bit'); expect(packageJson.bit).to.have.property('overrides'); expect(packageJson.bit.overrides).to.have.property('dependencies'); expect(packageJson.bit.overrides.dependencies).to.have.property(`${OVERRIDE_COMPONENT_PREFIX}foo2`); expect(packageJson.bit.overrides.dependencies[`${OVERRIDE_COMPONENT_PREFIX}foo2`]).to.equal('-'); }); it('bit status should not show the component as modified', () => { helper.command.expectStatusToBeClean(); }); it('bit diff should not show any diff', () => { const diff = helper.command.diff('bar'); expect(diff).to.have.string('no diff'); }); describe('changing the imported component to not ignore the dependency', () => { before(() => { const packageJson = helper.packageJson.read(path.join(helper.scopes.localPath, 'components/bar/')); packageJson.bit.overrides.dependencies = {}; helper.packageJson.write(packageJson, barRoot); }); it('bit status should show the component as modified', () => { const status = helper.command.status(); expect(status).to.have.string('modified components'); }); it('should show the previously ignored dependency as a missing component', () => { const status = helper.command.status(); expect(status).to.have.string(statusFailureMsg); expect(status).to.have.string('missing components'); }); it('bit diff should show the overrides differences', () => { const diff = helper.command.diff('bar'); expect(diff).to.have.string('--- Overrides Dependencies (0.0.2 original)'); expect(diff).to.have.string('+++ Overrides Dependencies (0.0.2 modified)'); expect(diff).to.have.string(`- [ ${OVERRIDE_COMPONENT_PREFIX}foo2@- ]`); }); }); }); }); }); describe('author ignored package, imported changed to not ignore', () => { let authorScope; before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fixtures.createComponentBarFoo("import chai from 'chai';"); helper.npm.addNpmPackage('chai', '2.2.0'); helper.fixtures.addComponentBarFoo(); const overrides = { 'bar/foo': { dependencies: { chai: '-' } } }; helper.bitJson.addOverrides(overrides); helper.command.tagAllComponents(); helper.command.exportAllComponents(); authorScope = helper.scopeHelper.cloneLocalScope(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); helper.npm.addNpmPackage('chai', '2.2.0'); const componentDir = path.join(helper.scopes.localPath, 'components/bar/foo'); const packageJson = helper.packageJson.read(componentDir); // an intermediate step to make sure we're good so far expect(packageJson.bit.overrides.dependencies).to.deep.equal({ chai: '-' }); packageJson.bit.overrides.dependencies = {}; helper.packageJson.write(packageJson, componentDir); // an intermediate step to make sure we're good so far const diff = helper.command.diff(); expect(diff).to.have.string('- [ chai@- ]'); helper.command.tagAllComponents(); helper.command.exportAllComponents(); }); it('should be saved into the model with an empty overrides', () => { const barFoo = helper.command.catComponent('bar/foo@latest'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(barFoo.overrides).to.have.property('dependencies'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(barFoo.overrides.dependencies).to.be.empty; }); it('should be saved into the model with the package in place', () => { const barFoo = helper.command.catComponent('bar/foo@latest'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(barFoo.packageDependencies).to.deep.equal({ chai: '2.2.0' }); }); describe('then, author re-import', () => { let scopeAfterReImport; before(() => { helper.scopeHelper.getClonedLocalScope(authorScope); helper.command.importComponent('bar/foo'); scopeAfterReImport = helper.scopeHelper.cloneLocalScope(); }); it('bit status should not show the component as modified', () => { helper.command.expectStatusToBeClean(); }); it('should save the new overrides to the consumer config', () => { const bitJson = helper.bitJson.read(); expect(bitJson.overrides['bar/foo'].dependencies).to.be.empty; }); describe('then author checkout to the first version', () => { before(() => { helper.command.checkoutVersion('0.0.1', 'bar/foo'); }); it('bit status should not show the component as modified', () => { const status = helper.command.status(); expect(status).to.not.have.string('modified components'); }); it('should show the dependency as ignored', () => { const showBar = helper.command.showComponentParsed('bar/foo'); expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include('chai'); }); it('should save the overrides of the first version into consumer config', () => { const bitJson = helper.bitJson.read(); expect(bitJson.overrides['bar/foo'].dependencies).to.not.be.empty; expect(bitJson.overrides['bar/foo'].dependencies).to.deep.equal({ chai: '-' }); }); }); describe('then author merge the first version', () => { before(() => { helper.scopeHelper.getClonedLocalScope(scopeAfterReImport); helper.command.mergeVersion('0.0.1', 'bar/foo'); }); it('bit status should not show the component as modified', () => { const status = helper.command.status(); expect(status).to.not.have.string('modified components'); }); it('should not show the dependency as ignored', () => { const showBar = helper.command.showComponentParsed('bar/foo'); expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.be.empty; }); it('should not change the consumer config', () => { const bitJson = helper.bitJson.read(); expect(bitJson.overrides['bar/foo'].dependencies).to.be.empty; }); }); describe('when the consumer config is saved also in the package.json file', () => { before(() => { helper.scopeHelper.getClonedLocalScope(authorScope); helper.npm.initNpm(); const packageJson = helper.packageJson.read(); packageJson.dependencies = { chai: '2.2.0' }; packageJson.bit = { env: {}, componentsDefaultDirectory: 'components/{name}', packageManager: 'npm' }; helper.packageJson.write(packageJson); try { helper.command.importComponent('bar/foo --skip-npm-install'); } catch (err) { // ignore. it shows an error because chai is missing, which is missing by purpose } }); it('should still update bit.json', () => { const bitJson = helper.bitJson.read(); expect(bitJson.overrides['bar/foo'].dependencies).to.be.empty; }); it('should also update package.json', () => { const packageJson = helper.packageJson.read(); expect(packageJson.bit.overrides['bar/foo'].dependencies).to.be.empty; }); }); }); }); describe('changing overrides of a component in consumer config after tag', () => { before(() => { helper.scopeHelper.reInitLocalScope(); helper.fixtures.createComponentBarFoo("require('chai');"); helper.npm.addNpmPackage('chai', '2.2.0'); helper.fixtures.addComponentBarFoo(); const overrides = { 'bar/foo': { dependencies: { chai: '-' } } }; helper.bitJson.addOverrides(overrides); helper.command.tagAllComponents(); const overridesChanged = { 'bar/foo': { dependencies: {} } }; helper.bitJson.addOverrides(overridesChanged); }); it('bit status should show the component as modified', () => { const status = helper.command.status(); expect(status).to.have.string('modified components'); }); }); describe('changing order of the overrides dependencies after tag', () => { before(() => { helper.scopeHelper.reInitLocalScope(); helper.fixtures.createComponentBarFoo("require('chai'); require('lodash')"); helper.npm.addNpmPackage('chai', '2.2.0'); helper.npm.addNpmPackage('lodash', '2.2.0'); helper.fixtures.addComponentBarFoo(); const overrides = { 'bar/foo': { dependencies: { chai: '-', lodash: '-' } } }; helper.bitJson.addOverrides(overrides); helper.command.tagAllComponents(); const overridesChangedOrder = { 'bar/foo': { dependencies: { lodash: '-', chai: '-' } } }; helper.bitJson.addOverrides(overridesChangedOrder); }); it('bit status should not show the component as modified', () => { const status = helper.command.status(); expect(status).to.not.have.string('modified components'); }); }); describe('manually adding dependencies', () => { describe('moving a package from dependencies to peerDependencies', () => { let showBar; before(() => { helper.scopeHelper.reInitLocalScope(); helper.fixtures.createComponentBarFoo("import chai from 'chai';"); helper.npm.addNpmPackage('chai', '2.2.0'); helper.packageJson.create({ dependencies: { chai: '2.2.0' } }); helper.fixtures.addComponentBarFoo(); const overrides = { 'bar/foo': { dependencies: { chai: '-' }, peerDependencies: { chai: '+' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar/foo'); }); it('should ignore the specified package from dependencies', () => { expect(Object.keys(showBar.packageDependencies)).to.have.lengthOf(0); }); it('should add the specified package to peerDependencies', () => { expect(Object.keys(showBar.peerPackageDependencies)).to.have.lengthOf(1); expect(showBar.peerPackageDependencies).to.deep.equal({ chai: '2.2.0' }); }); it('should show the package as ignored from dependencies', () => { expect(showBar).to.have.property('manuallyRemovedDependencies'); expect(showBar.manuallyRemovedDependencies).to.have.property('dependencies'); expect(showBar.manuallyRemovedDependencies.dependencies).to.include('chai'); }); it('should show the package as manually added to peerDependencies', () => { expect(showBar).to.have.property('manuallyAddedDependencies'); expect(showBar.manuallyAddedDependencies).to.have.property('peerDependencies'); expect(showBar.manuallyAddedDependencies.peerDependencies).to.deep.equal(['chai@2.2.0']); }); }); describe('adding a package with version that does not exist in package.json', () => { let showBar; before(() => { helper.scopeHelper.reInitLocalScope(); helper.fixtures.createComponentBarFoo("import chai from 'chai';"); helper.fixtures.addComponentBarFoo(); const overrides = { 'bar/foo': { peerDependencies: { chai: '2.2.0' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar/foo'); }); it('should add the specified package to peerDependencies', () => { expect(Object.keys(showBar.peerPackageDependencies)).to.have.lengthOf(1); expect(showBar.peerPackageDependencies).to.deep.equal({ chai: '2.2.0' }); }); it('should show the package as manually added to peerDependencies', () => { expect(showBar).to.have.property('manuallyAddedDependencies'); expect(showBar.manuallyAddedDependencies).to.have.property('peerDependencies'); expect(showBar.manuallyAddedDependencies.peerDependencies).to.deep.equal(['chai@2.2.0']); }); }); describe('adding a package without version that does not exist in package.json', () => { before(() => { helper.scopeHelper.reInitLocalScope(); helper.fixtures.createComponentBarFoo("import chai from 'chai';"); helper.fixtures.addComponentBarFoo(); const overrides = { 'bar/foo': { peerDependencies: { chai: '+' } } }; helper.bitJson.addOverrides(overrides); }); // See similar test in show.e2e - component with overrides data it('should not show the package in dependencies', () => { const output = helper.command.showComponent('bar/foo'); expect(output).to.not.have.string('chai"'); }); // See similar test in status.e2e - when a component is created and added without its package dependencies it('should show a missing package in status', () => { const output = helper.command.status().replace(/\n/g, ''); expect(output).to.have.string(componentIssuesLabels.missingPackagesDependenciesOnFs); expect(output).to.have.string('bar/foo.js -> chai'); expect(output).to.have.string(`${MISSING_PACKAGES_FROM_OVERRIDES_LABEL} -> chai`); }); }); describe('adding a component with a version', () => { let showBar; before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fs.createFile('', 'bar.js'); helper.fs.createFile('', 'foo.js'); helper.command.addComponent('bar.js'); helper.command.addComponent('foo.js'); const overrides = { bar: { dependencies: { [`${OVERRIDE_COMPONENT_PREFIX}foo`]: '0.0.1' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('should show the component as manually added dependency', () => { expect(showBar.manuallyAddedDependencies.dependencies).to.deep.equal(['foo@0.0.1']); }); it('should add the component to the dependencies array with an empty relativePaths', () => { expect(showBar.dependencies[0].id).to.equal('foo@0.0.1'); expect(showBar.dependencies[0].relativePaths).to.deep.equal([]); }); describe('tagging the components', () => { let catBar; before(() => { // with non-legacy mode, it complains about the missing foo@0.0.1 during the capsule write // this is fine. normally users use the version once the version created. helper.command.tagAllComponents(); catBar = helper.command.catComponent('bar@latest'); }); it('should save the overrides data into the scope', () => { expect(catBar).to.have.property('overrides'); expect(catBar.overrides) .to.have.property('dependencies') .that.deep.equal({ [`${OVERRIDE_COMPONENT_PREFIX}foo`]: '0.0.1' }); }); it('should save the manually added dependency into dependencies', () => { expect(catBar.dependencies[0].id).to.deep.equal({ name: 'foo', version: '0.0.1' }); expect(catBar.dependencies[0].relativePaths).to.deep.equal([]); }); it('should save the manually added dependency into flattenedDependencies', () => { expect(catBar.flattenedDependencies[0]).to.deep.equal({ name: 'foo', version: '0.0.1' }); }); describe('importing the component', () => { let originalAuthorScope; let afterImport; before(() => { helper.command.exportAllComponents(); originalAuthorScope = helper.scopeHelper.cloneLocalScope(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar'); afterImport = helper.scopeHelper.cloneLocalScope(); }); it('should also import the manually added dependency', () => { const fooPath = path.join(helper.scopes.localPath, 'components/.dependencies/foo'); expect(fooPath).to.be.a.directory(); }); it('should add the overrides data into package.json', () => { const packageJson = helper.packageJson.read(path.join(helper.scopes.localPath, 'components/bar')); expect(packageJson).to.have.property('bit'); expect(packageJson.bit.overrides.dependencies).to.deep.equal({ [`${OVERRIDE_COMPONENT_PREFIX}foo`]: '0.0.1' }); }); it('bit status should show a clean state', () => { helper.command.expectStatusToBeClean(); }); describe('changing the component name in the overrides to a package syntax', () => { before(() => { const componentPackageJson = helper.packageJson.readComponentPackageJson('bar'); componentPackageJson.bit.overrides.dependencies = { [`${OVERRIDE_COMPONENT_PREFIX}${helper.scopes.remote}.foo`]: '0.0.1' }; helper.packageJson.write(componentPackageJson, path.join(helper.scopes.localPath, 'components/bar')); }); it('should not recognize the bit component as a package', () => { const show = helper.command.showComponentParsed('bar'); expect(show.packageDependencies).to.deep.equal({}); expect(show.dependencies).to.have.lengthOf(1); }); }); describe('removing the manually added dependency from the imported', () => { before(() => { helper.scopeHelper.getClonedLocalScope(afterImport); const barPath = path.join(helper.scopes.localPath, 'components/bar'); const packageJson = helper.packageJson.read(barPath); packageJson.bit.overrides.dependencies = {}; helper.packageJson.write(packageJson, barPath); }); it('bit diff should show the removed dependency', () => { const diff = helper.command.diff(); expect(diff).to.have.string('--- Dependencies (0.0.1 original)'); expect(diff).to.have.string('+++ Dependencies (0.0.1 modified)'); expect(diff).to.have.string(`- [ ${helper.scopes.remote}/foo@0.0.1 ]`); expect(diff).to.have.string('--- Overrides Dependencies (0.0.1 original)'); expect(diff).to.have.string('+++ Overrides Dependencies (0.0.1 modified)'); expect(diff).to.have.string(`- [ ${OVERRIDE_COMPONENT_PREFIX}foo@0.0.1 ]`); }); describe('tagging, exporting the component and then re-import for original author', () => { before(() => { helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.getClonedLocalScope(originalAuthorScope); helper.command.importComponent('bar'); }); it('bit status should show a clean state', () => { helper.command.expectStatusToBeClean(); }); it('should remove the added dependencies from consumer-config', () => { const bitJson = helper.bitJson.read(); expect(bitJson.overrides.bar.dependencies).to.be.empty; }); it('should remove the dependency from the model', () => { catBar = helper.command.catComponent('bar@0.0.2'); expect(catBar.dependencies).to.deep.equal([]); expect(catBar.overrides.dependencies).to.deep.equal({}); }); it('bit show should have the manuallyAddedDependencies empty', () => { showBar = helper.command.showComponentParsed('bar'); expect(showBar.manuallyAddedDependencies).to.deep.equal({}); }); }); }); }); }); }); describe('adding a component without a version', () => { let showBar; before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fs.createFile('', 'bar.js'); helper.fs.createFile('', 'foo.js'); helper.command.addComponent('bar.js'); helper.command.addComponent('foo.js'); const overrides = { bar: { dependencies: { [`${OVERRIDE_COMPONENT_PREFIX}foo`]: '+' } } }; helper.bitJson.addOverrides(overrides); showBar = helper.command.showComponentParsed('bar'); }); it('should show the component as manually added dependency', () => { expect(showBar.manuallyAddedDependencies.dependencies).to.deep.equal(['foo']); }); it('should add the component to the dependencies array with an empty relativePaths', () => { expect(showBar.dependencies[0].id).to.equal('foo'); expect(showBar.dependencies[0].relativePaths).to.deep.equal([]); }); describe('tagging the components', () => { let catBar; before(() => { helper.command.tagAllComponents(); catBar = helper.command.catComponent('bar@latest'); }); it('should save the overrides data into the scope', () => { expect(catBar).to.have.property('overrides'); expect(catBar.overrides) .to.have.property('dependencies') .that.deep.equal({ [`${OVERRIDE_COMPONENT_PREFIX}foo`]: '+' }); }); it('should save the manually added dependency into dependencies and resolve its version correctly', () => { expect(catBar.dependencies[0].id).to.deep.equal({ name: 'foo', version: '0.0.1' }); expect(catBar.dependencies[0].relativePaths).to.deep.equal([]); }); it('should save the manually added dependency into flattenedDependencies', () => { expect(catBar.flattenedDependencies[0]).to.deep.equal({ name: 'foo', version: '0.0.1' }); }); }); describe('importing the component', () => { before(() => { helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar'); }); it('should also import the manually added dependency', () => { const fooPath = path.join(helper.scopes.localPath, 'components/.dependencies/foo'); expect(fooPath).to.be.a.directory(); }); it('should add the overrides data into package.json', () => { const packageJson = helper.packageJson.read(path.join(helper.scopes.localPath, 'components/bar')); expect(packageJson).to.have.property('bit'); expect(packageJson.bit.overrides.dependencies).to.deep.equal({ [`${OVERRIDE_COMPONENT_PREFIX}foo`]: '+' }); }); it('bit status should show a clean state', () => { helper.command.expectStatusToBeClean(); }); }); }); }); describe('override environments', () => { describe('default workspace compiler and different compilers for different components', () => { before(() => { helper.scopeHelper.reInitLocalScope(); helper.fs.createFile('bar', 'foo-default.js'); helper.fs.createFile('bar', 'foo1.js'); helper.fs.createFile('bar', 'foo2.js'); helper.command.addComponent('bar/*'); const bitJson = helper.bitJson.read(); bitJson.env = { compiler: 'my-scope/default-compiler@0.0.1' }; bitJson.overrides = { foo1: { env: { compiler: 'my-scope/foo1-compiler@0.0.1' } }, foo2: { env: { compiler: 'my-scope/foo2-compiler@0.0.1' } } }; helper.bitJson.write(bitJson); }); it('should set the compiler with no overrides to the workspace default', () => { const fooDefault = helper.command.showComponentParsed('foo-default'); expect(fooDefault.compiler.name).to.equal('my-scope/default-compiler@0.0.1'); }); it('should set the components with overrides compilers with the appropriate compilers', () => { const foo1 = helper.command.showComponentParsed('foo1'); const foo2 = helper.command.showComponentParsed('foo2'); expect(foo1.compiler.name).to.equal('my-scope/foo1-compiler@0.0.1'); expect(foo2.compiler.name).to.equal('my-scope/foo2-compiler@0.0.1'); }); describe('adding a compiler with minus sign to overrides', () => { before(() => { const overrides = { foo1: { env: { compiler: '-' } }, foo2: { env: { compiler: 'my-scope/foo2-compiler@0.0.1' } } }; helper.bitJson.addOverrides(overrides); }); it('should remove the compiler to that component', () => { const foo1 = helper.command.showComponentParsed('foo1'); expect(foo1.compiler).to.be.null; }); }); describe('adding "env" to overrides with no values', () => { before(() => { const overrides = { foo1: { env: {} }, foo2: { env: { compiler: 'my-scope/foo2-compiler@0.0.1' } } }; helper.bitJson.addOverrides(overrides); }); it('should not override the env to that component and should use the workspace default', () => { const foo1 = helper.command.showComponentParsed('foo1'); expect(foo1.compiler.name).to.equal('my-scope/default-compiler@0.0.1'); }); }); }); }); // legacy test in order to check the originallySharedDir describe('ignoring files with originallySharedDir', () => { before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); const fooFixture = 'require("../utils/is-string");'; helper.fs.createFile('src/bar', 'foo.js', fooFixture); helper.fs.createFile('src/utils', 'is-string.js'); helper.command.addComponent('src/bar/foo.js'); helper.command.addComponent('src/utils/is-string.js'); const overrides = { foo: { dependencies: { [`${OVERRIDE_FILE_PREFIX}src/utils/*`]: '-' } } }; helper.bitJson.addOverrides(overrides); helper.command.tagAllComponents(); // intermediate step, make sure the dependency is-string is ignored const foo = helper.command.catComponent('foo@latest'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(foo.dependencies).to.have.lengthOf(0); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(Object.keys(foo.overrides.dependencies)).to.have.lengthOf(1); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('foo'); // change the file to have it as modified. helper.fs.createFile('components/foo/bar', 'foo.js', `${fooFixture}\n console.log('hello');`); }); it('bit status should not show the component as missing dependencies', () => { const status = helper.command.status(); expect(status).to.not.have.string(statusFailureMsg); }); it('the originallySharedDir should take into account the overrides file', () => { const bitMap = helper.bitMap.read(); expect(bitMap[`${helper.scopes.remote}/foo@0.0.1`].originallySharedDir).to.equal('src'); // without file overrides, the originallySharedDir is 'src/bar'. }); it('should write the dependencies without the sharedDir', () => { const componentDir = path.join(helper.scopes.localPath, 'components/foo'); const packageJson = helper.packageJson.read(componentDir); expect(packageJson.bit.overrides.dependencies).to.deep.equal({ 'file://utils/*': '-' }); }); describe('tagging the component', () => { before(() => { helper.command.tagAllComponents(); }); it('should add back the sharedDir into the overrides', () => { const catFoo = helper.command.catComponent(`${helper.scopes.remote}/foo@latest`); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(catFoo.overrides.dependencies).to.deep.equal({ 'file://src/utils/*': '-' }); }); }); }); describe('adding overrides data on consumer-config to imported component', () => { let overrides; before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fixtures.createComponentBarFoo(); helper.fixtures.addComponentBarFoo(); helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); overrides = { 'bar/*': { peerDependencies: { chai: '2.2.0' }, env: { compiler: 'bit.env/my-special-compiler@0.0.1' } } }; helper.bitJson.addOverrides(overrides); const bitJson = helper.bitJson.read(); bitJson.env = { compiler: 'bit.env/my-special-compiler2@0.0.1' }; helper.bitJson.write(bitJson); }); it('bit status should show the component as modified', () => { const status = helper.command.status(); expect(status).to.have.string('modified'); }); it('bit diff should show the diff', () => { const diff = helper.command.diff('bar/foo'); expect(diff).to.have.string('+ bit.env/my-special-compiler@0.0.1'); expect(diff).to.have.string('+ [ chai@2.2.0 ]'); }); it('bit show should show the settings from the workspace config', () => { const showBar = helper.command.showComponentParsed('bar/foo'); expect(showBar.compiler.name).to.equal('bit.env/my-special-compiler@0.0.1'); expect(showBar.overrides.peerDependencies).to.deep.equal({ chai: '2.2.0' }); }); describe('when the overrides data on consumer config excluded the imported component', () => { before(() => { overrides['bar/*'].exclude = [`${helper.scopes.remote}/*`]; helper.bitJson.addOverrides(overrides); }); it('bit status should not show the component as modified', () => { helper.command.expectStatusToBeClean(); }); it('bit diff should not show any diff', () => { const diff = helper.command.diff('bar/foo'); expect(diff).to.have.string('no diff'); }); it('bit show should not display any compiler', () => { const showBar = helper.command.showComponentParsed('bar/foo'); expect(showBar.compiler).to.be.null; }); }); }); describe('override package.json values', () => { before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fixtures.createComponentBarFoo(); helper.fixtures.addComponentBarFoo(); const overrides = { 'bar/*': { bin: 'my-bin-file.js' } }; helper.bitJson.addOverrides(overrides); }); it('bit show should show the overrides', () => { const show = helper.command.showComponentParsed('bar/foo'); expect(show.overrides) .to.have.property('bin') .equal('my-bin-file.js'); }); describe('tag, export and import the component', () => { let authorScope; before(() => { helper.command.tagAllComponents(); helper.command.exportAllComponents(); authorScope = helper.scopeHelper.cloneLocalScope(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); }); it('should write the values into package.json file', () => { const packageJson = helper.packageJson.read(path.join(helper.scopes.localPath, 'components/bar/foo')); expect(packageJson) .to.have.property('bin') .that.equals('my-bin-file.js'); }); it('should not show the component as modified', () => { helper.command.expectStatusToBeClean(); }); describe('changing the value in the package.json directly (not inside overrides)', () => { before(() => { const compDir = path.join(helper.scopes.localPath, 'components/bar/foo'); const packageJson = helper.packageJson.read(compDir); packageJson.bin = 'my-new-file.js'; helper.packageJson.write(packageJson, compDir); }); it('should not show the component as modified', () => { const status = helper.command.status(); expect(status).to.not.have.string('modified components'); }); }); describe('changing the value in the package.json inside overrides', () => { before(() => { const compDir = path.join(helper.scopes.localPath, 'components/bar/foo'); const packageJson = helper.packageJson.read(compDir); packageJson.bit.overrides.bin = 'my-new-file.js'; helper.packageJson.write(packageJson, compDir); }); it('should show the component as modified', () => { const status = helper.command.status(); expect(status).to.have.string('modified components'); }); it('bit diff should show the field diff', () => { const diff = helper.command.diff('bar/foo'); expect(diff).to.have.string('my-bin-file.js'); expect(diff).to.have.string('my-new-file.js'); }); describe('tagging, exporting and re-importing as author', () => { before(() => { helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.scopeHelper.getClonedLocalScope(authorScope); helper.command.importComponent('bar/foo'); }); it('should not show the component as modified', () => { const status = helper.command.status(); expect(status).to.not.have.string('modified components'); }); it('author bit.json should be rewritten to include a rule of the specific component', () => { const bitJson = helper.bitJson.read(); expect(bitJson.overrides) .to.have.property(`${helper.scopes.remote}/bar/foo`) .that.deep.equals({ bin: 'my-new-file.js' }); }); it('bit show should display the modified field and not the original one', () => { const show = helper.command.showComponentParsed('bar/foo'); expect(show.overrides) .to.have.property('bin') .that.equals('my-new-file.js'); }); }); }); }); }); describe('propagating from a specific rule to a more general rule when propagate field is true', () => { let show; let overrides; before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fixtures.createComponentBarFoo(); helper.fixtures.addComponentBarFoo(); helper.fs.outputFile('baz.js'); helper.command.addComponent('baz.js'); overrides = { '*': { scripts: { build: 'babel build' } }, 'bar/*': { bin: 'my-bin-file.js', scripts: { test: 'mocha test', lint: 'eslint lint' }, propagate: true }, 'bar/foo': { scripts: { test: 'jest test', watch: 'babel watch' }, propagate: true } }; helper.bitJson.addOverrides(overrides); show = helper.command.showComponentParsed(); }); it('should not save the "propagate" field', () => { expect(show.overrides).to.not.have.property('propagate'); }); it('should propagate to a more general rule and save string values that are not in the specific rule', () => { expect(show.overrides) .to.have.property('bin') .that.equals('my-bin-file.js'); }); it('should propagate to a more general rule and merge objects that are in the specific rule', () => { expect(show.overrides).to.have.property('scripts'); expect(show.overrides.scripts) .to.have.property('build') .that.equals('babel build'); expect(show.overrides.scripts) .to.have.property('lint') .that.equals('eslint lint'); expect(show.overrides.scripts) .to.have.property('watch') .that.equals('babel watch'); }); it('should let the more specific rule wins when it contradict a more general rule', () => { expect(show.overrides.scripts).to.have.property('test'); expect(show.overrides.scripts.test).to.equals('jest test'); expect(show.overrides.scripts.test).not.to.equals('mocha test'); }); describe('propagate with exclude', () => { before(() => { overrides['bar/*'].exclude = ['bar/foo']; helper.bitJson.addOverrides(overrides); }); it('should consider the exclude prop and show the overrides accordingly', () => { const output = helper.command.showComponentParsed(); expect(output.overrides).to.not.have.property('bin'); expect(output.overrides).to.have.property('scripts'); expect(output.overrides.scripts).to.have.property('build'); expect(output.overrides.scripts).to.have.property('test'); expect(output.overrides.scripts).to.have.property('watch'); expect(output.overrides.scripts).to.not.have.property('lint'); }); }); describe('tagging the components and then changing the propagate of one component', () => { before(() => { helper.command.tagAllComponents(); const bitJson = helper.bitJson.read(); bitJson.overrides['bar/foo'].propagate = false; helper.bitJson.write(bitJson); }); it('should not affect other components that do not match any overrides criteria', () => { const status = helper.command.statusJson(); expect(status.modifiedComponent).to.not.include('baz@0.0.1'); }); }); }); describe('using "exclude" to exclude component from a rule', () => { before(() => { helper.scopeHelper.reInitLocalScope(); helper.fixtures.createComponentBarFoo(); helper.fixtures.addComponentBarFoo(); }); describe('exclude with an exact id', () => { before(() => { const overrides = { '*': { bin: 'my-bin-file.js', exclude: ['bar/foo'] } }; helper.bitJson.addOverrides(overrides); }); it('should exclude the excluded component from the overrides value', () => { const show = helper.command.showComponentParsed('bar/foo'); expect(show.overrides).to.not.have.property('bin'); }); }); describe('exclude with an wildcards', () => { before(() => { const overrides = { '*': { bin: 'my-bin-file.js', exclude: ['bar/*'] } }; helper.bitJson.addOverrides(overrides); }); it('should exclude the excluded component from the overrides value', () => { const show = helper.command.showComponentParsed('bar/foo'); expect(show.overrides).to.not.have.property('bin'); }); }); }); }); describe('basic validations', () => { describe('when overrides is not an object', () => { before(() => { helper.scopeHelper.reInitLocalScope(); const overrides = ['dependencies']; helper.bitJson.addOverrides(overrides); }); it('any bit command should throw an error', () => { const output = helper.general.runWithTryCatch('bit list'); expect(output).to.have.string('expected overrides to be object, got array'); }); }); describe('when overrides of a component is not an object', () => { before(() => { helper.scopeHelper.reInitLocalScope(); const overrides = { bar: 1234 }; helper.bitJson.addOverrides(overrides); }); it('any bit command should throw an error', () => { const output = helper.general.runWithTryCatch('bit list'); expect(output).to.have.string('expected overrides.bar to be object, got number'); }); }); describe('when a forbidden field is added into overrides of a component', () => { before(() => { helper.scopeHelper.reInitLocalScope(); const overrides = { bar: { name: 'foo' // the name field of package.json is not permitted to change } }; helper.bitJson.addOverrides(overrides); }); it('any bit command should throw an error', () => { const output = helper.general.runWithTryCatch('bit list'); expect(output).to.have.string('found a forbidden field "name" inside "overrides.bar" property'); }); }); describe('when a non-compliant package.json field is added into overrides of a component', () => { before(() => { helper.scopeHelper.reInitLocalScope(); helper.fixtures.createComponentBarFoo(); helper.fixtures.addComponentBarFoo(); const overrides = { 'bar/*': { private: 'foo' // according to npm specs it should be boolean } }; helper.bitJson.addOverrides(overrides); }); it('bit tag should throw an error', () => { const output = helper.general.runWithTryCatch('bit tag -a'); expect(output).to.have.string( 'unable to save Version object, "overrides.private" is a package.json field but is not compliant with npm requirements. Type for field private, was expected to be boolean, not string' ); }); }); describe('when a dependency field is not an object', () => { before(() => { helper.scopeHelper.reInitLocalScope(); const overrides = { bar: { dependencies: 1234 } }; helper.bitJson.addOverrides(overrides); }); it('any bit command should throw an error', () => { const output = helper.general.runWithTryCatch('bit list'); expect(output).to.have.string('expected overrides.bar.dependencies to be object, got number'); }); }); describe('when a dependency rule is not a string', () => { before(() => { helper.scopeHelper.reInitLocalScope(); const overrides = { foo: { dependencies: { bar: false } } }; helper.bitJson.addOverrides(overrides); }); it('any bit command should throw an error', () => { const output = helper.general.runWithTryCatch('bit list'); expect(output).to.have.string('expected overrides.foo.dependencies.bar to be string, got boolean'); }); }); describe('when "exclude" prop that is not an array', () => { before(() => { helper.scopeHelper.reInitLocalScope(); const overrides = { '*': { exclude: 'bar' } }; helper.bitJson.addOverrides(overrides); }); it('any bit command should throw an error', () => { const output = helper.general.runWithTryCatch('bit list'); expect(output).to.have.string('expected overrides.*.exclude to be array, got string'); }); }); }); describe('export a component with compiler then import', () => { before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); helper.fixtures.createComponentBarFoo(); helper.fixtures.addComponentBarFoo(); helper.env.importDummyCompiler(); helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.command.importComponent('bar/foo'); }); it('should not add the component into the overrides of the workspace because nothing has changed', () => { const bitJson = helper.bitJson.read(); expect(bitJson).to.not.have.property('overrides'); }); }); });
the_stack
import { IContext } from "./context"; import { Graph, alg } from "graphlib"; import hash from "object-hash"; import { RollingCache } from "./rollingcache"; import { ICache } from "./icache"; import * as _ from "lodash"; import { tsModule } from "./tsproxy"; import * as tsTypes from "typescript"; import { blue, yellow, green } from "colors/safe"; import { emptyDirSync, pathExistsSync, readdirSync, removeSync, statSync } from "fs-extra"; import { formatHost } from "./diagnostics-format-host"; import { NoCache } from "./nocache"; export interface ICode { code: string; map?: string; dts?: tsTypes.OutputFile; dtsmap?: tsTypes.OutputFile; references?: string[]; } interface INodeLabel { dirty: boolean; } export interface IDiagnostics { flatMessage: string; formatted: string; fileLine?: string; category: tsTypes.DiagnosticCategory; code: number; type: string; } interface ITypeSnapshot { id: string; snapshot: tsTypes.IScriptSnapshot | undefined; } export function convertEmitOutput(output: tsTypes.EmitOutput, references?: string[]): ICode { const out: ICode = { code: "", references }; output.outputFiles.forEach((e) => { if (_.endsWith(e.name, ".d.ts")) out.dts = e; else if (_.endsWith(e.name, ".d.ts.map")) out.dtsmap = e; else if (_.endsWith(e.name, ".map")) out.map = e.text; else out.code = e.text; }); return out; } export function getAllReferences(importer: string, snapshot: tsTypes.IScriptSnapshot | undefined, options: tsTypes.CompilerOptions) { if (!snapshot) return []; const info = tsModule.preProcessFile(snapshot.getText(0, snapshot.getLength()), true, true); return _.compact(_.concat(info.referencedFiles, info.importedFiles).map((reference) => { const resolved = tsModule.nodeModuleNameResolver(reference.fileName, importer, options, tsModule.sys); return resolved.resolvedModule ? resolved.resolvedModule.resolvedFileName : undefined; })); } export function convertDiagnostic(type: string, data: tsTypes.Diagnostic[]): IDiagnostics[] { return _.map(data, (diagnostic) => { const entry: IDiagnostics = { flatMessage: tsModule.flattenDiagnosticMessageText(diagnostic.messageText, "\n"), formatted: tsModule.formatDiagnosticsWithColorAndContext(data, formatHost), category: diagnostic.category, code: diagnostic.code, type, }; if (diagnostic.file && diagnostic.start !== undefined) { const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); entry.fileLine = `${diagnostic.file.fileName}(${line + 1},${character + 1})`; } return entry; }); } export class TsCache { private cacheVersion = "9"; private cachePrefix = "rpt2_"; private dependencyTree: Graph; private ambientTypes: ITypeSnapshot[]; private ambientTypesDirty = false; private cacheDir: string | undefined; private codeCache!: ICache<ICode | undefined>; private typesCache!: ICache<string>; private semanticDiagnosticsCache!: ICache<IDiagnostics[]>; private syntacticDiagnosticsCache!: ICache<IDiagnostics[]>; private hashOptions = { algorithm: "sha1", ignoreUnknown: false }; constructor(private noCache: boolean, hashIgnoreUnknown: boolean, private host: tsTypes.LanguageServiceHost, private cacheRoot: string, private options: tsTypes.CompilerOptions, private rollupConfig: any, rootFilenames: string[], private context: IContext) { this.hashOptions.ignoreUnknown = hashIgnoreUnknown; if (!noCache) { this.cacheDir = `${this.cacheRoot}/${this.cachePrefix}${hash( { version: this.cacheVersion, rootFilenames, options: this.options, rollupConfig: this.rollupConfig, tsVersion: tsModule.version, }, this.hashOptions, )}`; } this.dependencyTree = new Graph({ directed: true }); this.dependencyTree.setDefaultNodeLabel((_node: string) => ({ dirty: false })); const automaticTypes = _.map(tsModule.getAutomaticTypeDirectiveNames(options, tsModule.sys), (entry) => tsModule.resolveTypeReferenceDirective(entry, undefined, options, tsModule.sys)) .filter((entry) => entry.resolvedTypeReferenceDirective && entry.resolvedTypeReferenceDirective.resolvedFileName) .map((entry) => entry.resolvedTypeReferenceDirective!.resolvedFileName!); this.ambientTypes = _.filter(rootFilenames, (file) => _.endsWith(file, ".d.ts")) .concat(automaticTypes) .map((id) => ({ id, snapshot: this.host.getScriptSnapshot(id) })); this.init(); this.checkAmbientTypes(); } public clean() { if (pathExistsSync(this.cacheRoot)) { const entries = readdirSync(this.cacheRoot); entries.forEach((e) => { const dir = `${this.cacheRoot}/${e}`; if (e.startsWith(this.cachePrefix) && statSync(dir).isDirectory) { this.context.info(blue(`cleaning cache: ${dir}`)); emptyDirSync(`${dir}`); removeSync(`${dir}`); } else this.context.debug(`not cleaning ${dir}`); }); } this.init(); } public setDependency(importee: string, importer: string): void { // importee -> importer this.context.debug(`${blue("dependency")} '${importee}'`); this.context.debug(` imported by '${importer}'`); this.dependencyTree.setEdge(importer, importee); } public walkTree(cb: (id: string) => void | false): void { const acyclic = alg.isAcyclic(this.dependencyTree); if (acyclic) { _.each(alg.topsort(this.dependencyTree), (id: string) => cb(id)); return; } this.context.info(yellow("import tree has cycles")); _.each(this.dependencyTree.nodes(), (id: string) => cb(id)); } public done() { this.context.info(blue("rolling caches")); this.codeCache.roll(); this.semanticDiagnosticsCache.roll(); this.syntacticDiagnosticsCache.roll(); this.typesCache.roll(); } public getCompiled(id: string, snapshot: tsTypes.IScriptSnapshot, transform: () => ICode | undefined): ICode | undefined { if (this.noCache) { this.context.info(`${blue("transpiling")} '${id}'`); this.markAsDirty(id); return transform(); } const name = this.makeName(id, snapshot); this.context.info(`${blue("transpiling")} '${id}'`); this.context.debug(` cache: '${this.codeCache.path(name)}'`); if (this.codeCache.exists(name) && !this.isDirty(id, false)) { this.context.debug(green(" cache hit")); const data = this.codeCache.read(name); if (data) { this.codeCache.write(name, data); return data; } else this.context.warn(yellow(" cache broken, discarding")); } this.context.debug(yellow(" cache miss")); const transformedData = transform(); this.codeCache.write(name, transformedData); this.markAsDirty(id); return transformedData; } public getSyntacticDiagnostics(id: string, snapshot: tsTypes.IScriptSnapshot, check: () => tsTypes.Diagnostic[]): IDiagnostics[] { return this.getDiagnostics("syntax", this.syntacticDiagnosticsCache, id, snapshot, check); } public getSemanticDiagnostics(id: string, snapshot: tsTypes.IScriptSnapshot, check: () => tsTypes.Diagnostic[]): IDiagnostics[] { return this.getDiagnostics("semantic", this.semanticDiagnosticsCache, id, snapshot, check); } private checkAmbientTypes(): void { if (this.noCache) { this.ambientTypesDirty = true; return; } this.context.debug(blue("Ambient types:")); const typeNames = _.filter(this.ambientTypes, (snapshot) => snapshot.snapshot !== undefined) .map((snapshot) => { this.context.debug(` ${snapshot.id}`); return this.makeName(snapshot.id, snapshot.snapshot!); }); // types dirty if any d.ts changed, added or removed this.ambientTypesDirty = !this.typesCache.match(typeNames); if (this.ambientTypesDirty) this.context.info(yellow("ambient types changed, redoing all semantic diagnostics")); _.each(typeNames, (name) => this.typesCache.touch(name)); } private getDiagnostics(type: string, cache: ICache<IDiagnostics[]>, id: string, snapshot: tsTypes.IScriptSnapshot, check: () => tsTypes.Diagnostic[]): IDiagnostics[] { if (this.noCache) { this.markAsDirty(id); return convertDiagnostic(type, check()); } const name = this.makeName(id, snapshot); this.context.debug(` cache: '${cache.path(name)}'`); if (cache.exists(name) && !this.isDirty(id, true)) { this.context.debug(green(" cache hit")); const data = cache.read(name); if (data) { cache.write(name, data); return data; } else this.context.warn(yellow(" cache broken, discarding")); } this.context.debug(yellow(" cache miss")); const convertedData = convertDiagnostic(type, check()); cache.write(name, convertedData); this.markAsDirty(id); return convertedData; } private init() { if (this.noCache) { this.codeCache = new NoCache<ICode>(); this.typesCache = new NoCache<string>(); this.syntacticDiagnosticsCache = new NoCache<IDiagnostics[]>(); this.semanticDiagnosticsCache = new NoCache<IDiagnostics[]>(); } else { if (this.cacheDir === undefined) throw new Error(`this.cacheDir undefined`); this.codeCache = new RollingCache<ICode>(`${this.cacheDir}/code`, true); this.typesCache = new RollingCache<string>(`${this.cacheDir}/types`, true); this.syntacticDiagnosticsCache = new RollingCache<IDiagnostics[]>(`${this.cacheDir}/syntacticDiagnostics`, true); this.semanticDiagnosticsCache = new RollingCache<IDiagnostics[]>(`${this.cacheDir}/semanticDiagnostics`, true); } } private markAsDirty(id: string): void { this.dependencyTree.setNode(id, { dirty: true }); } // returns true if node or any of its imports or any of global types changed private isDirty(id: string, checkImports: boolean): boolean { const label = this.dependencyTree.node(id) as INodeLabel; if (!label) return false; if (!checkImports || label.dirty) return label.dirty; if (this.ambientTypesDirty) return true; const dependencies = alg.dijkstra(this.dependencyTree, id); return _.some(dependencies, (dependency, node) => { if (!node || dependency.distance === Infinity) return false; const l = this.dependencyTree.node(node) as INodeLabel | undefined; const dirty = l === undefined ? true : l.dirty; if (dirty) this.context.debug(` import changed: ${node}`); return dirty; }); } private makeName(id: string, snapshot: tsTypes.IScriptSnapshot) { const data = snapshot.getText(0, snapshot.getLength()); return hash({ data, id }, this.hashOptions); } }
the_stack
import { Application } from "../../automation"; import * as assert from "assert"; import * as path from "path"; import { AppiumClient, AppiumHelper, Platform } from "./helpers/appiumHelper"; import { SmokeTestsConstants } from "./helpers/smokeTestsConstants"; import { findFile, findStringInFile, isLoggedInExpo, sleep, waitUntil } from "./helpers/utilities"; import { androidEmulatorManager, iosSimulatorManager, vscodeManager } from "./main"; import { TestRunArguments } from "./helpers/testConfigProcessor"; import { SmokeTestLogger } from "./helpers/smokeTestLogger"; import TestProject from "./helpers/testProject"; import AutomationHelper from "./helpers/AutomationHelper"; import AndroidEmulatorManager from "./helpers/androidEmulatorManager"; const EXPO_APP_LAUNCH_TIMEOUT = 120_000; const ExpoSuccessPattern = "Tunnel ready"; const ExpoFailurePattern = "XDLError"; const EXPO_APP_PACKAGE_NAME = SmokeTestsConstants.expoPackageName; const EXPO_APP_ACTIVITY_NAME = `${SmokeTestsConstants.expoPackageName}.experience.HomeActivity`; const ExpoTunnelDebugConfigName = "Debug in Exponent (Tunnel)"; const ExpoLanDebugConfigName = "Debug in Exponent (LAN)"; const ExpoLocalDebugConfigName = "Debug in Exponent (Local)"; const ExpoSetBreakpointOnLine = 1; // Time for Android Expo Debug Test before it reaches timeout const debugExpoTestTime = SmokeTestsConstants.expoTestTimeout; const expoLogginErrorMessage = "It seems you are not currently logged into Expo account. To successfully pass this test, you must be logged into Expo account"; interface ExpoLaunch { successful: boolean; failed: boolean; } export function startExpoTests( expoProject: TestProject, pureProject: TestProject, testParameters: TestRunArguments, ): void { describe("Expo tests", () => { let app: Application; let expoFirstLaunch = true; let client: AppiumClient; let automationHelper: AutomationHelper; async function initApp( workspaceOrFolder: string, sessionName?: string, locale?: string, ): Promise<Application> { app = await vscodeManager.runVSCode(workspaceOrFolder, sessionName, locale); automationHelper = new AutomationHelper(app); return app; } async function disposeAll() { try { SmokeTestLogger.info("Dispose all ..."); if (app) { SmokeTestLogger.info("Stopping React Native packager ..."); await automationHelper.runCommandWithRetry( SmokeTestsConstants.stopPackagerCommand, ); await sleep(3000); SmokeTestLogger.info("Stopping application ..."); await app.stop(); } if (client) { try { SmokeTestLogger.info("Closing application ..."); await client.closeApp(); SmokeTestLogger.info("Deleting session ..."); await client.deleteSession(); } catch (err) { SmokeTestLogger.error(err); } } SmokeTestLogger.info("Clearing android application ..."); AndroidEmulatorManager.closeApp(EXPO_APP_PACKAGE_NAME); } catch (error) { SmokeTestLogger.error("Error while disposeAll:"); SmokeTestLogger.error(error); // throw error; } } afterEach(async function () { this.timeout(SmokeTestsConstants.smokeTestAfterEachTimeout); await disposeAll(); }); async function findExpoSuccessAndFailurePatterns( filePath: string, successPattern: string, failurePattern: string, ): Promise<ExpoLaunch> { let result: ExpoLaunch | undefined = undefined; const condition = () => { let expoStarted = findStringInFile(filePath, successPattern); let expoFailed = findStringInFile(filePath, failurePattern); SmokeTestLogger.info(`Searching for Expo launch logging patterns ...`); if (expoStarted || expoFailed) { result = { successful: expoStarted, failed: expoFailed }; SmokeTestLogger.info( `Expo launch status patterns found: ${JSON.stringify(result, null, 2)}`, ); return true; } else { return false; } }; await waitUntil(condition, EXPO_APP_LAUNCH_TIMEOUT, 5000); if (result) { return result; } else { SmokeTestLogger.info(`Expo launch logging patterns are not found`); return { successful: false, failed: false }; } } function findExpoURLInLogFile() { const match = vscodeManager.findPatternInLogs( /exp:\/\/\d+\.\d+\.\d+\.\d+\:\d+/gm, SmokeTestsConstants.ReactNativeRunExpoLogFileName, ); if (!match) return null; let expoURL = match[0]; SmokeTestLogger.info(`Found Expo URL: ${expoURL}`); return expoURL; } async function runExpoDebugScenario( logFilePath: string, testName: string, debugConfigName: string, triesToLaunchApp: number, ) { SmokeTestLogger.info(`${testName}: Starting debugging`); // Scan logs only if launch retries provided (Expo Tunnel scenarios) if (triesToLaunchApp <= 1) { await automationHelper.runDebugScenarioWithRetry(debugConfigName); await automationHelper.runCommandWithRetry("Output: Focus on Output View"); } else { for (let retry = 1; retry <= triesToLaunchApp; retry++) { let expoLaunchStatus: ExpoLaunch; await automationHelper.runDebugScenarioWithRetry(debugConfigName); await automationHelper.runCommandWithRetry("Output: Focus on Output View"); expoLaunchStatus = await findExpoSuccessAndFailurePatterns( logFilePath, ExpoSuccessPattern, ExpoFailurePattern, ); if (expoLaunchStatus.successful) { break; } else { if (retry === triesToLaunchApp) { assert.fail(`App start has failed after ${retry} retries`); } SmokeTestLogger.warn(`Attempt to start #${retry} failed, retrying...`); await automationHelper.stopDebuggingWithRetry(); } } } } async function expoTest( project: TestProject, testName: string, debugConfigName: string, platform: Platform.AndroidExpo | Platform.iOSExpo, triesToLaunchApp: number, ) { let logFilePath = ""; app = await initApp(project.workspaceDirectory, testName); SmokeTestLogger.info( `${testName}: ${project.workspaceDirectory} directory is opened in VS Code`, ); await automationHelper.openFileWithRetry(project.projectEntryPointFile); await app.workbench.editors.scrollTop(); SmokeTestLogger.info(`${testName}: ${project.projectEntryPointFile} file is opened`); await app.workbench.debug.setBreakpointOnLine(ExpoSetBreakpointOnLine); SmokeTestLogger.info( `${testName}: Breakpoint is set on line ${ExpoSetBreakpointOnLine}`, ); SmokeTestLogger.info(`${testName}: Chosen debug configuration: ${debugConfigName}`); if (process.env.REACT_NATIVE_TOOLS_LOGS_DIR) { logFilePath = path.join( process.env.REACT_NATIVE_TOOLS_LOGS_DIR, SmokeTestsConstants.ReactNativeLogFileName, ); } else { assert.fail("REACT_NATIVE_TOOLS_LOGS_DIR is not defined"); } await runExpoDebugScenario(logFilePath, testName, debugConfigName, triesToLaunchApp); await app.workbench.editors.waitForTab("Expo QR Code", false, true, 2400); await app.workbench.editors.waitForActiveTab("Expo QR Code", false, true); SmokeTestLogger.info(`${testName}: 'Expo QR Code' tab found`); let expoURL = findExpoURLInLogFile(); if (expoURL === null) { assert.fail("Expo URL pattern is not found"); return; } if (platform === Platform.iOSExpo) { const device = iosSimulatorManager.getSimulator().name; let appFile = findFile(SmokeTestsConstants.iOSExpoAppsCacheDir, /.*\.(app)/); if (!appFile) { throw new Error( `iOS Expo app is not found in ${SmokeTestsConstants.iOSExpoAppsCacheDir}`, ); } const appPath = path.join(SmokeTestsConstants.iOSExpoAppsCacheDir, appFile); const opts = AppiumHelper.prepareAttachOptsForIosApp(device, appPath); client = await AppiumHelper.webdriverAttach(opts); await AppiumHelper.openExpoApplication( Platform.iOS, client, expoURL, project.workspaceDirectory, expoFirstLaunch, ); expoFirstLaunch = false; SmokeTestLogger.info( `${testName}: Waiting ${SmokeTestsConstants.expoAppBuildAndInstallTimeout}ms until Expo app is ready...`, ); await sleep(SmokeTestsConstants.expoAppBuildAndInstallTimeout); await AppiumHelper.disableExpoErrorRedBox(client); await AppiumHelper.disableDevMenuInformationalMsg(client, Platform.iOSExpo); await AppiumHelper.enableRemoteDebugJS(client, Platform.iOSExpo); await sleep(5 * 1000); } else { expoURL = expoURL as string; const opts = AppiumHelper.prepareAttachOptsForAndroidActivity( EXPO_APP_PACKAGE_NAME, EXPO_APP_ACTIVITY_NAME, androidEmulatorManager.getEmulatorId(), ); client = await AppiumHelper.webdriverAttach(opts); // TODO Add listener to trigger that main expo app has been ran await AppiumHelper.openExpoApplication( Platform.Android, client, expoURL, project.workspaceDirectory, ); // TODO Add listener to trigger that child expo app has been ran instead of using timeout SmokeTestLogger.info( `${testName}: Waiting ${SmokeTestsConstants.expoAppBuildAndInstallTimeout}ms until Expo app is ready...`, ); await sleep(SmokeTestsConstants.expoAppBuildAndInstallTimeout); await AppiumHelper.disableDevMenuInformationalMsg(client, Platform.AndroidExpo); await sleep(2 * 1000); await AppiumHelper.enableRemoteDebugJS(client, Platform.AndroidExpo); await app.workbench.debug.waitForDebuggingToStart(); } SmokeTestLogger.info(`${testName}: Debugging started`); // Workaround for Windows platform to avoid incorrect work of dispatching keybindings // after opening "Expo QR Code" tab await app.workbench.editor.waitForEditorFocus(project.projectEntryPointFile, 1); await automationHelper.waitForStackFrameWithRetry( sf => sf.name === project.projectEntryPointFile && sf.lineNumber === ExpoSetBreakpointOnLine, `looking for ${project.projectEntryPointFile} and line ${ExpoSetBreakpointOnLine}`, ); SmokeTestLogger.info(`${testName}: Stack frame found`); await app.workbench.debug.stepOver(); // Wait for debug string to be rendered in debug console await sleep(SmokeTestsConstants.debugConsoleSearchTimeout); SmokeTestLogger.info( `${testName}: Searching for \"Test output from debuggee\" string in console`, ); await automationHelper.runCommandWithRetry("Debug: Focus on Debug Console View"); let found = await automationHelper.waitForOutputWithRetry("Test output from debuggee"); assert.notStrictEqual( found, false, '"Test output from debuggee" string is missing in debug console', ); SmokeTestLogger.success(`${testName}: \"Test output from debuggee\" string is found`); await automationHelper.disconnectFromDebuggerWithRetry(); SmokeTestLogger.info(`${testName}: Debugging is stopped`); } if (testParameters.RunAndroidTests) { it("Android Pure RN app Expo test(LAN)", async function () { this.timeout(debugExpoTestTime); await expoTest( pureProject, "Android pure RN Expo test(LAN)", ExpoLanDebugConfigName, Platform.AndroidExpo, 1, ); }); it("Android Expo app Debug test(LAN)", async function () { this.timeout(debugExpoTestTime); await expoTest( expoProject, "Android Expo Debug test(LAN)", ExpoLanDebugConfigName, Platform.AndroidExpo, 1, ); }); it("Android Expo app Debug test(Tunnel)", async function () { this.timeout(debugExpoTestTime); if (!isLoggedInExpo()) { assert.fail(expoLogginErrorMessage); } await expoTest( expoProject, "Android Expo Debug test(Tunnel)", ExpoTunnelDebugConfigName, Platform.AndroidExpo, 5, ); }); it("Android Expo app Debug test(localhost)", async function () { this.timeout(debugExpoTestTime); await expoTest( expoProject, "Android Expo Debug test(localhost)", ExpoLocalDebugConfigName, Platform.AndroidExpo, 1, ); }); } if (process.platform === "darwin" && testParameters.RunIosTests) { it("iOS Pure RN app Expo test(LAN)", async function () { this.timeout(debugExpoTestTime); await expoTest( pureProject, "iOS pure RN Expo test(LAN)", ExpoLanDebugConfigName, Platform.iOSExpo, 1, ); }); it("iOS Expo app Debug test(LAN)", async function () { this.timeout(debugExpoTestTime); await expoTest( expoProject, "iOS Expo Debug test(LAN)", ExpoLanDebugConfigName, Platform.iOSExpo, 1, ); }); it("iOS Expo app Debug test(localhost)", async function () { this.timeout(debugExpoTestTime); await expoTest( expoProject, "iOS Expo Debug test(localhost)", ExpoLocalDebugConfigName, Platform.iOSExpo, 1, ); }); it("iOS Expo app Debug test(Tunnel)", async function () { this.timeout(debugExpoTestTime); if (!isLoggedInExpo()) { assert.fail(expoLogginErrorMessage); } await expoTest( expoProject, "iOS Expo Debug test(Tunnel)", ExpoTunnelDebugConfigName, Platform.iOSExpo, 5, ); }); } }); }
the_stack
import { fixture, fixtureCleanup } from '@open-wc/testing/index-no-side-effects'; import { assert } from 'chai'; import { customElement, html, LitElement, property } from 'lit-element'; import { consumer, createContextLink, provider } from './context'; class Parent { prop1 = 1; } class Child extends Parent { prop2 = 2; } class GrandChild extends Child { prop3 = 3; } const [provideOuterProviderInactiveKey, consumeOuterProviderInactiveKey] = createContextLink<string>(); const [provideOuterProviderKey, consumeOuterProviderKey] = createContextLink<string>(); const [provideProviderKey, consumeProviderKey] = createContextLink<string>(); const [, consumeUnprovidedKey] = createContextLink<string>(); const [provideOuterUnobservedKey] = createContextLink<string>(); const [provideConsumerOptionalPropKey, consumeConsumerOptionalPropKey] = createContextLink<string>(); const [provideSubtypeKey, consumeSubtypeKey] = createContextLink<Child>(); const [provideSelfProvidedKey, consumeSelfProvidedKey] = createContextLink<string>(); @customElement('milo-outer-context-provider-test') @provider class OuterContextProvider extends LitElement { @provideOuterProviderInactiveKey() outerProviderInactiveKey = 'outer_provider-outer_provider_inactive-val0'; @property() @provideOuterProviderKey() outerProviderKey = 'outer_provider-outer_provider-val0'; // The same context is provided by multiple properties, the last one is used. @property() @provideProviderKey() ignoredProviderKey = 'ignored_outer_provider-provider-val0'; @property() @provideProviderKey() providerKey = 'outer_provider-provider-val0'; @property() @provideOuterUnobservedKey() outerUnobservedKey = 'outer_provider-outer_unobserved-val0'; @property() unprovidedKey = 'outer_provider-unprovided-val0'; @property() @provideConsumerOptionalPropKey() consumerOptionalPropKey = 'outer_provider-consumer_optional_pro-val0'; // // This should not compile because Parent is not assignable to Child. // @provideSubtypeKey // parent = new Parent(); @provideSubtypeKey() child = new GrandChild(); // This should compile without warning because GrandChild can be assigned to // parent. @provideSubtypeKey() grandChild = new GrandChild(); } @customElement('milo-inner-context-provider-test') @provider class InnerContextProvider extends LitElement { @property() @provideProviderKey() providerKey = 'inner_provider-provider-val0'; } @customElement('milo-global-context-provider-test') @provider class GlobalContextProvider extends LitElement { @property() @provideProviderKey({ global: true }) providerKey = 'global_provider-provider-val0'; } @customElement('milo-context-consumer-test') @provider @consumer class ContextConsumer extends LitElement { @property() @consumeOuterProviderInactiveKey() outerProviderInactiveKey = 'local-outer_provider_inactive'; @property() @consumeOuterProviderKey() outerProviderKey = 'local-output_provider'; @consumeProviderKey() providerKey = 'local-provider'; // Multiple props can map to the same context. @consumeProviderKey() providerKeyWithAnotherName = 'local-provider'; @property() @consumeUnprovidedKey() unprovidedKey = 'local-unprovided'; @property() outerUnobservedKey = 'local-unobserved'; // This should compile without warnings. @property() @consumeConsumerOptionalPropKey() consumerOptionalPropKey?: string; // This should compile without warning because Child is assignable to Parent. @consumeSubtypeKey() parent = new Parent(); // // This should not compile because Child is not assignable to GrandChild. // @consumeSubtypeKey // grandChild = new GrandChild(); @consumeSubtypeKey() child = new Child(); @property() @provideSelfProvidedKey() selfProvided = 'local-self_provided'; @property() @consumeSelfProvidedKey() selfProvided2 = ''; // Help testing that the property is not set too many times, particularly // when the element is first rendered. setterCallCount = 0; @consumeProviderKey() set providerKeySetter(_newVal: string) { this.setterCallCount++; } } @customElement('milo-context-consumer-wrapper-test') export class ContextConsumerWrapper extends LitElement { protected render() { return html` <milo-context-consumer-test></milo-context-consumer-test> `; } } // TODO(weiweilin): test what happens when ContextProvider is disconnected from // DOM then reconnected to DOM. describe('context', () => { describe('ContextProvider', () => { it('should provide context to descendent context consumers', async () => { after(fixtureCleanup); const outerProvider = await fixture<OuterContextProvider>(html` <milo-outer-context-provider-test> <milo-inner-context-provider-test> <milo-context-consumer-test id="inner-consumer"> </milo-context-consumer-test> </milo-inner-context-provider-test> <milo-context-consumer-test id="outer-consumer"> </milo-context-consumer-test> <milo-outer-context-provider> </milo-outer-context-provider ></milo-outer-context-provider-test> `); const innerProvider = outerProvider.querySelector('milo-inner-context-provider-test')!.shadowRoot! .host as InnerContextProvider; const outerConsumer = outerProvider.querySelector('#outer-consumer')!.shadowRoot!.host as ContextConsumer; const innerConsumer = outerProvider.querySelector('#inner-consumer')!.shadowRoot!.host as ContextConsumer; assert.strictEqual(outerConsumer.outerProviderInactiveKey, 'outer_provider-outer_provider_inactive-val0'); assert.strictEqual(outerConsumer.outerProviderKey, 'outer_provider-outer_provider-val0'); assert.strictEqual(outerConsumer.providerKey, 'outer_provider-provider-val0'); assert.strictEqual(outerConsumer.providerKeyWithAnotherName, 'outer_provider-provider-val0'); assert.strictEqual(outerConsumer.outerUnobservedKey, 'local-unobserved'); assert.strictEqual(outerConsumer.unprovidedKey, 'local-unprovided'); assert.strictEqual(outerConsumer.selfProvided2, 'local-self_provided'); assert.strictEqual(outerConsumer.setterCallCount, 1); assert.strictEqual(innerConsumer.outerProviderInactiveKey, 'outer_provider-outer_provider_inactive-val0'); assert.strictEqual(innerConsumer.outerProviderKey, 'outer_provider-outer_provider-val0'); assert.strictEqual(innerConsumer.providerKey, 'inner_provider-provider-val0'); assert.strictEqual(innerConsumer.providerKeyWithAnotherName, 'inner_provider-provider-val0'); assert.strictEqual(innerConsumer.outerUnobservedKey, 'local-unobserved'); assert.strictEqual(innerConsumer.unprovidedKey, 'local-unprovided'); assert.strictEqual(innerConsumer.setterCallCount, 1); // Update outer provider. outerProvider.outerProviderInactiveKey = 'outer_provider-outer_provider_inactive-val1'; outerProvider.outerProviderKey = 'outer_provider-outer_provider-val1'; outerProvider.providerKey = 'outer_provider-provider-val1'; outerProvider.outerUnobservedKey = 'outer_provider-unobserved_val1'; outerProvider.unprovidedKey = 'outer_provider-local_val1'; await outerProvider.updateComplete; // outerConsumer updated. assert.strictEqual(outerConsumer.outerProviderInactiveKey, 'outer_provider-outer_provider_inactive-val0'); assert.strictEqual(outerConsumer.outerProviderKey, 'outer_provider-outer_provider-val1'); assert.strictEqual(outerConsumer.providerKey, 'outer_provider-provider-val1'); assert.strictEqual(outerConsumer.providerKeyWithAnotherName, 'outer_provider-provider-val1'); assert.strictEqual(outerConsumer.outerUnobservedKey, 'local-unobserved'); assert.strictEqual(outerConsumer.unprovidedKey, 'local-unprovided'); assert.strictEqual(outerConsumer.setterCallCount, 2); // innerConsumer.providerKey unchanged, other properties updated. assert.strictEqual(innerConsumer.outerProviderInactiveKey, 'outer_provider-outer_provider_inactive-val0'); assert.strictEqual(innerConsumer.outerProviderKey, 'outer_provider-outer_provider-val1'); assert.strictEqual(innerConsumer.providerKey, 'inner_provider-provider-val0'); assert.strictEqual(innerConsumer.providerKeyWithAnotherName, 'inner_provider-provider-val0'); assert.strictEqual(innerConsumer.unprovidedKey, 'local-unprovided'); assert.strictEqual(innerConsumer.outerUnobservedKey, 'local-unobserved'); assert.strictEqual(innerConsumer.setterCallCount, 1); // Update inner provider. innerProvider.providerKey = 'inner_provider-provider-val1'; await innerProvider.updateComplete; // outerConsumer unchanged. assert.strictEqual(outerConsumer.outerProviderInactiveKey, 'outer_provider-outer_provider_inactive-val0'); assert.strictEqual(outerConsumer.outerProviderKey, 'outer_provider-outer_provider-val1'); assert.strictEqual(outerConsumer.providerKey, 'outer_provider-provider-val1'); assert.strictEqual(outerConsumer.providerKeyWithAnotherName, 'outer_provider-provider-val1'); assert.strictEqual(outerConsumer.outerUnobservedKey, 'local-unobserved'); assert.strictEqual(outerConsumer.unprovidedKey, 'local-unprovided'); assert.strictEqual(outerConsumer.setterCallCount, 2); // innerConsumer.providerKey updated, other properties unchanged. assert.strictEqual(innerConsumer.outerProviderInactiveKey, 'outer_provider-outer_provider_inactive-val0'); assert.strictEqual(innerConsumer.outerProviderKey, 'outer_provider-outer_provider-val1'); assert.strictEqual(innerConsumer.providerKey, 'inner_provider-provider-val1'); assert.strictEqual(innerConsumer.providerKeyWithAnotherName, 'inner_provider-provider-val1'); assert.strictEqual(innerConsumer.outerUnobservedKey, 'local-unobserved'); assert.strictEqual(innerConsumer.unprovidedKey, 'local-unprovided'); assert.strictEqual(innerConsumer.setterCallCount, 2); }); it('should provide context to any context consumers if global is set to true', async () => { after(fixtureCleanup); const rootEle = await fixture<HTMLDivElement>(html` <div> <milo-global-context-provider-test> </milo-global-context-provider-test> <milo-context-consumer-wrapper-test></milo-context-consumer-wrapper-test> </div> `); const globalProvider = rootEle.querySelector('milo-global-context-provider-test')!.shadowRoot! .host as GlobalContextProvider; const consumer = rootEle .querySelector('milo-context-consumer-wrapper-test')! .shadowRoot!.querySelector('milo-context-consumer-test')!.shadowRoot!.host as ContextConsumer; assert.strictEqual(consumer.providerKey, 'global_provider-provider-val0'); // Update inner provider. globalProvider.providerKey = 'global_provider-provider-val1'; await globalProvider.updateComplete; // consumer.providerKey updated assert.strictEqual(consumer.providerKey, 'global_provider-provider-val1'); }); }); });
the_stack
import BN from "bn.js"; import * as bs58 from "bs58"; import * as crypto from "crypto"; import { ec as EC, eddsa as EDDSA } from "elliptic"; import versions, { VersionBytes } from "../versions"; // Implements BIP-32: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki // Added ED25519 support: https://github.com/satoshilabs/slips/blob/master/slip-0010.md export enum Algorithm { secp256k1 = "secp256k1", ed25519 = "ed25519", } const SUPPORTED_ALGORITHMS = [Algorithm.secp256k1, Algorithm.ed25519]; const HARDENED_KEY_OFFSET = 0x80000000; // 2^31 const secp256k1 = new EC(Algorithm.secp256k1); const ed25519 = new EDDSA(Algorithm.ed25519); export interface HDKeyConstructorOptions { algorithm?: Algorithm; chainCode: Buffer; privateKey?: Buffer | null; publicKey?: Buffer | null; index?: number; depth?: number; parentFingerprint?: Buffer; version?: VersionBytes; } export class HDKey { private readonly _algorithm: Algorithm; private readonly _privateKey: Buffer | null = null; private readonly _publicKey: Buffer; private readonly _chainCode: Buffer; private readonly _index: number; private readonly _depth: number; private readonly _parentFingerprint: Buffer; private readonly _version: VersionBytes; private readonly _keyIdentifier: Buffer; constructor({ algorithm, privateKey, publicKey, chainCode, index, depth, parentFingerprint, version, }: HDKeyConstructorOptions) { if (algorithm && SUPPORTED_ALGORITHMS.indexOf(algorithm) === -1) { throw new Error(`unsupported algorithm: ${algorithm}`); } this._algorithm = algorithm || Algorithm.secp256k1; if (!privateKey && !publicKey) { throw new Error("either private key or public key must be provided"); } if (privateKey) { this._privateKey = privateKey; this._publicKey = publicFromPrivateKey(privateKey, this.algorithm); } else { this._publicKey = publicKey as Buffer; } this._chainCode = chainCode; this._depth = depth || 0; this._index = index || 0; this._parentFingerprint = parentFingerprint || Buffer.alloc(4); this._keyIdentifier = hash160(this._publicKey); this._version = version || versions.bitcoinMain; } public static parseMasterSeed(seed: Buffer, version?: VersionBytes): HDKey { return this.parseSeedWithKey( Algorithm.secp256k1, "Bitcoin seed", seed, version ); } public static parseEd25519Seed(seed: Buffer, version?: VersionBytes): HDKey { return this.parseSeedWithKey( Algorithm.ed25519, "ed25519 seed", seed, version ); } private static parseSeedWithKey( algorithm: Algorithm, key: string, seed: Buffer, version?: VersionBytes ): HDKey { const i = hmacSha512(key, seed); const iL = i.slice(0, 32); const iR = i.slice(32); return new HDKey({ algorithm, privateKey: iL, chainCode: iR, version }); } public static parseExtendedKey( key: string, version: VersionBytes = versions.bitcoinMain ): HDKey { // version_bytes[4] || depth[1] || parent_fingerprint[4] || index[4] || // chain_code[32] || key_data[33] || checksum[4] const decoded = Buffer.from(bs58.decode(key)); if (decoded.length > 112) { throw new Error("invalid extended key"); } const checksum = decoded.slice(-4); const buf = decoded.slice(0, -4); if (!sha256(sha256(buf)).slice(0, 4).equals(checksum)) { throw new Error("invalid checksum"); } let o: number = 0; const versionRead = buf.readUInt32BE(o); o += 4; const depth = buf.readUInt8(o); o += 1; let parentFingerprint: Buffer | undefined = buf.slice(o, (o += 4)); if (parentFingerprint.readUInt32BE(0) === 0) { parentFingerprint = undefined; } const index = buf.readUInt32BE(o); o += 4; const chainCode = buf.slice(o, (o += 32)); const keyData = buf.slice(o); const privateKey = keyData[0] === 0 ? keyData.slice(1) : undefined; const publicKey = keyData[0] !== 0 ? keyData : undefined; if ( (privateKey && versionRead !== version.bip32.private) || (publicKey && versionRead !== version.bip32.public) ) { throw new Error("invalid version bytes"); } return new HDKey({ privateKey, publicKey, chainCode, index, depth, parentFingerprint, version, }); } public get algorithm(): Algorithm { return this._algorithm; } public get privateKey(): Buffer | null { return this._privateKey || null; } public get publicKey(): Buffer { return this._publicKey; } public get chainCode(): Buffer { return this._chainCode; } public get depth(): number { return this._depth; } public get parentFingerprint(): Buffer { return this._parentFingerprint; } public get index(): number { return this._index; } public get keyIdentifier(): Buffer { return this._keyIdentifier; } public get fingerprint(): Buffer { return this._keyIdentifier.slice(0, 4); } public get version(): VersionBytes { return this._version; } public get extendedPrivateKey(): string | null { if (this.algorithm === Algorithm.ed25519) { throw new Error( "extended private key generation is not supported for ed25519" ); } return this._privateKey ? this.serialize(this._version.bip32.private, this._privateKey) : null; } public get extendedPublicKey(): string { if (this.algorithm === Algorithm.ed25519) { throw new Error( "extended public key generation is not supported for ed25519" ); } return this.serialize(this._version.bip32.public, this._publicKey); } public derive(chain: string): HDKey { const c = chain.toLowerCase(); let childKey: HDKey = this; c.split("/").forEach((path) => { const p = path.trim(); if (p === "m" || p === "m'" || p === "") { return; } const index = Number.parseInt(p, 10); if (Number.isNaN(index)) { throw new Error("invalid child key derivation chain"); } const hardened = p.slice(-1) === "'"; childKey = childKey.deriveChildKey(index, hardened); }); return childKey; } private deriveChildKey(childIndex: number, hardened: boolean): HDKey { if (childIndex >= HARDENED_KEY_OFFSET) { throw new Error("invalid index"); } if (!this.privateKey && !this.publicKey) { throw new Error("either private key or public key must be provided"); } let index = childIndex; const data = Buffer.alloc(37); let offset = 0; // offset if (hardened) { if (!this.privateKey) { throw new Error("cannot derive a hardened child key from a public key"); } // 0x00 || ser256(kpar) || ser32(i) // 0x00[1] || parent_private_key[32] || child_index[4] index += HARDENED_KEY_OFFSET; offset += 1; offset += this.privateKey.copy(data, offset); } else { if (this.algorithm === Algorithm.ed25519) { throw new Error( "non-hardened key generation is not supported for ed25519" ); } // serP(point(kpar)) || ser32(i) // compressed_parent_public_key[33] || child_index[4] offset += this.publicKey.copy(data, offset); } offset += data.writeUInt32BE(index, offset); const i = hmacSha512(this.chainCode, data); const iL = new BN(i.slice(0, 32)); const iR = i.slice(32); // the returned chain code ci is IR // ed25519 if (this.algorithm === Algorithm.ed25519) { if (!this.privateKey) { throw new Error( "derivation from public parent key is not supported for ed25519" ); } // if curve is ed25519: The returned child key ki is parse256(IL) const childKey = iL; return new HDKey({ algorithm: this.algorithm, privateKey: childKey.toArrayLike(Buffer, "be", 32), chainCode: iR, index, depth: this.depth + 1, parentFingerprint: this.fingerprint, version: this.version, }); } // secp256k1 // if parse256(IL) >= n, the resulting key is invalid; proceed with the next // value for i if (iL.cmp(secp256k1.n as BN) >= 0) { return this.deriveChildKey(childIndex + 1, hardened); } if (this.privateKey) { // child key ki is parse256(IL) + kpar (mod n) const childKey = iL.add(new BN(this.privateKey)).mod(secp256k1.n as BN); // if ki = 0, the resulting key is invalid; proceed with the next value // for i if (childKey.cmp(new BN(0)) === 0) { return this.deriveChildKey(childIndex + 1, hardened); } return new HDKey({ algorithm: this.algorithm, privateKey: childKey.toArrayLike(Buffer, "be", 32), chainCode: iR, index, parentFingerprint: this.fingerprint, depth: this.depth + 1, version: this.version, }); } else { // Ki is point(parse256(IL)) + Kpar = G * IL + Kpar const parentKey = secp256k1.keyFromPublic(this.publicKey).pub; const childKey = secp256k1.g.mul(iL).add(parentKey); // if Ki is the point at infinity, the resulting key is invalid; proceed // with the next value for i if (childKey.isInfinity()) { return this.deriveChildKey(childIndex + 1, false); } const compressedChildKey = Buffer.from(childKey.encode(null, true)); return new HDKey({ depth: this.depth + 1, publicKey: compressedChildKey, chainCode: iR, parentFingerprint: this.fingerprint, index, version: this.version, }); } } private serialize(version: number, key: Buffer): string { // version_bytes[4] || depth[1] || parent_fingerprint[4] || index[4] || // chain_code[32] || key_data[33] || checksum[4] const buf = Buffer.alloc(78); let o: number = buf.writeUInt32BE(version, 0); o = buf.writeUInt8(this.depth, o); o += this.parentFingerprint.copy(buf, o); o = buf.writeUInt32BE(this.index, o); o += this.chainCode.copy(buf, o); o += 33 - key.length; key.copy(buf, o); const checksum = sha256(sha256(buf)).slice(0, 4); return bs58.encode(Buffer.concat([buf, checksum])); } } function hmacSha512(key: Buffer | string, data: Buffer): Buffer { return crypto.createHmac("sha512", key).update(data).digest(); } function sha256(data: Buffer): Buffer { return crypto.createHash("sha256").update(data).digest(); } function hash160(data: Buffer): Buffer { const d = crypto.createHash("sha256").update(data).digest(); return crypto.createHash("rmd160").update(d).digest(); } function publicFromPrivateKey( privateKey: Buffer, algorithm: Algorithm ): Buffer { let publicKey: string; switch (algorithm) { case Algorithm.secp256k1: { publicKey = secp256k1.keyFromPrivate(privateKey).getPublic(true, "hex"); break; } case Algorithm.ed25519: { publicKey = "00" + ed25519.keyFromSecret(privateKey).getPublic("hex"); break; } default: throw new Error("unsupported algorithm"); } return Buffer.from(publicKey, "hex"); }
the_stack
declare namespace ಠ_ಠ.clutz { interface Transferable { } } // Generated from externs.zip//fido.js declare namespace ಠ_ಠ.clutz.u2f { /** * An error object for responses */ type Error = { errorCode : number , errorMessage : string | null } ; } // Generated from externs.zip//fido.js declare namespace ಠ_ಠ.clutz.u2f { type RegisterRequest = { challenge : string , version : string } ; } // Generated from externs.zip//fido.js declare namespace ಠ_ಠ.clutz.u2f { /** * Data object for a registered key. */ type RegisteredKey = { appId : string | null , keyHandle : string , transports ? : string [] , version : string } ; } // Generated from externs.zip//fido.js declare namespace ಠ_ಠ.clutz.u2f { /** * Data object for a sign response. */ type SignResponse = { clientData : string , keyHandle : string , signatureData : string } ; } // Generated from externs.zip//fido.js declare namespace ಠ_ಠ.clutz.u2f { /** * Data object for a single sign request. */ type Transport = string ; } // Generated from externs.zip//fido.js declare namespace ಠ_ಠ.clutz.u2f { function register (appId : string , registerRequests : ಠ_ಠ.clutz.u2f.RegisterRequest [] , registeredKeys : ಠ_ಠ.clutz.u2f.RegisteredKey [] , callback : (a : ಠ_ಠ.clutz.u2f.Error | ಠ_ಠ.clutz.u2f.SignResponse ) => any , opt_timeoutSeconds ? : number ) : any ; } // Generated from externs.zip//fido.js declare namespace ಠ_ಠ.clutz.u2f { function sign (appId : string , challenge : string , registeredKeys : ಠ_ಠ.clutz.u2f.RegisteredKey [] , callback : (a : ಠ_ಠ.clutz.u2f.Error | ಠ_ಠ.clutz.u2f.SignResponse ) => any , opt_timeoutSeconds ? : number ) : any ; } // Generated from externs.zip//html5.js declare namespace ಠ_ಠ.clutz { abstract class BaseRenderingContext2D implements CanvasDrawingStyles , CanvasPathMethods { private noStructuralTyping_BaseRenderingContext2D : any; arc (x : number , y : number , radius : number , startAngle : number , endAngle : number , opt_anticlockwise ? : boolean ) : void ; arcTo (x1 : number , y1 : number , x2 : number , y2 : number , radius : number ) : void ; beginPath ( ) : void ; bezierCurveTo (cp1x : number , cp1y : number , cp2x : number , cp2y : number , x : number , y : number ) : void ; canvas : HTMLCanvasElement | OffscreenCanvas ; clearRect (x : number , y : number , w : number , h : number ) : void ; clip (optFillRuleOrPath ? : Path2D | null | string , optFillRule ? : string ) : void ; closePath ( ) : void ; createImageData (sw : number , sh : number ) : ImageData ; createLinearGradient (x0 : number , y0 : number , x1 : number , y1 : number ) : CanvasGradient ; createPattern (image : HTMLImageElement | null | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas , repetition : string ) : CanvasPattern | null ; createRadialGradient (x0 : number , y0 : number , r0 : number , x1 : number , y1 : number , r1 : number ) : CanvasGradient ; drawFocusIfNeeded (element : GlobalElement | null ) : void ; drawImage (image : HTMLImageElement | null | HTMLVideoElement | HTMLCanvasElement | ImageBitmap | OffscreenCanvas , dx : number , dy : number , opt_dw ? : number , opt_dh ? : number , opt_sx ? : number , opt_sy ? : number , opt_sw ? : number , opt_sh ? : number ) : void ; ellipse (x : number , y : number , radiusX : number , radiusY : number , rotation : number , startAngle : number , endAngle : number , opt_anticlockwise ? : boolean ) : void ; fill (optFillRuleOrPath ? : Path2D | null | string , optFillRule ? : string ) : void ; fillColor : string ; fillRect (x : number , y : number , w : number , h : number ) : void ; fillStyle : string | CanvasGradient | CanvasPattern ; fillText (text : string , x : number , y : number , opt_maxWidth ? : number ) : void ; font : string ; getImageData (sx : number , sy : number , sw : number , sh : number ) : ImageData ; getLineDash ( ) : number [] ; globalAlpha : number ; globalCompositeOperation : string ; imageSmoothingEnabled : boolean ; isPointInPath (x : number , y : number , opt_fillRule ? : string ) : boolean ; isPointInStroke (x : number , y : number ) : boolean ; lineCap : string ; lineDashOffset : number ; lineJoin : string ; lineTo (x : number , y : number ) : void ; lineWidth : number ; measureText (text : string ) : TextMetrics ; miterLimit : number ; moveTo (x : number , y : number ) : void ; putImageData (imagedata : ImageData | null , dx : number , dy : number , opt_dirtyX ? : number , opt_dirtyY ? : number , opt_dirtyWidth ? : number , opt_dirtyHeight ? : number ) : void ; quadraticCurveTo (cpx : number , cpy : number , x : number , y : number ) : void ; rect (x : number , y : number , w : number , h : number ) : void ; restore ( ) : void ; rotate (angle : number ) : void ; save ( ) : void ; scale (x : number , y : number ) : void ; /** * Note: WebKit only */ setFillColor (opt_a ? : number | string , opt_b ? : number , opt_c ? : number , opt_d ? : number , opt_e ? : number ) : void ; setLineDash (segments : number [] | null ) : void ; /** * Note: WebKit only */ setStrokeColor (opt_a ? : number | string , opt_b ? : number , opt_c ? : number , opt_d ? : number , opt_e ? : number ) : void ; setTransform (m11 : number , m12 : number , m21 : number , m22 : number , dx : number , dy : number ) : void ; shadowBlur : number ; shadowColor : string ; shadowOffsetX : number ; shadowOffsetY : number ; stroke (optStroke ? : Path2D | null ) : void ; strokeColor : string ; strokeRect (x : number , y : number , w : number , h : number ) : void ; strokeStyle : string | CanvasGradient | CanvasPattern ; strokeText (text : string , x : number , y : number , opt_maxWidth ? : number ) : void ; textAlign : string ; textBaseline : string ; transform (m11 : number , m12 : number , m21 : number , m22 : number , dx : number , dy : number ) : void ; translate (x : number , y : number ) : void ; } } // Generated from externs.zip//html5.js declare namespace ಠ_ಠ.clutz { interface CanvasDrawingStyles { font : string ; getLineDash ( ) : number [] ; lineCap : string ; lineJoin : string ; lineWidth : number ; miterLimit : number ; setLineDash (segments : number [] | null ) : void ; textAlign : string ; textBaseline : string ; } } // Generated from externs.zip//html5.js declare namespace ಠ_ಠ.clutz { interface CanvasPathMethods { arc (x : number , y : number , radius : number , startAngle : number , endAngle : number , opt_anticlockwise ? : boolean ) : void ; arcTo (x1 : number , y1 : number , x2 : number , y2 : number , radius : number ) : void ; bezierCurveTo (cp1x : number , cp1y : number , cp2x : number , cp2y : number , x : number , y : number ) : void ; closePath ( ) : void ; lineTo (x : number , y : number ) : void ; moveTo (x : number , y : number ) : void ; quadraticCurveTo (cpx : number , cpy : number , x : number , y : number ) : void ; rect (x : number , y : number , w : number , h : number ) : void ; } } // Generated from externs.zip//html5.js declare namespace ಠ_ಠ.clutz { interface NavigatorStorage { storage : StorageManager ; } } // Generated from externs.zip//html5.js declare namespace ಠ_ಠ.clutz { class OffscreenCanvas implements GlobalEventTarget , Transferable { private noStructuralTyping_OffscreenCanvas : any; constructor (width : number , height : number ) ; addEventListener (type : string , listener : EventListener | null | ( (a : GlobalEvent ) => any ) , opt_options ? : boolean | AddEventListenerOptions ) : void ; convertToBlob (opt_options ? : { quality ? : number , type ? : string } ) : Promise < Blob > ; dispatchEvent (evt : GlobalEvent ) : boolean ; getContext (contextId : string , opt_options ? : GlobalObject ) : GlobalObject ; height : number ; removeEventListener (type : string , listener : EventListener | null | ( (a : GlobalEvent ) => any ) , opt_options ? : boolean | EventListenerOptions ) : void ; transferToImageBitmap ( ) : ImageBitmap ; width : number ; } } // Generated from externs.zip//html5.js declare namespace ಠ_ಠ.clutz { class OffscreenCanvasRenderingContext2D extends BaseRenderingContext2D { private noStructuralTyping_OffscreenCanvasRenderingContext2D : any; canvas : OffscreenCanvas ; } } // Generated from externs.zip//html5.js declare namespace ಠ_ಠ.clutz { interface ShareData { text ? : string ; title ? : string ; url ? : string ; } } // Generated from externs.zip//html5.js declare namespace ಠ_ಠ.clutz { type StorageEstimate = { quota : number , usage : number } ; } // Generated from externs.zip//html5.js declare namespace ಠ_ಠ.clutz { class StorageManager { private noStructuralTyping_StorageManager : any; estimate ( ) : Promise < ಠ_ಠ.clutz.StorageEstimate > ; persist ( ) : Promise < boolean > ; persisted ( ) : Promise < boolean > ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class DirectoryEntry extends Entry { private noStructuralTyping_DirectoryEntry : any; createReader ( ) : DirectoryReader ; getDirectory (path : string , options ? : FileSystemFlags , successCallback ? : (a : DirectoryEntry ) => any , errorCallback ? : (a : FileError ) => any ) : void ; getFile (path : string , options ? : FileSystemFlags , successCallback ? : (a : FileEntry ) => any , errorCallback ? : (a : FileError ) => any ) : void ; removeRecursively (successCallback : ( ) => any , errorCallback ? : (a : FileError ) => any ) : void ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class DirectoryEntrySync extends EntrySync { private noStructuralTyping_DirectoryEntrySync : any; createReader ( ) : DirectoryReaderSync ; getDirectory (path : string , options ? : GlobalObject | null ) : DirectoryEntrySync ; getFile (path : string , options ? : GlobalObject | null ) : FileEntrySync ; removeRecursively ( ) : void ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class DirectoryReader { private noStructuralTyping_DirectoryReader : any; readEntries (successCallback : (a : Entry [] ) => any , errorCallback ? : (a : FileError ) => any ) : void ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class DirectoryReaderSync { private noStructuralTyping_DirectoryReaderSync : any; readEntries ( ) : EntrySync [] ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class Entry { private noStructuralTyping_Entry : any; copyTo (parent : DirectoryEntry , newName ? : string , successCallback ? : (a : Entry ) => any , errorCallback ? : (a : FileError ) => any ) : void ; filesystem : FileSystem ; fullPath : string ; getMetadata (successCallback : (a : Metadata ) => any , errorCallback ? : (a : FileError ) => any ) : void ; getParent (successCallback : (a : Entry ) => any , errorCallback ? : (a : FileError ) => any ) : void ; isDirectory : boolean ; isFile : boolean ; moveTo (parent : DirectoryEntry , newName ? : string , successCallback ? : (a : Entry ) => any , errorCallback ? : (a : FileError ) => any ) : void ; name : string ; remove (successCallback : ( ) => any , errorCallback ? : (a : FileError ) => any ) : void ; toURL (mimeType ? : string ) : string ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class EntrySync { private noStructuralTyping_EntrySync : any; copyTo (parent : DirectoryEntrySync , newName ? : string ) : EntrySync ; filesystem : FileSystemSync ; fullPath : string ; getMetadata ( ) : Metadata ; getParent ( ) : DirectoryEntrySync ; isDirectory : boolean ; isFile : boolean ; moveTo (parent : DirectoryEntrySync , newName ? : string ) : EntrySync ; name : string ; remove ( ) : void ; toURL (mimeType ? : string ) : string ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class FileEntry extends Entry { private noStructuralTyping_FileEntry : any; createWriter (successCallback : (a : FileWriter ) => any , errorCallback ? : (a : FileError ) => any ) : void ; file (successCallback : (a : File ) => any , errorCallback ? : (a : FileError ) => any ) : void ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class FileEntrySync extends EntrySync { private noStructuralTyping_FileEntrySync : any; createWriter ( ) : FileWriterSync ; file ( ) : File ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class FileError extends DOMError { private noStructuralTyping_FileError : any; ABORT_ERR : number ; ENCODING_ERR : number ; INVALID_MODIFICATION_ERR : number ; INVALID_STATE_ERR : number ; NOT_FOUND_ERR : number ; NOT_READABLE_ERR : number ; NO_MODIFICATION_ALLOWED_ERR : number ; PATH_EXISTS_ERR : number ; QUOTA_EXCEEDED_ERR : number ; SECURITY_ERR : number ; SYNTAX_ERR : number ; TYPE_MISMATCH_ERR : number ; code : number ; static ABORT_ERR : number ; static ENCODING_ERR : number ; static INVALID_MODIFICATION_ERR : number ; static INVALID_STATE_ERR : number ; static NOT_FOUND_ERR : number ; static NOT_READABLE_ERR : number ; static NO_MODIFICATION_ALLOWED_ERR : number ; static PATH_EXISTS_ERR : number ; static QUOTA_EXCEEDED_ERR : number ; static SECURITY_ERR : number ; static SYNTAX_ERR : number ; static TYPE_MISMATCH_ERR : number ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class FileException { private noStructuralTyping_FileException : any; ABORT_ERR : number ; ENCODING_ERR : number ; INVALID_MODIFICATION_ERR : number ; INVALID_STATE_ERR : number ; NOT_FOUND_ERR : number ; NOT_READABLE_ERR : number ; NO_MODIFICATION_ALLOWED_ERR : number ; PATH_EXISTS_ERR : number ; QUOTA_EXCEEDED_ERR : number ; SECURITY_ERR : number ; SYNTAX_ERR : number ; TYPE_MISMATCH_ERR : number ; code : number ; static ABORT_ERR : number ; static ENCODING_ERR : number ; static INVALID_MODIFICATION_ERR : number ; static INVALID_STATE_ERR : number ; static NOT_FOUND_ERR : number ; static NOT_READABLE_ERR : number ; static NO_MODIFICATION_ALLOWED_ERR : number ; static PATH_EXISTS_ERR : number ; static QUOTA_EXCEEDED_ERR : number ; static SECURITY_ERR : number ; static SYNTAX_ERR : number ; static TYPE_MISMATCH_ERR : number ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class FileSaver { private noStructuralTyping_FileSaver : any; DONE : number ; INIT : number ; WRITING : number ; abort ( ) : void ; error : FileError | null ; onabort : ( (a : ProgressEvent ) => any ) | null ; onerror : ( (a : ProgressEvent ) => any ) | null ; onprogress : ( (a : ProgressEvent ) => any ) | null ; onwrite : ( (a : ProgressEvent ) => any ) | null ; onwriteend : ( (a : ProgressEvent ) => any ) | null ; onwritestart : ( (a : ProgressEvent ) => any ) | null ; readyState : number ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class FileSystem { private noStructuralTyping_FileSystem : any; name : string ; root : DirectoryEntry ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { interface FileSystemFlags { create ? : boolean ; exclusive ? : boolean ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class FileSystemSync { private noStructuralTyping_FileSystemSync : any; name : string ; root : DirectoryEntrySync ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class FileWriter extends FileSaver { private noStructuralTyping_FileWriter : any; length : number ; position : number ; seek (offset : number ) : void ; truncate (size : number ) : void ; write (blob : Blob ) : void ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { class FileWriterSync { private noStructuralTyping_FileWriterSync : any; length : number ; position : number ; seek (offset : number ) : void ; truncate (size : number ) : void ; write (blob : Blob ) : void ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { /** * LocalFileSystemSync interface, implemented by WorkerGlobalScope. */ class LocalFileSystemSync { private noStructuralTyping_LocalFileSystemSync : any; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { /** * Metadata interface. */ class Metadata { private noStructuralTyping_Metadata : any; modificationTime : GlobalDate ; size : number ; } } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { function requestFileSystemSync (type : number , size : number ) : FileSystemSync ; } // Generated from externs.zip//nonstandard_fileapi.js declare namespace ಠ_ಠ.clutz { function webkitRequestFileSystemSync (type : number , size : number ) : FileSystemSync ; } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { class ByteLengthQueuingStrategy { private noStructuralTyping_ByteLengthQueuingStrategy : any; constructor (config : { highWaterMark : number } ) ; /** * If we don't want to be strict we can define chunk as {*} * and return as {number|undefined} */ size (chunk : { byteLength : number } ) : number ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { class CountQueuingStrategy { private noStructuralTyping_CountQueuingStrategy : any; constructor (config : { highWaterMark : number } ) ; size (chunk : any ) : number ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { /** * A transform stream (https://streams.spec.whatwg.org/#transform-stream). */ interface ITransformStream { readable : ReadableStream ; writable : WritableStream ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { /** * The ReadableByteStreamController constructor cannot be used directly; * it only works on a ReadableStream that is in the middle of being constructed. */ interface ReadableByteStreamController { byobRequest : ReadableStreamBYOBRequest ; close ( ) : void ; desiredSize : number ; enqueue (chunk : ArrayBufferView ) : void ; error (err : any ) : void ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { /** * The ReadableStreamBYOBReader constructor is generally not meant to be used * directly; instead, a stream’s getReader() method should be used. */ interface ReadableStreamBYOBReader { cancel (reason : any ) : Promise < any > ; closed : Promise < undefined > ; read (view : ArrayBufferView ) : Promise < { done : boolean , value : any } > ; releaseLock ( ) : void ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { interface ReadableStreamBYOBRequest { respond (bytesWritten : number ) : void ; respondWithNewView (view : ArrayBufferView ) : void ; view : ArrayBufferView ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { /** * The ReadableStreamDefaultController constructor cannot be used directly; * it only works on a ReadableStream that is in the middle of being constructed. */ interface ReadableStreamDefaultController { close ( ) : void ; desiredSize : number ; enqueue (chunk : any ) : void ; error (err : any ) : void ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { /** * The ReadableStreamDefaultReader constructor is generally not meant to be used directly; * instead, a stream’s getReader() method should be used. */ interface ReadableStreamDefaultReader { cancel (reason : any ) : Promise < any > ; closed : Promise < undefined > ; read ( ) : Promise < { done : boolean , value : any } > ; releaseLock ( ) : void ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { interface ReadableStreamIteratorOptions { preventCancel ? : boolean ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { interface ReadableStreamSource { autoAllocateChunkSize ? : number ; cancel ? : (a : any ) => Promise < any > | undefined ; pull ? : (a : ReadableByteStreamController | ReadableStreamDefaultController ) => PromiseLike < any > | undefined ; start ? : (a : ReadableByteStreamController | ReadableStreamDefaultController ) => PromiseLike < any > | undefined ; type ? : string ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { /** * The TransformStreamDefaultController class has methods that allow * manipulation of the associated ReadableStream and WritableStream. * * This class cannot be directly constructed and is instead passed by the * TransformStream to the methods of its transformer. */ interface TransformStreamDefaultController { desiredSize : number ; enqueue (chunk : any ) : void ; error (reason : any ) : void ; terminate ( ) : void ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { interface TransformStreamTransformer { flush ? : (a : TransformStreamDefaultController ) => PromiseLike < any > | undefined ; start ? : (a : TransformStreamDefaultController ) => PromiseLike < any > | undefined ; transform ? : (a : any , b : TransformStreamDefaultController ) => PromiseLike < any > | undefined ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { class WritableStream { private noStructuralTyping_WritableStream : any; constructor (opt_underlyingSink ? : WritableStreamSink , opt_queuingStrategy ? : CountQueuingStrategy | ByteLengthQueuingStrategy | { highWaterMark ? : number , size ? : (a : any ) => number } ) ; abort (reason : any ) : Promise < undefined > ; getWriter ( ) : WritableStreamDefaultWriter ; locked : boolean ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { /** * The WritableStreamDefaultController constructor cannot be used directly; * it only works on a WritableStream that is in the middle of being constructed. */ interface WritableStreamDefaultController { error (err : any ) : Promise < undefined > ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { interface WritableStreamDefaultWriter { abort (reason : any ) : Promise < undefined > ; close ( ) : Promise < undefined > ; closed : Promise < undefined > ; desiredSize : number ; ready : Promise < number > ; releaseLock ( ) : void ; write (chunk : any ) : Promise < undefined > ; } } // Generated from externs.zip//streamsapi.js declare namespace ಠ_ಠ.clutz { interface WritableStreamSink { abort ? : (a : any ) => PromiseLike < any > | undefined ; close ? : ( ) => PromiseLike < any > | undefined ; start ? : (a : WritableStreamDefaultController ) => PromiseLike < any > | undefined ; write ? : (a : any , b : WritableStreamDefaultController ) => PromiseLike < any > | undefined ; } } // Generated from externs.zip//url.js declare namespace ಠ_ಠ.clutz { type URLSearchParamsTupleType = string [] | null ; } // Generated from externs.zip//w3c_abort.js declare namespace ಠ_ಠ.clutz { class AbortController { private noStructuralTyping_AbortController : any; abort ( ) : void ; signal : AbortSignal ; } } // Generated from externs.zip//w3c_abort.js declare namespace ಠ_ಠ.clutz { interface AbortSignal extends GlobalEventTarget { aborted : boolean ; onabort : ( (a : GlobalEvent ) => any ) | null ; } } // Generated from externs.zip//w3c_clipboard.js declare namespace ಠ_ಠ.clutz { interface Clipboard { readText ( ) : Promise < string > ; writeText (text : string ) : Promise < undefined > ; } } // Generated from externs.zip//w3c_navigation_timing.js declare namespace ಠ_ಠ.clutz { /** * https://wicg.github.io/largest-contentful-paint/#largestcontentfulpaint */ class LargestContentfulPaint extends PerformanceEntry { private noStructuralTyping_LargestContentfulPaint : any; element : GlobalElement | null ; id : string ; loadTime : number ; renderTime : number ; size : number ; url : string ; } } // Generated from externs.zip//w3c_navigation_timing.js declare namespace ಠ_ಠ.clutz { /** * https://wicg.github.io/layout-instability/#sec-layout-shift */ class LayoutShift extends PerformanceEntry { private noStructuralTyping_LayoutShift : any; hadRecentInput : boolean ; lastInputTime : number ; value : number ; } } // Generated from externs.zip//w3c_navigation_timing.js declare namespace ಠ_ಠ.clutz { /** * https://wicg.github.io/event-timing/#sec-performance-event-timing */ class PerformanceEventTiming extends PerformanceEntry { private noStructuralTyping_PerformanceEventTiming : any; cancelable : boolean ; processingEnd : number ; processingStart : number ; } } // Generated from externs.zip//w3c_navigation_timing.js declare namespace ಠ_ಠ.clutz { /** * https://w3c.github.io/paint-timing/#sec-PerformancePaintTiming */ class PerformancePaintTiming extends PerformanceEntry { private noStructuralTyping_PerformancePaintTiming : any; } } // Generated from externs.zip//w3c_rtc.js declare namespace ಠ_ಠ.clutz { class BlobEvent extends GlobalEvent { private noStructuralTyping_BlobEvent : any; constructor (type : string , eventInitDict : { data : Blob , timecode ? : number } ) ; data : Blob ; timecode : number ; } } // Generated from externs.zip//w3c_rtc.js declare namespace ಠ_ಠ.clutz { interface RTCRtpSendParameters { /** * Possible string values are "maintain-framerate", "maintain-resolution", and * "balanced". */ degradationPreference ? : string ; encodings : RTCRtpEncodingParameters [] ; transactionId ? : string ; } } // Generated from externs.zip//w3c_rtc.js declare namespace ಠ_ಠ.clutz { /** * Possible values are "sendrecv", "sendonly", "recvonly", and "inactive". */ type RTCRtpTransceiverDirection = string ; } // Generated from externs.zip//w3c_rtc.js declare namespace ಠ_ಠ.clutz { interface RTCRtpTransceiverInit { /** * The direction of the `RTCRtpTransceiver`. Defaults to "sendrecv". */ direction ? : string | null ; sendEncodings ? : RTCRtpEncodingParameters [] | null ; /** * The streams to add to the tranceiver's sender. */ streams ? : MediaStream [] | null ; } } // Generated from externs.zip//w3c_trusted_types.js declare namespace ಠ_ಠ.clutz { let TrustedTypePolicyOptions : PrivateType; } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { class Animation implements GlobalEventTarget { private noStructuralTyping_Animation : any; constructor (effect ? : AnimationEffectReadOnly | null , timeline ? : AnimationTimeline | null ) ; addEventListener (type : string , listener : EventListener | null | ( (a : GlobalEvent ) => any ) , options ? : boolean | AddEventListenerOptions ) : void ; cancel ( ) : void ; currentTime : number ; dispatchEvent (evt : GlobalEvent ) : boolean ; effect : AnimationEffectReadOnly | null ; finish ( ) : void ; finished : Promise < undefined > ; id : string ; oncancel : ( (a : GlobalEvent ) => any ) | null ; onfinish : ( (a : GlobalEvent ) => any ) | null ; pause ( ) : void ; play ( ) : void ; playState : string ; playbackRate : number ; ready : Promise < undefined > ; removeEventListener (type : string , listener : EventListener | null | ( (a : GlobalEvent ) => any ) , options ? : boolean | EventListenerOptions ) : void ; reverse ( ) : void ; startTime : number ; timeline : AnimationTimeline ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { interface AnimationEffectReadOnly { getComputedTiming ( ) : ComputedTimingProperties ; timing : AnimationEffectTiming ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { interface AnimationEffectTiming extends AnimationEffectTimingReadOnly { } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { interface AnimationEffectTimingProperties { delay ? : number ; direction ? : string ; duration ? : number | string ; easing ? : string ; endDelay ? : number ; fill ? : string ; iterationStart ? : number ; iterations ? : number ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { interface AnimationEffectTimingReadOnly { delay : number ; direction : string ; duration : number | string ; easing : string ; endDelay : number ; fill : string ; iterationStart : number ; iterations : number ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { interface AnimationTimeline { currentTime : number | null ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { interface ComputedTimingProperties extends AnimationEffectTimingProperties { activeDuration : number ; currentIteration : number | null ; endTime : number ; localTime : number | null ; progress : number | null ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { class DocumentTimeline implements AnimationTimeline { private noStructuralTyping_DocumentTimeline : any; currentTime : number | null ; getAnimations ( ) : Animation [] ; play (effect : AnimationEffectReadOnly ) : Animation ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { class GroupEffect implements AnimationEffectReadOnly { private noStructuralTyping_GroupEffect : any; constructor (children : AnimationEffectReadOnly [] , timing ? : AnimationEffectTimingProperties | null ) ; children : AnimationEffectReadOnly [] ; getComputedTiming ( ) : ComputedTimingProperties ; timing : AnimationEffectTiming ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { interface KeyframeAnimationOptions extends KeyframeEffectOptions { id ? : string ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { class KeyframeEffect extends KeyframeEffectReadOnly { private noStructuralTyping_KeyframeEffect : any; constructor (target : GlobalElement | null , frames : { [ key: string ]: any } [] | { [ key: string ]: any [] } , options ? : number | AnimationEffectTimingProperties | null ) ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { interface KeyframeEffectOptions extends AnimationEffectTimingProperties { /** * Possible values: 'replace', 'add', 'accumulate' */ composite ? : string ; /** * Possible values: 'replace', 'accumulate' */ iterationComposite ? : string ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { class KeyframeEffectReadOnly implements AnimationEffectReadOnly { private noStructuralTyping_KeyframeEffectReadOnly : any; constructor (target : GlobalElement | null , frames : { [ key: string ]: any } [] | { [ key: string ]: any [] } , options ? : number | AnimationEffectTimingProperties | null ) ; getComputedTiming ( ) : ComputedTimingProperties ; onsample ? : ( (a : number , b : KeyframeEffect , c : Animation ) => any ) | null ; target : GlobalElement | null ; timing : AnimationEffectTiming ; } } // Generated from externs.zip//web_animations.js declare namespace ಠ_ಠ.clutz { class SequenceEffect implements AnimationEffectReadOnly { private noStructuralTyping_SequenceEffect : any; constructor (children : AnimationEffectReadOnly [] , timing ? : AnimationEffectTimingProperties | null ) ; children : AnimationEffectReadOnly [] ; getComputedTiming ( ) : ComputedTimingProperties ; timing : AnimationEffectTiming ; } }
the_stack
import assert = require("assert"); // import { IEntityAnnotationObject } from "../../src/data/IEntityAnnotationObject"; // import { IEntityObjectByPosition } from "../../src/data/IEntityObjectByPosition"; // import { IPartOfSpeechTagObjectByPosition } from "../../src/data/IPartOfSpeechTagObjectByPosition"; import { ITextIntentSequenceLabelObjectByPosition} from "../../src/data/ITextIntentSequenceLabelObjectByPosition"; import { LuDataWithSubwordFeaturizer } from "../../src/data/LuDataWithSubwordFeaturizer"; import { NgramSubwordFeaturizer } from "../../src/model/language_understanding/featurizer/NgramSubwordFeaturizer"; import { Utility } from "../../src/utility/Utility"; import { UnitTestHelper } from "../utility/Utility.test"; /* tslint:disable */ // ---- NOTE ---- The dataset in LuContentEmail was minorly revised (LUIS application header added) from // ---- NOTE ---- Reference: https://github.com/microsoft/botframework-solutions/blob/master/skills/src/csharp/emailskill/emailskill/Deployment/Resources/LU/en/Email.lu export const LuContentEmail: string = ` > LUIS application description > !# @app.name = my luis application > !# @app.desc = description of my luis application > !# @app.versionId = 0.5 > !# @app.culture = en-us > !# @app.luis_schema_version = 3.2.0 > # Intent definitions ## AddFlag - add a flag - add a flag please - add a flag to the {OrderReference=last} email - add a flag to this email - add flag - add flag on it - add flag to it - add flag to the email {SenderName=john} just sent to me - add {Category=flag} to this email - add flag to this message - flag - flag it - flag on - flag the current email - flag the email - flag the email from {SenderName=davis} - flag this email - flag this email as {Category=important} for me - i want to add a flag - i want to add a flag on this email - make it flagged - mark as flag - mark the email {Category=flagged} - put a flag - put a flag on the new email - the email from {SenderName=thomas} should be flagged - the email to {ContactName=ruth} needs to be flagged - this email need to be flagged - this email needs to be flagged - this email should be flagged - turn flag on ## AddMore - add a {Attachment=file} to the email - add a {Attachment=picture} - add a subject - add another line to the message - add {Message=did you enjoy the entire program} - add {Attachment=file} to email - add more - add more and change the message - add more details to it - add more {Message=don't forget to bring beer} - add more message - add more please - add more text - add more text please - add more to email - add more to email body - add more to it - add more to message - add more to {ContactName=roy} 's email - add more to text - add more to the email - add more to the {OrderReference=last} email - add more to the message - add {Attachment=photo} - add some more - add something - add to body of email - add, by the way, what's the plan of next step - add: {Message=call me tonight after work} - append an {Attachment=attachment} to this email - attach {Attachment=file} - can i add more to the email - can i add more to the message - edit email so i can type an additional message - i am not done yet. i need to add some more details - i forgot to add an important part to that email to {ContactName=james} . please set it up to edit - i need to add additional lines - i need to add further contents - i need to add more message - i need to add more text - i need to add more to the email - i need to add more to the email message i am sending to {ContactName=vincent} - i need to add something else to my email to {ContactName=cheryl} - i need to add something else to that email to {ContactName=donna} before it is sent - i want to add more the email - i wish to add more to the message - i would like to add more to the email - i would like to add more to the email message - i would like to open a new line - i'd like to add a bit more to the email. - i'd like to add a bit more to the message - i'd like to add more to the email - insert more lines for me please - insert more text in my email - is it ok if i add more to the email? - it isn't complete, need more contents - more text - need to add information to the {OrderReference=previous} email - ok, i need to add a few things to that - please add {Message=it was terrible} - please add more - please add, {Message=please let me know what i can bring. i'd be happy to make a side dish or dessert} - put some additional lines to this message - wait, i need to write more - write more ## CancelMessages - abort deletion - can you cancel it - cancel email - cancel email to {ContactName=natalie} - cancel message - cancel my email to {ContactName=jane} - cancel searching the messages - cancel the email - cancel the email sent to {ContactName=alex} - cancel the email to my {RelationshipName=sister} - cancel the mail - cancel the message - cancel this email - cancel this message - cancel this sending process - don ' t read - don ' t read it - don 't send the email - don't email - don't email to her - don't read the email - don't read the message - don't send - don't send it - don't send out - don't send that email - don't send this email - don't show me - exit - forget about the email - i want you to cancel the email - neither of them - never mind cancel the mail - never mind cancel the message - never mind, forget about the mail - nevermind cancel - no cancel it, i don't want to send the mail - no don't send - no don't send it - no just cancel the email - no, i don't want to send this message - no, no, cancel the reading - okay cancel sending the mail - quit the sending - stop message - stop reading - ^cancel [sending] [(my|the)] (email|mail) to {ContactName} ## CheckMessages - any {Category=new} email - any {Category=new} email available - any {Category=new} email {Time=now} - any {Category=new} message {Time=now} - check email - check email please - check my email please - check my emails - check my {Line=gmail} - check my inbox - check my mail box - check my message - check {Line=outlook} please - check up email - check up messages - could you please check my emails - could you please check my inbox - could you please check my messages - do i get new email - do i have any {Category=new} mail - do i have {Category=new} email - do i have {Category=new} email {Time=now} - do i have {Category=new} message - do i receive {Category=new} email - do i receive {Category=new} mail in {Line=outlook}? - do i receive {Category=new} message - does anyone send email to me just then - does anyone send message to me {Time=just then} - does my {Line=outlook} have {Category=new} email - i want to check my emails - i want to check my inbox - i'd like to check my inbox - is there new email - please check my emails - please check my inbox - please check my {Line=outlook} - show {OrderReference=latest} emails - show my emails - show my {Category=unread} mails - show the {Category=important} emails in my inbox - whether i get {Category=new} email - whether i get {Category=new} message - whether i have {Category=new} email - whether i have {Category=new} message - whether i receive new email - show [(my|the)] [(unread|important|{Category})] (email|mail|emails)^ ## ConfirmMessages - "okay, send it" - "sure, go ahead" - "yes, you can" - alright, just send the message - correct, please send it. - i confirm that i want to send this email - just do it - no problem, go ahead send the mail - of course, just delete the mail - ok send the mail to {ContactName=may} - ok, good to me, send it please - ok, good, just send it - okay - okay send it - okay, send it now - perfect thank you - right, send it please - yeah right, send to {ContactName=alex} - yes it's right - yes that's right - yes, send it ## Delete - can you help me delete it - clear my inbox - delete all emails from {SenderName=tom} - delete all emails received {Time=tonight} - delete the email from my {Line=hotmail} account - delete the email sent from {SenderName=mary jane} - delete the {PositionReference=first} email for me - delete the {OrderReference=last} one - delete the {OrderReference=previous} 4 emails - delete the {Category=red} ones - delete the second mail - delete the {PositionReference=second} one - delete the {Category=unread} emails - delete this email - delete this message permanently - delete what i just wrote - empty the email inbox - put it in the recycle bin - put the email in the recycle bin - put the email to trash bin - put the emails from this file folder to trash bin - remove emails that are duplicate - remove emails with {Category=red} flags - remove it from my inbox - remove the email from {SenderName=mary} - remove the emails received {Date=yesterday} - ^(delete|remove) [the] [{OrderReference}] (email|emails|mails) [from {SenderName}] ## Forward - could you forward this message to {ContactName=ronald} and {ContactName=roy} - could you please forward this email to my {RelationshipName=sister} - forward all {Attachment=files} from {SenderName=sally} to {ContactName=austin} - forward by saying {Message=if you interest} to {ContactName=rebecca} - forward email - forward email to {RelationshipName=girlfriend} - forward emails to {ContactName=gabriel} - forward message to {RelationshipName=girlfriend} - forward the email from {SenderName=john smith} to {ContactName=michelle} by saying {Message=fyi} - forward the email from {SenderName=melissa} to {ContactName=peter} - forward the email to {RelationshipName=dad} - forward the {OrderReference=last} email to {ContactName=susan} - forward this email - forward this email to {ContactName=eugene} by typing {Message=what do you think} - forward this email to {ContactName=gary brown} please - forward this email to {ContactName=joseph} - forward this email to partone dot parttwo at gmail dot com - forward this email to {ContactName=patricia} - forward to {ContactName=alan} {Time=tonight} - forward to {ContactName=brian potter} {Time=tonight} - forward to {ContactName=deborah} with a message saying that {Message=i don't want that} - forward to {ContactName=dorothy} by typing {Message=i agree with it} - forward to {RelationshipName=mom} - forward to my {RelationshipName=boss} and attach the {Attachment=schedule file} - forward to partoneparttwo@gmail.com {Date=next monday} - forward to {ContactName=thomas} please - forward to {RelationshipName=wife} by saying {Message=i love you} - please forward this email to {ContactName=albert} by typing {Message=everything goes fine} - please forward this email to partoneparttwo@163.com - please forward this email to partoneparttwo@outlook.com - please forward this message - please forward to {ContactName=benjamin} ## None - 1 - 2 - 3 - the {PositionReference=first} one - the {PositionReference=second} one - the {PositionReference=third} one ## QueryLastText - can you tell me the {OrderReference=last} email i received - come to the {OrderReference=last} - go to the {OrderReference=last} one - i want to see the {OrderReference=last} email - {OrderReference=last} email - open the {OrderReference=last} email - open the {OrderReference=lastest} email i got - please tell me who emailed me {OrderReference=last} - show me the {OrderReference=lastest} email - show me the {OrderReference=newest} email - show the {OrderReference=last} email - the {OrderReference=last} email - what did {RelationshipName=mom} just say - what {ContactName=eric watson} just said - what {SenderName=harry} {OrderReference=last} email said - what {ContactName=henry} just said - what is the {OrderReference=last} email i received {Date=today} - what is the {OrderReference=lastest} email i received from {FromRelationshipName=dad} - what was the {OrderReference=last} email - what was the {OrderReference=last} email i got from {FromRelationshipName=dad} - what was the {OrderReference=last} email i got from {SenderName=steve edwards} - who email me {Time=just now} - who emailed me - who emailed me just now - who emailed me {OrderReference=last} - who recently emailed me - who sent me the email lastly {Date=yesterday} - who sent me the mail just now - who texted me - who texted me {Time=just now} - whose email just then ? - whose email {Time=now} ? ## ReadAloud - can you read my emails - can you read my {OrderReference=last} email - could you read out the email on {EmailSubject=how to use the new tool}? - please read my {OrderReference=last} email - read aloud my {Category=new} email - read aloud the {EmailSubject=christmas party} email - read {SenderName=darren}'s mail on {EmailSubject=the movie} - read email - read email from {SenderName=dawn} - read email from {SenderName=kat} - read email from {FromRelationshipName=mum} - read email to me - read emails - read emails from {SenderName=clay} - read {PositionReference=first} email in link box - read {PositionReference=first} email in the linked inbox - read {Line=google} mail - read it - read {OrderReference=last} email received - read {OrderReference=last} incoming emails - read {OrderReference=last} mail - read {OrderReference=latest} email - read {SenderName=mary grace white} email - read me {SenderName=dylan}'s email sent on {Date=yesterday} - read me {SenderName=jessica}'s email on {EmailSubject=dress code for the party} - read me my {OrderReference=last} {Line=hotmail} email - read me my {OrderReference=latest} emails - read me the email - read me the email on {EmailSubject=apple} - read me the email on {EmailSubject=thanksgiving day} - read me the email sent on {Date=thanksgiving day} - read me the email titled {EmailSubject=happy new year} - read me the emails from {SenderName=agatha} - read me the {OrderReference=last} email {SenderName=claude} sent - read me the {OrderReference=last} emails of the {Time=five minutes} - read me the {OrderReference=newest} email - read me the {OrderReference=recent} email titled {EmailSubject=abcd} from {SenderName=jessica} - read most {OrderReference=recent} email - read my email from {SenderName=baby} - read my email from {SenderName=hubby} - read my email from {SenderName=tyler swift} - read my email messages - read my email please - read my email to me - read my emails - read my emails from {SenderName=patty} - read my inbox - read my {OrderReference=last} email - read my {OrderReference=last} email out to me - read my {OrderReference=most recent} email - read my {Category=new} email - read my {Category=new} emails - read my notification - read my {Line=outlook} email - read my {OrderReference=recent} email - read my {OrderReference=recent} email message please - read my {OrderReference=recent} email messages - read my {OrderReference=recent} email to me - read my {PositionReference=second} email - read {Category=new} email - read {Category=new} email from {SenderName=david ma} - read {Category=new} message - read out {SenderName=darren}'s mail - read out the email from {SenderName=liu} about {EmailSubject=transfer} - read out {SenderName=xu}'s email about {EmailSubject=apple's news} - read please - read {OrderReference=recent} email - read the email - read the email on {EmailSubject=auto repair} - read the {PositionReference=first} email - read the {PositionReference=first} email in {Line=hotmail} - read the {OrderReference=last} email - read the {OrderReference=last} email message - read the {OrderReference=latest} email from {FromRelationshipName=mom} - read the {OrderReference=latest} email from {SenderName=steve lip} - read the {OrderReference=latest} email i sent - read {Date=todays} mail - read {Date=today}'s mail - read {Category=unread} email - read {Category=unread} message - ^read [(me|out)] [the] (email|emails) from {SenderName} [(about|on) {EmailSubject}]^ - ^read [me] [the] (email|mail|emails) (on|about|titled) {EmailSubject} - ^read [me] [the] (email|mail|emails) (on|about|titled) {EmailSubject} [sent] from {SenderName}^ - ^read [me] the (email|mail) (titled|about|on) [the] {EmailSubject}^ ## Reply - create a response to the email by saying {Message=pls send me the picture again} - email back - email back {Message=i will call you back} - how to reply to an email - make a response with {Message=thank you very much} - reply - reply by email {Message=thank you very much best regards jun} - reply by saying {Message=i love you} - reply by saying {Message=yes} - reply by typing {Message=hello} - reply {Message=required} to an email - reply that {Message=i am busy} - reply to {ContactName=edward} - reply to email {Message=i am busy now} - reply to my {OrderReference=last} email - reply to {ContactName=susan} - reply to the email - reply to the {PositionReference=first} one - reply {Message=we'll see you later} - reply with {Message=hello} - reply {Message=yee ha} - reply {ContactName=yee} {Message=hello} - reply {Message=yes boss.} - respond {Message=i ' m sick i can ' t do it} - respond to {ContactName=lore hound} - respond to {ContactName=nathan} - respond to the email by saying {Message=i am busy today} - return {ContactName=barbara} on {Line=mobile} - return {ContactName=siberian huskies} {Line=mobile} - send email back - send the response with {Message=i've already know} - ^reply [back] with [the] (title|subject) {EmailSubject} - ^reply [back] [the] message [that] {Message}^ - ^reply [back] [with] [the] [message] [that] "{Message.Any}" ## SearchMessages - can you search my emails - detect emails from {SenderName=betty} - detect the email containing keyword {SearchTexts=beauty} - detect the email from {SenderName=lisa} - did i get any email from {SenderName=tom} - did i get emails from {SenderName=tom} - did i get the email containing keyword {SearchTexts=lunch} - email sent from {SenderName=lisa} - emails contains {SearchTexts=bank} - enumerate the emails with {SearchTexts=algroithm} - find an email about {EmailSubject=new year's planning} - find an email from abc123@outlook.com - find an email from {SenderName=angela} - find an email from {SenderName=jay} that contains {SearchTexts=halloween} - find an email on the {EmailSubject=dinner reservation} - find email titled {EmailSubject=new design} - find email with title {EmailSubject=production tools} - find emails from {FromRelationshipName=mom} - find emails that contain {SearchTexts=malta} - find emails with {SearchTexts=resume} - find mails titled {EmailSubject=recommended courses} - list the emails contain {SearchTexts=funny picture} - looking for an email with {SearchTexts=hello} - query emails with {SearchTexts=bill} - search an email with subject {EmailSubject=background screening} - search {SearchTexts=bla bla} in my emails - search email contain {SearchTexts=outlook} - search email with key words {SearchTexts=lunch} - search emails about {EmailSubject=boating} - search emails contain {SearchTexts=work items} - search emails contains {SearchTexts=coupons} - search emails from {SenderName=mike} - search {SenderName=jensen}'s emails - search keywords {SearchTexts=keywordone keywordtwo} in my emails - search {SearchTexts=keywordsone keywordstwo} from inbox - search my emails - search text with words {SearchTexts=lunch together} - search the email with keywords {SearchTexts=hello} - search the emails contains {SearchTexts=microsoft} - search the emails contains {SearchTexts=money} - show emails contain words "{SearchTexts=future plan}" - show emails with "{SearchTexts=credit card}" - show me emails from {SenderName=clara chan} - show me emails from {FromRelationshipName=girlfriend} - show me the email about {EmailSubject=spring festival} - show me the email from {SenderName=tom} and filtering with word {SearchTexts=lunch} - show me the email sent from {FromRelationshipName=mom} - tell me the email from {SenderName=lily wong} - tell me the email with subject {EmailSubject=weekly report} - ^(tell|find|show) [me] [(an|the)] email (with the title|with title|titled) {EmailSubject} - ^(tell|find|show) [me] [(an|the)] email (with the title|with title|titled) "{EmailSubject.Any}" - ^(search|find|show) [me] [(an|the)] (email|emails|mail) [(containing|filtering)] [with] [the] [(texts|text|word)] "{SearchTexts.Any}" - ^(show|search|find) [me] [(an|the)] [{Category}] email[s] (on|about|titled) {EmailSubject} [sent] [(by|from) {SenderName}]^ ## SendEmail - compose new email about {EmailSubject=spanish homework} - create new mail titled {EmailSubject=urgent meeting information} to {ContactName=jonathan} - email her the message "fine, ok" - email my {RelationshipName=brother} - email my {Attachment=presentation} - email the {Attachment=file} to {ContactName=henry mathew} - email to {ContactName=amy cooper} about {Message=haha saying hello} - email to {ContactName=cynthia} and {ContactName=mike}, {Message=that dinner {OrderReference=last} week was splendid}. - email to {ContactName=harry potter} and {ContactName=hermione granger} - email to {ContactName=lawrence} about {EmailSubject=opening issue} - email to {ContactName=mike waters} : {Message=mike, that dinner last week was splendid.} - email to partoneparttwo@gmail.com - email to {ContactName=tom white} about {Message=that flower saying beautiful} - i need to send an email about the {EmailSubject=words to a song} - make a new email about {EmailSubject=weather forecast} - mark email for {Category=follow up} and send to {ContactName=arthur} - new email about {EmailSubject=really good talk} to {ContactName=michelle} - new email about {EmailSubject=writing documents} - new email to {ContactName=kimberly} about {EmailSubject=wingman} - send a email to {ContactName=leehom wong} about the {EmailSubject=piano concert} saying {Message=it's wonderful} - send a mail to {ContactName=daniel} - send a new email about {EmailSubject=facebook} - send a new email about the {EmailSubject=hockey tournament} to {ContactName=marie jane}, {ContactName=joseph} , and {ContactName=john} - send a new email about the {EmailSubject=problem solving} to {ContactName=andrea}, {ContactName=angela}, and {ContactName=ron} - send a new email to {ContactName=larry} with a {Attachment=file} attached - send a new email to {ContactName=nicholas} and {ContactName=jesse} about {EmailSubject=coupons} - send a new email to partonepartwopartthree@yahoo.com - send a new {Category=high importance} email to {ContactName=jordan} - send a {Category=read receipt} email to {ContactName=samuel} - send {ContactName=alexander} a {Category=red bang} email - send an email - send an email about {EmailSubject=swim team practice} - send an email about {EmailSubject=test status} to {ContactName=mark} - send an email about the {EmailSubject=window that is broken} - send an email for me - send an email marked {Category=follow up} to {ContactName=jerry} - send an email marked for {Category=follow up} to {ContactName=christian} - send an email marked with a {Category=bang} to {ContactName=amy} - send an email to {ContactName=a.j.ron} marked as {Category=important} - send an email to {ContactName=christopher carpenter} about the {EmailSubject=hiking trip} - send an email to {ContactName=harold} and {ContactName=bob kappus} about {Message=team lunch saying same team lunch this tuesday} - send an email to {ContactName=harry potter} - send an email to {ContactName=jacqueline} and {ContactName=tianyu} about the {EmailSubject=test result} - send an email to {ContactName=jimmy klein} saying {Message=this is the message about weekend plans} - send an email to {ContactName=larry} , {ContactName=joseph} and {ContactName=billy larkson} - send an email to {ContactName=lily roth} and abc123@microsoft.com - send an email to {ContactName=lu} , {ContactName=yue} and {ContactName=qiong} about {EmailSubject=funding} - send an email to {RelationshipName=mom} - send an email to my {RelationshipName=brother} - send an email to {ContactName=nathan} with a {Category=red bang} - send an email to partone@gmail.com - send an email to partone_parttwo@microsoft.com - send an email to {ContactName=sean} about {EmailSubject=weekend plans} - send an email to {ContactName=zachary} about {EmailSubject=we can plan things let's go hiking} - send an email {Date=today} - send an email with {Category=read receipt} to {ContactName=peter} - send an {Category=important} email to {ContactName=olivia} - send an {Category=urgent} email - send an {Category=urgent} email from my {Line=work account} to {ContactName=christian} - send an {Category=urgent} email from my {Line=work} email to {ContactName=jack} - send and email about {EmailSubject=swim team practice} - send {ContactName=angela} an email marked as {Category=high priority} - send {ContactName=billy} an email with a {Category=red bang} - send email about {EmailSubject=homework plan} to {ContactName=raymond} and {ContactName=philip} - send email marked {Category=priority} to {ContactName=yun-sim} and {ContactName=yi} - send email to {ContactName=a} and {ContactName=tian} - send email to {ContactName=hannah} saying {Message=test} - send email to {ContactName=heather} about {EmailSubject=car} - send email to {ContactName=jiayi} {Date=today} - send email to {ContactName=kai xu}, {ContactName=mingming} and my {RelationshipName=mother} - send email to {ContactName=louis} and mark it {Category=important} - send email to partone.parttwo@outlook.com - send {Category=important} email to {ContactName=evelyn} and {ContactName=gary} - send {ContactName=jacqueline} an email with {Category=low priority} - send {Attachment=large files} through email - send {ContactName=lori} a new {Category=flagged} email - send mail to {ContactName=dorothy} - send my {Attachment=housekeeping doc} to {ContactName=jeffrey} - send my {Attachment=payment visio diagram} to {ContactName=ronald} - send new email to {ContactName=christian} and mark it {Category=high importance} - send the email - send the email {Time=now} - send this {Attachment=document} to an email - send {ContactName=thomas} an email - set an email {Date=today} - start a new email about {EmailSubject=marriage counselor appointments} - start a new email from {SenderName=tracy} saying {Message=here is my resume} - start a new email saying {Message=lets go to the park} - start a new email to {ContactName=aaron} about {EmailSubject=sleeping over tonight} - start an email to {ContactName=jason} about {EmailSubject=speaking up} - start new email about {EmailSubject=taco blog} to {ContactName=nicole} and {ContactName=emily} - start new email to {RelationshipName=friends} about the {EmailSubject=club} - start up a new email to {ContactName=michelle} about {EmailSubject=watching baseball} - the new email is {Category=high priority} that is being sent to {ContactName=jacob} - will you send a marked {Category=non urgent} email to {ContactName=james} - write an email about the {EmailSubject=fundraiser} - write an email which title is {EmailSubject=hello} and context is {Message=let's have meeting together} - write an {Category=urgent} email to {ContactName=bobby} - write email - write email to {RelationshipName=mom} subject is {EmailSubject=babysit} - ^(write|send|start) [(a|an|the)] [new] email to {ContactName}^ - ^[(send|write)] [(the|a)] [new] [(email|mail)] [to {ContactName}] [with message "{Message.Any}"] - ^(write|send|start) [(a|an|the)] [new] email to {ContactName} (about|on|with) [the subject] [that] {EmailSubject}^ ## ShowNext - are there any {Category=unread} messages? show {OrderReference=next} - go forward to {OrderReference=next} mails - go on, show me more mails - go to {OrderReference=next} mail - go to the {OrderReference=next} page - move forward - move on {OrderReference=next} mail by jason - move on to {OrderReference=next} mails - {OrderReference=next} email - {OrderReference=next} {Category=unread} email - {OrderReference=next} {Category=unread} one - show me {OrderReference=next} from {SenderName=mary} - show me the {OrderReference=next} - show me the {OrderReference=next} five mails - show {OrderReference=next} email - show {OrderReference=next} {Category=unread} - show the {OrderReference=next} email from my {FromRelationshipName=boss} - show the {OrderReference=next} emails by wong - show the {OrderReference=next} messages - the {OrderReference=next} email - the {OrderReference=next} {Category=important} message - ^(show|give|tell) [me] [the] next (email|message|mail)^ ## ShowPrevious - back to the {OrderReference=last} one from {SenderName=apple} - bring the {OrderReference=previous} one, i want to read it again - go to {OrderReference=previous} mails - move back to {OrderReference=last} mails - {OrderReference=previous} email - {OrderReference=previous} one please - show me {OrderReference=previous} email from {SenderName=jack} - show me the {OrderReference=last} three mails - show me the one {OrderReference=before} - show me the {OrderReference=previous} email - show {OrderReference=previous} in {Category=red} category - show {OrderReference=previous} one in inbox - show the {OrderReference=previous} email from my {FromRelationshipName=mentor} - show the {OrderReference=previous} one - the {OrderReference=previous} email - what is the {OrderReference=previous} email - ^(show|give|tell) [me] [the] previous (email|message|mail)^ > # Entity definitions $Attachment:simple $Category:simple $ContactName:simple $Date:simple $EmailSubject:simple $FromRelationshipName:simple $Line:simple $Message:simple $OrderReference:simple $PositionReference:simple $RelationshipName:simple $SearchTexts:simple $SenderName:simple $Time:simple > # PREBUILT Entity definitions $PREBUILT:email $PREBUILT:ordinal > # Phrase list definitions > # List entities > # RegEx entities `; /* tslint:enable */ export async function exampleFunctionDataWithSubwordFeaturizerWithLuContent( luContent: string): Promise<LuDataWithSubwordFeaturizer> { // ----------------------------------------------------------------------- const luDataWithSubwordFeaturizer: LuDataWithSubwordFeaturizer = await LuDataWithSubwordFeaturizer.createLuDataWithSubwordFeaturizer( luContent, new NgramSubwordFeaturizer(), true); const luUtterances: ITextIntentSequenceLabelObjectByPosition[] = luDataWithSubwordFeaturizer.getLuUtterances(); Utility.debuggingLog(`luUtterances=${Utility.getJsonStringified(luUtterances)}`); assert.ok(luUtterances, `luUtterances=${luUtterances}`); const intentInstanceIndexMapArray: Map<string, number[]> = luDataWithSubwordFeaturizer.getIntentInstanceIndexMapArray(); Utility.debuggingLog(`intentInstanceIndexMapSet=${Utility.stringMapArrayToJson(intentInstanceIndexMapArray)}`); const entityTypeInstanceIndexMapArray: Map<string, number[]> = luDataWithSubwordFeaturizer.getEntityTypeInstanceIndexMapArray(); Utility.debuggingLog(`entityTypeInstanceIndexMapSet=${Utility.stringMapArrayToJson(entityTypeInstanceIndexMapArray)}`); const numberLuUtterances: number = luDataWithSubwordFeaturizer.getNumberLuUtterances(); Utility.debuggingLog(`numberLuUtterances=${numberLuUtterances}`); assert.ok(numberLuUtterances === 601, `numberLuUtterances=${numberLuUtterances}`); const numberIntents: number = luDataWithSubwordFeaturizer.getNumberIntents(); Utility.debuggingLog(`numberIntents=${numberIntents}`); assert.ok(numberIntents === 15, `numberIntents=${numberIntents}`); const numberEntityTypes: number = luDataWithSubwordFeaturizer.getNumberEntityTypes(); Utility.debuggingLog(`numberEntityTypes=${numberEntityTypes}`); assert.ok(numberEntityTypes === 14, `numberEntityTypes=${numberEntityTypes}`); // ----------------------------------------------------------------------- const minNumberUtterancesToCoverAllIntentAndEntityTypeLabels: number = Math.max(numberIntents, numberEntityTypes); const maxNumberUtterancesToCoverAllIntentAndEntityTypeLabels: number = numberIntents + numberEntityTypes; const maxNumberCandidateUtterancesForSampling: number = numberLuUtterances - minNumberUtterancesToCoverAllIntentAndEntityTypeLabels; const minNumberCandidateUtterancesForSampling: number = numberLuUtterances - maxNumberUtterancesToCoverAllIntentAndEntityTypeLabels; // ----------------------------------------------------------------------- const results = luDataWithSubwordFeaturizer.collectSmallUtteranceIndexSetCoveringAllIntentEntityLabels(); const smallUtteranceIndexIntentMapCoveringAllIntentEntityLabels: Map<string, Set<number>> = results.smallUtteranceIndexIntentMapCoveringAllIntentEntityLabels; const smallUtteranceIndexEntityTypeMapCoveringAllIntentEntityLabels: Map<string, Set<number>> = results.smallUtteranceIndexEntityTypeMapCoveringAllIntentEntityLabels; const smallUtteranceIndexSetCoveringAllIntentEntityLabels: Set<number> = results.smallUtteranceIndexSetCoveringAllIntentEntityLabels; const remainingUtteranceIndexSet: Set<number> = results.remainingUtteranceIndexSet; Utility.debuggingLog(`smallUtteranceIndexIntentMapCoveringAllIntentEntityLabels=` + `${Utility.stringMapSetToJson(smallUtteranceIndexIntentMapCoveringAllIntentEntityLabels)}`); Utility.debuggingLog(`smallUtteranceIndexEntityTypeMapCoveringAllIntentEntityLabels=` + `${Utility.stringMapSetToJson(smallUtteranceIndexEntityTypeMapCoveringAllIntentEntityLabels)}`); Utility.debuggingLog(`smallUtteranceIndexSetCoveringAllIntentEntityLabels=` + `${Utility.setToJsonSerialization(smallUtteranceIndexSetCoveringAllIntentEntityLabels)}`); Utility.debuggingLog(`remainingUtteranceIndexSet=` + `${Utility.setToJsonSerialization(remainingUtteranceIndexSet)}`); Utility.debuggingLog(`smallUtteranceIndexSetCoveringAllIntentEntityLabels.size=` + `${smallUtteranceIndexSetCoveringAllIntentEntityLabels.size}`); assert.ok( smallUtteranceIndexSetCoveringAllIntentEntityLabels.size >= minNumberUtterancesToCoverAllIntentAndEntityTypeLabels, `smallUtteranceIndexSetCoveringAllIntentEntityLabels.size=` + `${smallUtteranceIndexSetCoveringAllIntentEntityLabels.size}` + `, minNumberUtterancesToCoverAllIntentAndEntityTypeLabels=` + `${minNumberUtterancesToCoverAllIntentAndEntityTypeLabels}`); assert.ok( smallUtteranceIndexSetCoveringAllIntentEntityLabels.size <= maxNumberUtterancesToCoverAllIntentAndEntityTypeLabels, `smallUtteranceIndexSetCoveringAllIntentEntityLabels.size=` + `${smallUtteranceIndexSetCoveringAllIntentEntityLabels.size}` + `, maxNumberUtterancesToCoverAllIntentAndEntityTypeLabels=` + `${maxNumberUtterancesToCoverAllIntentAndEntityTypeLabels}`); Utility.debuggingLog(`remainingUtteranceIndexSet.size=` + `${remainingUtteranceIndexSet.size}`); assert.ok( remainingUtteranceIndexSet.size <= maxNumberCandidateUtterancesForSampling, `remainingUtteranceIndexSet.size=` + `${remainingUtteranceIndexSet.size}` + `, maxNumberCandidateUtterancesForSampling=` + `${maxNumberCandidateUtterancesForSampling}`); assert.ok( remainingUtteranceIndexSet.size >= minNumberCandidateUtterancesForSampling, `remainingUtteranceIndexSet.size=` + `${remainingUtteranceIndexSet.size}` + `, minNumberCandidateUtterancesForSampling=` + `${minNumberCandidateUtterancesForSampling}`); // ----------------------------------------------------------------------- const limitInitialNumberOfInstancesPerCategory: number = 10; const resultsInitialSampling = luDataWithSubwordFeaturizer.collectUtteranceIndexSetSeedingIntentTrainingSet( smallUtteranceIndexIntentMapCoveringAllIntentEntityLabels, remainingUtteranceIndexSet, limitInitialNumberOfInstancesPerCategory); const seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels: Map<string, Set<number>> = resultsInitialSampling.seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels; const candidateUtteranceIndexSetSampled: Set<number> = resultsInitialSampling.candidateUtteranceIndexSetSampled; const candidateUtteranceIndexSetRemaining: Set<number> = resultsInitialSampling.candidateUtteranceIndexSetRemaining; Utility.debuggingLog(`seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels=` + `${Utility.stringMapSetToJson(seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels)}`); Utility.debuggingLog(`candidateUtteranceIndexSetSampled=` + `${Utility.setToJsonSerialization(candidateUtteranceIndexSetSampled)}`); Utility.debuggingLog(`candidateUtteranceIndexSetRemaining=` + `${Utility.setToJsonSerialization(candidateUtteranceIndexSetRemaining)}`); Utility.debuggingLog(`candidateUtteranceIndexSetSampled.size=` + `${candidateUtteranceIndexSetSampled.size}`); assert.ok( candidateUtteranceIndexSetSampled.size + smallUtteranceIndexSetCoveringAllIntentEntityLabels.size === 146, `candidateUtteranceIndexSetSampled.size=` + `${candidateUtteranceIndexSetSampled.size}` + `, smallUtteranceIndexSetCoveringAllIntentEntityLabels.size=` + `${smallUtteranceIndexSetCoveringAllIntentEntityLabels.size}`); Utility.debuggingLog(`candidateUtteranceIndexSetRemaining.size=` + `${candidateUtteranceIndexSetRemaining.size}`); assert.ok( candidateUtteranceIndexSetRemaining.size === 455, `candidateUtteranceIndexSetRemaining.size=` + `${candidateUtteranceIndexSetRemaining.size}`); const countSeedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels: number = [...seedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels].reduce( (accumulation: number, entry: [string, Set<number>]) => accumulation + entry[1].size, 0); Utility.debuggingLog(`countSeedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels=` + `${countSeedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels}`); assert.ok( countSeedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels === 146, `countSeedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels=` + `${countSeedingUtteranceIndexIntentMapCoveringAllIntentEntityLabels}`); // ----------------------------------------------------------------------- const featurizerLabelsLength: number = luDataWithSubwordFeaturizer.getFeaturizerLabels().length; Utility.debuggingLog(`featurizerLabelsLength=` + `${featurizerLabelsLength}`); assert.ok( featurizerLabelsLength === 15, `featurizerLabelsLength=` + `${featurizerLabelsLength}`); const featurizerFeaturesLength: number = luDataWithSubwordFeaturizer.getFeaturizerFeatures().length; Utility.debuggingLog(`featurizerFeaturesLength=` + `${featurizerFeaturesLength}`); assert.ok( featurizerFeaturesLength === 5645, `featurizerFeaturesLength=` + `${featurizerFeaturesLength}`); // ----------------------------------------------------------------------- return luDataWithSubwordFeaturizer; // ----------------------------------------------------------------------- } describe("Test Suite - data/LuDataWithSubwordFeaturizer", () => { it("Test.0000 exampleFunctionDataWithSubwordFeaturizerWithLuContent()", async function() { Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag()); this.timeout(UnitTestHelper.getDefaultUnitTestTimeout()); const luDataWithSubwordFeaturizer: LuDataWithSubwordFeaturizer = await exampleFunctionDataWithSubwordFeaturizerWithLuContent( LuContentEmail); }); });
the_stack
import { DateTime, Interval } from 'luxon'; import { CompletedDataPlayload, ContextExtensionsDefinition, DataPayload, InitializedContextExtensions, InteractedContextExtensions, InteractedResultExtensions, PausedResultExtensions, PlayedResultExtensions, ResultExtensionsDefinition, SeekedResultExtensions, TerminatedResultExtensions, VerbDefinition, XapiResourceType, } from '../types/XAPI'; import { truncateDecimalDigits } from '../utils/truncateDecimalDigits'; import { Nullable } from '../utils/types'; import { sendXAPIStatement, VideoXAPIStatementInterface } from '.'; export class VideoXAPIStatement implements VideoXAPIStatementInterface { private playedSegments: string = ''; private startSegment: Nullable<number> = null; private duration: number = 0; private startedAt: Nullable<DateTime> = null; private isCompleted: boolean = false; private completionThreshold: Nullable<number> = null; constructor(private jwt: string, private sessionId: string) {} setDuration(duration: number) { if (this.duration > 0) { throw new Error('duration is already set. You can not modify it anymore'); } if (duration <= 0) { throw new Error('duration must be strictly positive'); } this.duration = duration; this.computeCompletionThreshold(); } getPlayedSegment(): string { if (this.startSegment !== null) { if (this.playedSegments.length === 0) { return `${this.startSegment}`; } return `${this.playedSegments}[,]${this.startSegment}`; } return this.playedSegments; } mergeSegments(playedSegments: string[]): string { return ( playedSegments // remove non complete segments .filter((segment) => segment.indexOf('[.]') >= 0) // split segments to have begin and end segment in an array .map((segment) => segment.split('[.]')) // cast segment from string to number .reduce((acc: number[][], curr: string[]): number[][] => { acc.push([Number(curr[0]), Number(curr[1])]); return acc; }, []) // sort segment bounds in ascending order .map((segment) => segment.sort((a, b) => a - b)) // sort segments (numerically) .sort((a: number[], b: number[]): number => { return a[0] - b[0]; }) // once sorted, merge overlapped segments .reduce((acc: number[][], curr: number[], i: number): number[][] => { acc.push(curr); if (i === 0) { return acc; } // segment starting point included in previous segment if (acc[i][0] <= acc[i - 1][1]) { // segments included in previous segments if (acc[i][1] <= acc[i - 1][1]) { // remove "i"nth segments acc.splice(i, 1); } else { // remove overlapping part of the current segment with the previous segment acc[i - 1][1] = acc[i][1]; acc.splice(i, 1); } } return acc; }, []) // recast segments from arrays to string .map((segment) => segment.join('[.]')) .join('[,]') ); } getProgress(): number { const segments = this.getPlayedSegment().split('[,]'); const progressLength = segments // split segments to have begin and end segment in an array .map((segment) => segment.split('[.]')) // cast segment from string to number .reduce((acc: number[][], curr: string[]): number[][] => { acc.push([Number(curr[0]), Number(curr[1])]); return acc; }, []) // compute progression .reduce((acc: number, curr: number[]): number => { if (curr[1] > curr[0]) { acc += curr[1] - curr[0]; } return acc; }, 0); const progress = progressLength / this.duration; // Force to return no more than 1 to be sure to not have a progression higher than 100%. // This case can be found when the last timecode os higher than the video duration. return progress > 1.0 ? 1.0 : progress; } /** * compute the completion threshold to reach to consider a video * as completed. */ computeCompletionThreshold() { // beyond durationThreshold we've reached the maximal completion threshold const durationThreshold = 600; let duration = this.duration; if (duration > durationThreshold) { duration = durationThreshold; } this.completionThreshold = 0.7 + (0.25 * duration) / durationThreshold; } getCompletionThreshold(): number { if (this.completionThreshold === null) { throw new Error( 'Completion threshold cannot be computed. You should call initialized first', ); } return this.completionThreshold; } initialized(contextExtensions: InitializedContextExtensions): void { const extensions: { [key: string]: string | boolean | number | undefined; } = { [ContextExtensionsDefinition.sessionId]: this.sessionId, }; for (const key of Object.keys(contextExtensions)) { extensions[ ContextExtensionsDefinition[key as keyof InitializedContextExtensions] ] = contextExtensions[key as keyof InitializedContextExtensions]; } this.setDuration(contextExtensions.length); this.startedAt = DateTime.utc(); extensions[ContextExtensionsDefinition.completionTreshold] = truncateDecimalDigits(this.getCompletionThreshold()); const data: DataPayload = { context: { extensions, }, verb: { display: { 'en-US': 'initialized', }, id: VerbDefinition.initialized, }, }; this.send(data); } played(resultExtensions: PlayedResultExtensions): void { const time: number = truncateDecimalDigits(resultExtensions.time); this.addStartSegment(time); const data: DataPayload = { context: { extensions: { [ContextExtensionsDefinition.sessionId]: this.sessionId, }, }, result: { extensions: { [ResultExtensionsDefinition.time]: time, }, }, verb: { display: { 'en-US': 'played', }, id: VerbDefinition.played, }, }; this.send(data); } paused(resultExtensions: PausedResultExtensions): void { const time: number = truncateDecimalDigits(resultExtensions.time); this.addEndSegment(time); const progress = this.getProgress(); const data: DataPayload = { context: { extensions: { [ContextExtensionsDefinition.completionTreshold]: truncateDecimalDigits(this.getCompletionThreshold()), [ContextExtensionsDefinition.length]: this.duration, [ContextExtensionsDefinition.sessionId]: this.sessionId, }, }, result: { extensions: { [ResultExtensionsDefinition.time]: time, [ResultExtensionsDefinition.playedSegment]: this.getPlayedSegment(), [ResultExtensionsDefinition.progress]: truncateDecimalDigits(progress), }, }, verb: { display: { 'en-US': 'paused', }, id: VerbDefinition.paused, }, }; this.send(data); if (progress > this.getCompletionThreshold()) { this.completed(resultExtensions.time); } } seeked(resultExtensions: SeekedResultExtensions): void { const timeFrom: number = truncateDecimalDigits(resultExtensions.timeFrom); const timeTo: number = truncateDecimalDigits(resultExtensions.timeTo); this.addEndSegment(timeFrom); this.addStartSegment(timeTo); const data: DataPayload = { context: { extensions: { [ContextExtensionsDefinition.sessionId]: this.sessionId, }, }, result: { extensions: { [ResultExtensionsDefinition.timeFrom]: timeFrom, [ResultExtensionsDefinition.timeTo]: timeTo, [ContextExtensionsDefinition.length]: truncateDecimalDigits( this.duration, ), [ResultExtensionsDefinition.progress]: truncateDecimalDigits( this.getProgress(), ), [ResultExtensionsDefinition.playedSegment]: this.getPlayedSegment(), }, }, verb: { display: { 'en-US': 'seeked', }, id: VerbDefinition.seeked, }, }; this.send(data); } completed(time: number): void { if (this.isCompleted === true) { return; } const data: CompletedDataPlayload = { context: { extensions: { [ContextExtensionsDefinition.length]: this.duration, [ContextExtensionsDefinition.sessionId]: this.sessionId, [ContextExtensionsDefinition.completionTreshold]: truncateDecimalDigits(this.getCompletionThreshold()), }, }, result: { completion: true, duration: Interval.fromDateTimes(this.startedAt!, DateTime.utc()) .toDuration('milliseconds') .toISO(), extensions: { [ResultExtensionsDefinition.time]: truncateDecimalDigits(time), [ResultExtensionsDefinition.progress]: 1, [ResultExtensionsDefinition.playedSegment]: this.getPlayedSegment(), }, }, verb: { display: { 'en-US': 'completed', }, id: VerbDefinition.completed, }, }; this.send(data); this.isCompleted = true; } terminated(resultExtensions: TerminatedResultExtensions): void { if (this.startSegment !== null) { this.paused({ time: resultExtensions.time }); } const time = truncateDecimalDigits(resultExtensions.time); const data: DataPayload = { context: { extensions: { [ContextExtensionsDefinition.completionTreshold]: truncateDecimalDigits(this.getCompletionThreshold()), [ContextExtensionsDefinition.length]: this.duration, [ContextExtensionsDefinition.sessionId]: this.sessionId, }, }, result: { extensions: { [ResultExtensionsDefinition.time]: time, [ResultExtensionsDefinition.progress]: truncateDecimalDigits( this.getProgress(), ), [ResultExtensionsDefinition.playedSegment]: this.getPlayedSegment(), }, }, verb: { display: { 'en-US': 'terminated', }, id: VerbDefinition.terminated, }, }; this.send(data); } interacted( resultExtensions: InteractedResultExtensions, contextExtensions: InteractedContextExtensions, ): void { // find a way to remove this undefined type. There is no undefined value const extensions: { [key: string]: string | boolean | number | undefined; } = { [ContextExtensionsDefinition.sessionId]: this.sessionId, }; for (const key of Object.keys(contextExtensions)) { extensions[ ContextExtensionsDefinition[key as keyof InteractedContextExtensions] ] = contextExtensions[key as keyof InteractedContextExtensions]; } const data: DataPayload = { context: { extensions, }, result: { extensions: { [ResultExtensionsDefinition.time]: truncateDecimalDigits( resultExtensions.time, ), }, }, verb: { display: { 'en-US': 'interacted', }, id: VerbDefinition.interacted, }, }; this.send(data); } downloaded(quality: string | number): void { const data: DataPayload = { context: { extensions: { [ContextExtensionsDefinition.sessionId]: this.sessionId, [ContextExtensionsDefinition.quality]: quality, [ContextExtensionsDefinition.length]: this.duration, }, }, verb: { display: { 'en-US': 'downloaded', }, id: VerbDefinition.downloaded, }, }; this.send(data); } private send(data: DataPayload) { // duration is set when initialized is called. // While initialized is not called, no statement should be sent to the xapi server. if (!this.duration) { return; } sendXAPIStatement(data, this.jwt, XapiResourceType.VIDEO); } private addStartSegment(time: number) { this.startSegment = time; } private addEndSegment(time: number) { if (this.startSegment === null) { return; } const playedSegments = this.playedSegments.length === 0 ? [] : this.playedSegments.split('[,]'); playedSegments.push(`${this.startSegment}[.]${time}`); this.playedSegments = this.mergeSegments(playedSegments); this.startSegment = null; } }
the_stack
import assert from "assert"; import { Decimal } from "./Decimal"; import { StabilityDeposit } from "./StabilityDeposit"; import { Trove, TroveWithPendingRedistribution, UserTrove } from "./Trove"; import { Fees } from "./Fees"; import { LQTYStake } from "./LQTYStake"; import { FrontendStatus } from "./ReadableLiquity"; /** * State variables read from the blockchain. * * @public */ export interface LiquityStoreBaseState { /** Status of currently used frontend. */ frontend: FrontendStatus; /** Status of user's own frontend. */ ownFrontend: FrontendStatus; /** Number of Troves that are currently open. */ numberOfTroves: number; /** User's native currency balance (e.g. Ether). */ accountBalance: Decimal; /** User's LUSD token balance. */ lusdBalance: Decimal; /** User's LQTY token balance. */ lqtyBalance: Decimal; /** User's Uniswap ETH/LUSD LP token balance. */ uniTokenBalance: Decimal; /** The liquidity mining contract's allowance of user's Uniswap ETH/LUSD LP tokens. */ uniTokenAllowance: Decimal; /** Remaining LQTY that will be collectively rewarded to liquidity miners. */ remainingLiquidityMiningLQTYReward: Decimal; /** Amount of Uniswap ETH/LUSD LP tokens the user has staked in liquidity mining. */ liquidityMiningStake: Decimal; /** Total amount of Uniswap ETH/LUSD LP tokens currently staked in liquidity mining. */ totalStakedUniTokens: Decimal; /** Amount of LQTY the user has earned through mining liquidity. */ liquidityMiningLQTYReward: Decimal; /** * Amount of leftover collateral available for withdrawal to the user. * * @remarks * See {@link ReadableLiquity.getCollateralSurplusBalance | getCollateralSurplusBalance()} for * more information. */ collateralSurplusBalance: Decimal; /** Current price of the native currency (e.g. Ether) in USD. */ price: Decimal; /** Total amount of LUSD currently deposited in the Stability Pool. */ lusdInStabilityPool: Decimal; /** Total collateral and debt in the Liquity system. */ total: Trove; /** * Total collateral and debt per stake that has been liquidated through redistribution. * * @remarks * Needed when dealing with instances of {@link TroveWithPendingRedistribution}. */ totalRedistributed: Trove; /** * User's Trove in its state after the last direct modification. * * @remarks * The current state of the user's Trove can be found as * {@link LiquityStoreDerivedState.trove | trove}. */ troveBeforeRedistribution: TroveWithPendingRedistribution; /** User's stability deposit. */ stabilityDeposit: StabilityDeposit; /** Remaining LQTY that will be collectively rewarded to stability depositors. */ remainingStabilityPoolLQTYReward: Decimal; /** @internal */ _feesInNormalMode: Fees; /** User's LQTY stake. */ lqtyStake: LQTYStake; /** Total amount of LQTY currently staked. */ totalStakedLQTY: Decimal; /** @internal */ _riskiestTroveBeforeRedistribution: TroveWithPendingRedistribution; } /** * State variables derived from {@link LiquityStoreBaseState}. * * @public */ export interface LiquityStoreDerivedState { /** Current state of user's Trove */ trove: UserTrove; /** Calculator for current fees. */ fees: Fees; /** * Current borrowing rate. * * @remarks * A value between 0 and 1. * * @example * For example a value of 0.01 amounts to a borrowing fee of 1% of the borrowed amount. */ borrowingRate: Decimal; /** * Current redemption rate. * * @remarks * Note that the actual rate paid by a redemption transaction will depend on the amount of LUSD * being redeemed. * * Use {@link Fees.redemptionRate} to calculate a precise redemption rate. */ redemptionRate: Decimal; /** * Whether there are any Troves with collateral ratio below the * {@link MINIMUM_COLLATERAL_RATIO | minimum}. */ haveUndercollateralizedTroves: boolean; } /** * Type of {@link LiquityStore}'s {@link LiquityStore.state | state}. * * @remarks * It combines all properties of {@link LiquityStoreBaseState} and {@link LiquityStoreDerivedState} * with optional extra state added by the particular `LiquityStore` implementation. * * The type parameter `T` may be used to type the extra state. * * @public */ export type LiquityStoreState<T = unknown> = LiquityStoreBaseState & LiquityStoreDerivedState & T; /** * Parameters passed to {@link LiquityStore} listeners. * * @remarks * Use the {@link LiquityStore.subscribe | subscribe()} function to register a listener. * @public */ export interface LiquityStoreListenerParams<T = unknown> { /** The entire previous state. */ newState: LiquityStoreState<T>; /** The entire new state. */ oldState: LiquityStoreState<T>; /** Only the state variables that have changed. */ stateChange: Partial<LiquityStoreState<T>>; } const strictEquals = <T>(a: T, b: T) => a === b; const eq = <T extends { eq(that: T): boolean }>(a: T, b: T) => a.eq(b); const equals = <T extends { equals(that: T): boolean }>(a: T, b: T) => a.equals(b); const frontendStatusEquals = (a: FrontendStatus, b: FrontendStatus) => a.status === "unregistered" ? b.status === "unregistered" : b.status === "registered" && a.kickbackRate.eq(b.kickbackRate); const showFrontendStatus = (x: FrontendStatus) => x.status === "unregistered" ? '{ status: "unregistered" }' : `{ status: "registered", kickbackRate: ${x.kickbackRate} }`; const wrap = <A extends unknown[], R>(f: (...args: A) => R) => (...args: A) => f(...args); const difference = <T>(a: T, b: T) => Object.fromEntries( Object.entries(a).filter(([key, value]) => value !== (b as Record<string, unknown>)[key]) ) as Partial<T>; /** * Abstract base class of Liquity data store implementations. * * @remarks * The type parameter `T` may be used to type extra state added to {@link LiquityStoreState} by the * subclass. * * Implemented by {@link @liquity/lib-ethers#BlockPolledLiquityStore}. * * @public */ export abstract class LiquityStore<T = unknown> { /** Turn console logging on/off. */ logging = false; /** * Called after the state is fetched for the first time. * * @remarks * See {@link LiquityStore.start | start()}. */ onLoaded?: () => void; /** @internal */ protected _loaded = false; private _baseState?: LiquityStoreBaseState; private _derivedState?: LiquityStoreDerivedState; private _extraState?: T; private _updateTimeoutId: ReturnType<typeof setTimeout> | undefined; private _listeners = new Set<(params: LiquityStoreListenerParams<T>) => void>(); /** * The current store state. * * @remarks * Should not be accessed before the store is loaded. Assign a function to * {@link LiquityStore.onLoaded | onLoaded} to get a callback when this happens. * * See {@link LiquityStoreState} for the list of properties returned. */ get state(): LiquityStoreState<T> { return Object.assign({}, this._baseState, this._derivedState, this._extraState); } /** @internal */ protected abstract _doStart(): () => void; /** * Start monitoring the blockchain for Liquity state changes. * * @remarks * The {@link LiquityStore.onLoaded | onLoaded} callback will be called after the state is fetched * for the first time. * * Use the {@link LiquityStore.subscribe | subscribe()} function to register listeners. * * @returns Function to stop the monitoring. */ start(): () => void { const doStop = this._doStart(); return () => { doStop(); this._cancelUpdateIfScheduled(); }; } private _cancelUpdateIfScheduled() { if (this._updateTimeoutId !== undefined) { clearTimeout(this._updateTimeoutId); } } private _scheduleUpdate() { this._cancelUpdateIfScheduled(); this._updateTimeoutId = setTimeout(() => { this._updateTimeoutId = undefined; this._update(); }, 30000); } private _logUpdate<U>(name: string, next: U, show?: (next: U) => string): U { if (this.logging) { console.log(`${name} updated to ${show ? show(next) : next}`); } return next; } private _updateIfChanged<U>( equals: (a: U, b: U) => boolean, name: string, prev: U, next?: U, show?: (next: U) => string ): U { return next !== undefined && !equals(prev, next) ? this._logUpdate(name, next, show) : prev; } private _silentlyUpdateIfChanged<U>(equals: (a: U, b: U) => boolean, prev: U, next?: U): U { return next !== undefined && !equals(prev, next) ? next : prev; } private _updateFees(name: string, prev: Fees, next?: Fees): Fees { if (next && !next.equals(prev)) { // Filter out fee update spam that happens on every new block by only logging when string // representation changes. if (`${next}` !== `${prev}`) { this._logUpdate(name, next); } return next; } else { return prev; } } private _reduce( baseState: LiquityStoreBaseState, baseStateUpdate: Partial<LiquityStoreBaseState> ): LiquityStoreBaseState { return { frontend: this._updateIfChanged( frontendStatusEquals, "frontend", baseState.frontend, baseStateUpdate.frontend, showFrontendStatus ), ownFrontend: this._updateIfChanged( frontendStatusEquals, "ownFrontend", baseState.ownFrontend, baseStateUpdate.ownFrontend, showFrontendStatus ), numberOfTroves: this._updateIfChanged( strictEquals, "numberOfTroves", baseState.numberOfTroves, baseStateUpdate.numberOfTroves ), accountBalance: this._updateIfChanged( eq, "accountBalance", baseState.accountBalance, baseStateUpdate.accountBalance ), lusdBalance: this._updateIfChanged( eq, "lusdBalance", baseState.lusdBalance, baseStateUpdate.lusdBalance ), lqtyBalance: this._updateIfChanged( eq, "lqtyBalance", baseState.lqtyBalance, baseStateUpdate.lqtyBalance ), uniTokenBalance: this._updateIfChanged( eq, "uniTokenBalance", baseState.uniTokenBalance, baseStateUpdate.uniTokenBalance ), uniTokenAllowance: this._updateIfChanged( eq, "uniTokenAllowance", baseState.uniTokenAllowance, baseStateUpdate.uniTokenAllowance ), remainingLiquidityMiningLQTYReward: this._silentlyUpdateIfChanged( eq, baseState.remainingLiquidityMiningLQTYReward, baseStateUpdate.remainingLiquidityMiningLQTYReward ), liquidityMiningStake: this._updateIfChanged( eq, "liquidityMiningStake", baseState.liquidityMiningStake, baseStateUpdate.liquidityMiningStake ), totalStakedUniTokens: this._updateIfChanged( eq, "totalStakedUniTokens", baseState.totalStakedUniTokens, baseStateUpdate.totalStakedUniTokens ), liquidityMiningLQTYReward: this._silentlyUpdateIfChanged( eq, baseState.liquidityMiningLQTYReward, baseStateUpdate.liquidityMiningLQTYReward ), collateralSurplusBalance: this._updateIfChanged( eq, "collateralSurplusBalance", baseState.collateralSurplusBalance, baseStateUpdate.collateralSurplusBalance ), price: this._updateIfChanged(eq, "price", baseState.price, baseStateUpdate.price), lusdInStabilityPool: this._updateIfChanged( eq, "lusdInStabilityPool", baseState.lusdInStabilityPool, baseStateUpdate.lusdInStabilityPool ), total: this._updateIfChanged(equals, "total", baseState.total, baseStateUpdate.total), totalRedistributed: this._updateIfChanged( equals, "totalRedistributed", baseState.totalRedistributed, baseStateUpdate.totalRedistributed ), troveBeforeRedistribution: this._updateIfChanged( equals, "troveBeforeRedistribution", baseState.troveBeforeRedistribution, baseStateUpdate.troveBeforeRedistribution ), stabilityDeposit: this._updateIfChanged( equals, "stabilityDeposit", baseState.stabilityDeposit, baseStateUpdate.stabilityDeposit ), remainingStabilityPoolLQTYReward: this._silentlyUpdateIfChanged( eq, baseState.remainingStabilityPoolLQTYReward, baseStateUpdate.remainingStabilityPoolLQTYReward ), _feesInNormalMode: this._silentlyUpdateIfChanged( equals, baseState._feesInNormalMode, baseStateUpdate._feesInNormalMode ), lqtyStake: this._updateIfChanged( equals, "lqtyStake", baseState.lqtyStake, baseStateUpdate.lqtyStake ), totalStakedLQTY: this._updateIfChanged( eq, "totalStakedLQTY", baseState.totalStakedLQTY, baseStateUpdate.totalStakedLQTY ), _riskiestTroveBeforeRedistribution: this._silentlyUpdateIfChanged( equals, baseState._riskiestTroveBeforeRedistribution, baseStateUpdate._riskiestTroveBeforeRedistribution ) }; } private _derive({ troveBeforeRedistribution, totalRedistributed, _feesInNormalMode, total, price, _riskiestTroveBeforeRedistribution }: LiquityStoreBaseState): LiquityStoreDerivedState { const fees = _feesInNormalMode._setRecoveryMode(total.collateralRatioIsBelowCritical(price)); return { trove: troveBeforeRedistribution.applyRedistribution(totalRedistributed), fees, borrowingRate: fees.borrowingRate(), redemptionRate: fees.redemptionRate(), haveUndercollateralizedTroves: _riskiestTroveBeforeRedistribution .applyRedistribution(totalRedistributed) .collateralRatioIsBelowMinimum(price) }; } private _reduceDerived( derivedState: LiquityStoreDerivedState, derivedStateUpdate: LiquityStoreDerivedState ): LiquityStoreDerivedState { return { fees: this._updateFees("fees", derivedState.fees, derivedStateUpdate.fees), trove: this._updateIfChanged(equals, "trove", derivedState.trove, derivedStateUpdate.trove), borrowingRate: this._silentlyUpdateIfChanged( eq, derivedState.borrowingRate, derivedStateUpdate.borrowingRate ), redemptionRate: this._silentlyUpdateIfChanged( eq, derivedState.redemptionRate, derivedStateUpdate.redemptionRate ), haveUndercollateralizedTroves: this._updateIfChanged( strictEquals, "haveUndercollateralizedTroves", derivedState.haveUndercollateralizedTroves, derivedStateUpdate.haveUndercollateralizedTroves ) }; } /** @internal */ protected abstract _reduceExtra(extraState: T, extraStateUpdate: Partial<T>): T; private _notify(params: LiquityStoreListenerParams<T>) { // Iterate on a copy of `_listeners`, to avoid notifying any new listeners subscribed by // existing listeners, as that could result in infinite loops. // // Before calling a listener from our copy of `_listeners`, check if it has been removed from // the original set. This way we avoid calling listeners that have already been unsubscribed // by an earlier listener callback. [...this._listeners].forEach(listener => { if (this._listeners.has(listener)) { listener(params); } }); } /** * Register a state change listener. * * @param listener - Function that will be called whenever state changes. * @returns Function to unregister this listener. */ subscribe(listener: (params: LiquityStoreListenerParams<T>) => void): () => void { const uniqueListener = wrap(listener); this._listeners.add(uniqueListener); return () => { this._listeners.delete(uniqueListener); }; } /** @internal */ protected _load(baseState: LiquityStoreBaseState, extraState?: T): void { assert(!this._loaded); this._baseState = baseState; this._derivedState = this._derive(baseState); this._extraState = extraState; this._loaded = true; this._scheduleUpdate(); if (this.onLoaded) { this.onLoaded(); } } /** @internal */ protected _update( baseStateUpdate?: Partial<LiquityStoreBaseState>, extraStateUpdate?: Partial<T> ): void { assert(this._baseState && this._derivedState); const oldState = this.state; if (baseStateUpdate) { this._baseState = this._reduce(this._baseState, baseStateUpdate); } // Always running this lets us derive state based on passage of time, like baseRate decay this._derivedState = this._reduceDerived(this._derivedState, this._derive(this._baseState)); if (extraStateUpdate) { assert(this._extraState); this._extraState = this._reduceExtra(this._extraState, extraStateUpdate); } this._scheduleUpdate(); this._notify({ newState: this.state, oldState, stateChange: difference(this.state, oldState) }); } }
the_stack
import { arrayRemoveItem, ClassType } from '@deepkit/core'; import { ClassSchema, getClassSchema, stringifyUuid, writeUuid } from '@deepkit/type'; import { RpcMessageSubject } from '../client/message-subject'; import { AuthenticationError, ControllerDefinition, rpcAuthenticate, rpcClientId, rpcError, rpcPeerRegister, rpcResponseAuthenticate, RpcTypes } from '../model'; import { createBuffer, createRpcCompositeMessage, createRpcCompositeMessageSourceDest, createRpcMessage, createRpcMessageForBody, createRpcMessageSourceDest, createRpcMessageSourceDestForBody, RpcCreateMessageDef, rpcEncodeError, RpcMessage, RpcMessageReader, RpcMessageRouteType } from '../protocol'; import { RpcMessageWriter, RpcMessageWriterOptions } from '../writer'; import { RpcServerAction } from './action'; import { RpcKernelSecurity, SessionState } from './security'; import { RpcActionClient, RpcControllerState } from '../client/action'; import { RemoteController } from '../client/client'; import { InjectorContext, InjectorModule } from '@deepkit/injector'; import { Logger, LoggerInterface } from '@deepkit/logger'; export class RpcCompositeMessage { protected messages: RpcCreateMessageDef<any>[] = []; constructor( public type: number, protected id: number, protected writer: RpcConnectionWriter, protected clientId?: Uint8Array, protected source?: Uint8Array, protected routeType: RpcMessageRouteType.client | RpcMessageRouteType.server = RpcMessageRouteType.client ) { } add<T>(type: number, schema?: ClassSchema<T> | ClassType<T>, body?: T): this { this.messages.push({ type, schema: schema ? getClassSchema(schema) : undefined, body }); return this; } send() { if (this.clientId && this.source) { //we route back accordingly this.writer.write(createRpcCompositeMessageSourceDest(this.id, this.clientId, this.source, this.type, this.messages)); } else { this.writer.write(createRpcCompositeMessage(this.id, this.type, this.messages, this.routeType)); } } } export class RpcMessageBuilder { public routeType: RpcMessageRouteType.client | RpcMessageRouteType.server = RpcMessageRouteType.client; constructor( protected writer: RpcConnectionWriter, protected id: number, protected clientId?: Uint8Array, protected source?: Uint8Array, ) { } protected messageFactory<T>(type: RpcTypes, schemaOrBody?: ClassSchema<T> | Uint8Array, data?: T): Uint8Array { if (schemaOrBody instanceof Uint8Array) { if (this.source && this.clientId) { //we route back accordingly return createRpcMessageSourceDestForBody(this.id, type, this.clientId, this.source, schemaOrBody); } else { return createRpcMessageForBody(this.id, type, schemaOrBody, this.routeType); } } else { if (this.source && this.clientId) { //we route back accordingly return createRpcMessageSourceDest(this.id, type, this.clientId, this.source, schemaOrBody, data); } else { return createRpcMessage(this.id, type, schemaOrBody, data, this.routeType); } } } ack(): void { this.writer.write(this.messageFactory(RpcTypes.Ack)); } error(error: Error | string): void { const extracted = rpcEncodeError(error); this.writer.write(this.messageFactory(RpcTypes.Error, rpcError, extracted)); } reply<T>(type: number, schemaOrBody?: ClassSchema<T> | Uint8Array, body?: T): void { this.writer.write(this.messageFactory(type, schemaOrBody, body)); } composite(type: number): RpcCompositeMessage { return new RpcCompositeMessage(type, this.id, this.writer, this.clientId, this.source); } } /** * This is a reference implementation and only works in a single process. * A real-life implementation would use an external message-bus, like Redis & co. */ export class RpcPeerExchange { protected registeredPeers = new Map<string, RpcConnectionWriter>(); async isRegistered(id: string): Promise<boolean> { return this.registeredPeers.has(id); } async deregister(id: string | Uint8Array): Promise<void> { this.registeredPeers.delete('string' === typeof id ? id : stringifyUuid(id)); } register(id: string | Uint8Array, writer: RpcConnectionWriter): void { this.registeredPeers.set('string' === typeof id ? id : stringifyUuid(id), writer); } redirect(message: RpcMessage) { if (message.routeType == RpcMessageRouteType.peer) { const peerId = message.getPeerId(); const writer = this.registeredPeers.get(peerId); if (!writer) { //we silently ignore, as a pub/sub would do as well console.log('NO writer found for peer', peerId); return; } writer.write(message.getBuffer()); } if (message.routeType == RpcMessageRouteType.sourceDest) { const destination = message.getDestination(); //in this implementation we have to stringify it first, since v8 can not index Uint8Arrays const uuid = stringifyUuid(destination); const writer = this.registeredPeers.get(uuid); if (!writer) { console.log('NO writer found for destination', uuid); //we silently ignore, as a pub/sub would do as well return; } writer.write(message.getBuffer()); } } } export interface RpcConnectionWriter { write(buffer: Uint8Array): void; close(): void; bufferedAmount?(): number; clientAddress?(): string; } export abstract class RpcKernelBaseConnection { protected messageId: number = 0; public sessionState = new SessionState(); protected reader = new RpcMessageReader( this.handleMessage.bind(this), (id: number) => { this.writer.write(createRpcMessage(id, RpcTypes.ChunkAck)); } ); protected actionClient: RpcActionClient = new RpcActionClient(this); protected id: Uint8Array = writeUuid(createBuffer(16)); protected replies = new Map<number, ((message: RpcMessage) => void)>(); public writerOptions: RpcMessageWriterOptions = new RpcMessageWriterOptions; public writer: RpcMessageWriter = new RpcMessageWriter(this.transportWriter, this.reader, this.writerOptions); protected timeoutTimers: any[] = []; public readonly onClose: Promise<void>; protected onCloseResolve?: Function; constructor( protected transportWriter: RpcConnectionWriter, protected connections: RpcKernelConnections, ) { this.connections.connections.push(this); this.onClose = new Promise((resolve) => { this.onCloseResolve = resolve; }); } clientAddress(): string | undefined { return this.transportWriter.clientAddress ? this.transportWriter.clientAddress() : undefined; } createMessageBuilder(): RpcMessageBuilder { return new RpcMessageBuilder(this.writer, this.messageId++); } /** * Creates a regular timer using setTimeout() and automatically cancel it once the connection breaks or server stops. */ public setTimeout(cb: () => void, timeout: number): any { const timer = setTimeout(() => { cb(); arrayRemoveItem(this.timeoutTimers, timer); }, timeout); this.timeoutTimers.push(timer); return timer; } public close(): void { for (const timeout of this.timeoutTimers) clearTimeout(timeout); if (this.onCloseResolve) this.onCloseResolve(); arrayRemoveItem(this.connections.connections, this); this.writer.close(); } public feed(buffer: Uint8Array, bytes?: number): void { this.reader.feed(buffer, bytes); } public handleMessage(message: RpcMessage): void { if (message.routeType === RpcMessageRouteType.server) { //initiated by the server, so we check replies const callback = this.replies.get(message.id); if (callback) { callback(message); return; } } const response = new RpcMessageBuilder(this.writer, message.id); this.onMessage(message, response); } abstract onMessage(message: RpcMessage, response: RpcMessageBuilder): void | Promise<void>; public controller<T>(nameOrDefinition: string | ControllerDefinition<T>, timeoutInSeconds = 60): RemoteController<T> { const controller = new RpcControllerState('string' === typeof nameOrDefinition ? nameOrDefinition : nameOrDefinition.path); return new Proxy(this, { get: (target, propertyName) => { return (...args: any[]) => { return this.actionClient.action(controller, propertyName as string, args); }; } }) as any as RemoteController<T>; } public sendMessage<T>( type: number, schema?: ClassSchema<T>, body?: T ): RpcMessageSubject { const id = this.messageId++; const continuation = <T>(type: number, schema?: ClassSchema<T>, body?: T) => { //send a message with the same id. Don't use sendMessage() again as this would lead to a memory leak // and a new id generated. We want to use the same id. const message = createRpcMessage(id, type, schema, body, RpcMessageRouteType.server); this.writer.write(message); }; const subject = new RpcMessageSubject(continuation, () => { this.replies.delete(id); }); this.replies.set(id, (v: RpcMessage) => subject.next(v)); const message = createRpcMessage(id, type, schema, body, RpcMessageRouteType.server); this.writer.write(message); return subject; } } export class RpcKernelConnections { public connections: RpcKernelBaseConnection[] = []; broadcast(buffer: Uint8Array) { for (const connection of this.connections) { connection.writer.write(buffer); } } } export class RpcKernelConnection extends RpcKernelBaseConnection { public myPeerId?: string; protected actionHandler = new RpcServerAction(this.controllers, this.injector, this.security, this.sessionState); public routeType: RpcMessageRouteType.client | RpcMessageRouteType.server = RpcMessageRouteType.client; constructor( writer: RpcConnectionWriter, connections: RpcKernelConnections, protected controllers: Map<string, { controller: ClassType, module?: InjectorModule }>, protected security = new RpcKernelSecurity(), protected injector: InjectorContext, protected peerExchange: RpcPeerExchange, protected logger: LoggerInterface = new Logger(), ) { super(writer, connections); this.onClose.then(() => this.actionHandler.onClose()); this.peerExchange.register(this.id, this.writer); } async onMessage(message: RpcMessage): Promise<void> { if (message.routeType == RpcMessageRouteType.peer && message.getPeerId() !== this.myPeerId) { // console.log('Redirect peer message', RpcTypes[message.type]); if (!await this.security.isAllowedToSendToPeer(this.sessionState.getSession(), message.getPeerId())) { new RpcMessageBuilder(this.writer, message.id).error(new Error('Access denied')); return; } this.peerExchange.redirect(message); return; } if (message.routeType == RpcMessageRouteType.sourceDest) { // console.log('Redirect sourceDest message', RpcTypes[message.type]); this.peerExchange.redirect(message); return; } if (message.type === RpcTypes.Ping) { this.writer.write(createRpcMessage(message.id, RpcTypes.Pong)); return; } //all outgoing replies need to be routed to the source via sourceDest messages. const response = new RpcMessageBuilder(this.writer, message.id, this.id, message.routeType === RpcMessageRouteType.peer ? message.getSource() : undefined); response.routeType = this.routeType; try { if (message.routeType === RpcMessageRouteType.client) { switch (message.type) { case RpcTypes.ClientId: return response.reply(RpcTypes.ClientIdResponse, rpcClientId, { id: this.id }); case RpcTypes.PeerRegister: return await this.registerAsPeer(message, response); case RpcTypes.PeerDeregister: return this.deregisterAsPeer(message, response); } } switch (message.type) { case RpcTypes.Authenticate: return await this.authenticate(message, response); case RpcTypes.ActionType: return await this.actionHandler.handleActionTypes(message, response); case RpcTypes.Action: return await this.actionHandler.handleAction(message, response); default: return await this.actionHandler.handle(message, response); } } catch (error) { response.error(error); } } protected async authenticate(message: RpcMessage, response: RpcMessageBuilder) { const body = message.parseBody(rpcAuthenticate); try { const session = await this.security.authenticate(body.token); this.sessionState.setSession(session); response.reply(RpcTypes.AuthenticateResponse, rpcResponseAuthenticate, { username: session.username }); } catch (error) { if (error instanceof AuthenticationError) throw new Error(error.message); this.logger.error('authenticate failed', error); throw new AuthenticationError(); } } protected async deregisterAsPeer(message: RpcMessage, response: RpcMessageBuilder) { const body = message.parseBody(rpcPeerRegister); try { if (body.id !== this.myPeerId) { return response.error(new Error(`Not registered as that peer`)); } this.myPeerId = undefined; await this.peerExchange.deregister(body.id); response.ack(); } catch (error) { this.logger.error('deregisterAsPeer failed', error); response.error(new Error('Failed')); } } protected async registerAsPeer(message: RpcMessage, response: RpcMessageBuilder) { const body = message.parseBody(rpcPeerRegister); try { if (await this.peerExchange.isRegistered(body.id)) { return response.error(new Error(`Peer ${body.id} already registereed`)); } if (!await this.security.isAllowedToRegisterAsPeer(this.sessionState.getSession(), body.id)) { response.error(new Error('Access denied')); return; } await this.peerExchange.register(body.id, this.writer); this.myPeerId = body.id; response.ack(); } catch (error) { this.logger.error('registerAsPeer failed', error); response.error(new Error('Failed')); } } } export type OnConnectionCallback = (connection: RpcKernelConnection, injector: InjectorContext, logger: LoggerInterface) => void; /** * The kernel is responsible for parsing the message header, redirecting to peer if necessary, loading the body parser, * and encode/send outgoing messages. */ export class RpcKernel { public readonly controllers = new Map<string, { controller: ClassType, module: InjectorModule }>(); protected peerExchange = new RpcPeerExchange; protected connections = new RpcKernelConnections; protected RpcKernelConnection = RpcKernelConnection; protected onConnectionListeners: OnConnectionCallback[] = []; protected autoInjector: boolean = false; public injector: InjectorContext; constructor( injector?: InjectorContext, protected security = new RpcKernelSecurity(), protected logger: LoggerInterface = new Logger(), ) { if (injector) { this.injector = injector; } else { this.injector = InjectorContext.forProviders([ SessionState, //will be provided when scope is created {provide: RpcKernelConnection, scope: 'rpc', useValue: undefined}, ]); this.autoInjector = true; } } public onConnection(callback: OnConnectionCallback) { this.onConnectionListeners.push(callback); return () => { arrayRemoveItem(this.onConnectionListeners, callback); }; } /** * This registers the controller and adds it as provider to the injector. * * If you created a kernel with custom injector, you probably want to set addAsProvider to false. * Adding a provider is rather expensive, so you should prefer to create a kernel with pre-filled injector. */ public registerController(id: string | ControllerDefinition<any>, controller: ClassType, module?: InjectorModule) { if (this.autoInjector) { if (!this.injector.rootModule.isProvided(controller)) { this.injector.rootModule.addProvider({ provide: controller, scope: 'rpc' }); } } this.controllers.set('string' === typeof id ? id : id.path, { controller, module: module || this.injector.rootModule }); } createConnection(writer: RpcConnectionWriter, injector?: InjectorContext): RpcKernelBaseConnection { if (!injector) injector = this.injector.createChildScope('rpc'); const connection = new this.RpcKernelConnection(writer, this.connections, this.controllers, this.security, injector, this.peerExchange, this.logger); injector.set(RpcKernelConnection, connection); for (const on of this.onConnectionListeners) on(connection, injector, this.logger); return connection; } }
the_stack
import { b, x } from 'code-red'; import Binding from '../../../nodes/Binding.ts'; import ElementWrapper from '../Element/index.ts'; import InlineComponentWrapper from '../InlineComponent/index.ts'; import get_object from '../../../utils/get_object.ts'; import replace_object from '../../../utils/replace_object.ts'; import Block from '../../Block.ts'; import Renderer from '../../Renderer.ts'; import flatten_reference from '../../../utils/flatten_reference.ts'; import { Node, Identifier } from 'estree'; import add_to_set from '../../../utils/add_to_set.ts'; import mark_each_block_bindings from '../shared/mark_each_block_bindings.ts'; import handle_select_value_binding from './handle_select_value_binding.ts'; export default class BindingWrapper { node: Binding; parent: ElementWrapper | InlineComponentWrapper; object: string; handler: { uses_context: boolean; mutation: (Node | Node[]); contextual_dependencies: Set<string>; lhs?: Node; }; snippet: Node; is_readonly: boolean; needs_lock: boolean; constructor(block: Block, node: Binding, parent: ElementWrapper | InlineComponentWrapper) { this.node = node; this.parent = parent; const { dependencies } = this.node.expression; block.add_dependencies(dependencies); // TODO does this also apply to e.g. `<input type='checkbox' bind:group='foo'>`? handle_select_value_binding(this, dependencies); if (node.is_contextual) { mark_each_block_bindings(this.parent, this.node); } this.object = get_object(this.node.expression.node).name; // view to model this.handler = get_event_handler(this, parent.renderer, block, this.object, this.node.raw_expression); this.snippet = this.node.expression.manipulate(block); this.is_readonly = this.node.is_readonly; this.needs_lock = this.node.name === 'currentTime'; // TODO others? } get_dependencies() { const dependencies = new Set(this.node.expression.dependencies); this.node.expression.dependencies.forEach((prop: string) => { const indirect_dependencies = this.parent.renderer.component.indirect_dependencies.get(prop); if (indirect_dependencies) { indirect_dependencies.forEach(indirect_dependency => { dependencies.add(indirect_dependency); }); } }); return dependencies; } is_readonly_media_attribute() { return this.node.is_readonly_media_attribute(); } render(block: Block, lock: Identifier) { if (this.is_readonly) return; const { parent } = this; const update_conditions: any[] = this.needs_lock ? [x`!${lock}`] : []; const mount_conditions: any[] = []; const dependency_array = Array.from(this.get_dependencies()); if (dependency_array.length > 0) { update_conditions.push(block.renderer.dirty(dependency_array)); } if (parent.node.name === 'input') { const type = parent.node.get_static_attribute_value('type'); if ( type === null || type === '' || type === 'text' || type === 'email' || type === 'password' ) { update_conditions.push( x`${parent.var}.${this.node.name} !== ${this.snippet}` ); } else if (type === 'number') { update_conditions.push( x`@to_number(${parent.var}.${this.node.name}) !== ${this.snippet}` ); } } // model to view let update_dom = get_dom_updater(parent, this); let mount_dom = update_dom; // special cases switch (this.node.name) { case 'group': { const { binding_group, is_context, contexts, index } = get_binding_group(parent.renderer, this.node, block); block.renderer.add_to_context('$$binding_groups'); if (is_context) { if (contexts.length > 1) { let binding_group = x`${block.renderer.reference('$$binding_groups')}[${index}]`; for (const name of contexts.slice(0, -1)) { binding_group = x`${binding_group}[${block.renderer.reference(name)}]`; block.chunks.init.push( b`${binding_group} = ${binding_group} || [];` ); } } block.chunks.init.push( b`${binding_group(true)} = [];` ); } block.chunks.hydrate.push( b`${binding_group(true)}.push(${parent.var});` ); block.chunks.destroy.push( b`${binding_group(true)}.splice(${binding_group(true)}.indexOf(${parent.var}), 1);` ); break; } case 'textContent': update_conditions.push(x`${this.snippet} !== ${parent.var}.textContent`); mount_conditions.push(x`${this.snippet} !== void 0`); break; case 'innerHTML': update_conditions.push(x`${this.snippet} !== ${parent.var}.innerHTML`); mount_conditions.push(x`${this.snippet} !== void 0`); break; case 'currentTime': update_conditions.push(x`!@_isNaN(${this.snippet})`); mount_dom = null; break; case 'playbackRate': case 'volume': update_conditions.push(x`!@_isNaN(${this.snippet})`); mount_conditions.push(x`!@_isNaN(${this.snippet})`); break; case 'paused': { // this is necessary to prevent audio restarting by itself const last = block.get_unique_name(`${parent.var.name}_is_paused`); block.add_variable(last, x`true`); update_conditions.push(x`${last} !== (${last} = ${this.snippet})`); update_dom = b`${parent.var}[${last} ? "pause" : "play"]();`; mount_dom = null; break; } case 'value': if (parent.node.get_static_attribute_value('type') === 'file') { update_dom = null; mount_dom = null; } } if (update_dom) { if (update_conditions.length > 0) { const condition = update_conditions.reduce((lhs, rhs) => x`${lhs} && ${rhs}`); block.chunks.update.push(b` if (${condition}) { ${update_dom} } `); } else { block.chunks.update.push(update_dom); } } if (mount_dom) { if (mount_conditions.length > 0) { const condition = mount_conditions.reduce((lhs, rhs) => x`${lhs} && ${rhs}`); block.chunks.mount.push(b` if (${condition}) { ${mount_dom} } `); } else { block.chunks.mount.push(mount_dom); } } } } function get_dom_updater( element: ElementWrapper | InlineComponentWrapper, binding: BindingWrapper ) { const { node } = element; if (binding.is_readonly_media_attribute()) { return null; } if (binding.node.name === 'this') { return null; } if (node.name === 'select') { return node.get_static_attribute_value('multiple') === true ? b`@select_options(${element.var}, ${binding.snippet})` : b`@select_option(${element.var}, ${binding.snippet})`; } if (binding.node.name === 'group') { const type = node.get_static_attribute_value('type'); const condition = type === 'checkbox' ? x`~${binding.snippet}.indexOf(${element.var}.__value)` : x`${element.var}.__value === ${binding.snippet}`; return b`${element.var}.checked = ${condition};`; } if (binding.node.name === 'value') { return b`@set_input_value(${element.var}, ${binding.snippet});`; } return b`${element.var}.${binding.node.name} = ${binding.snippet};`; } function get_binding_group(renderer: Renderer, value: Binding, block: Block) { const { parts } = flatten_reference(value.raw_expression); let keypath = parts.join('.'); const contexts = []; for (const dep of value.expression.contextual_dependencies) { const context = block.bindings.get(dep); let key; let name; if (context) { key = context.object.name; name = context.property.name; } else { key = dep; name = dep; } keypath = `${key}@${keypath}`; contexts.push(name); } if (!renderer.binding_groups.has(keypath)) { const index = renderer.binding_groups.size; contexts.forEach(context => { renderer.add_to_context(context, true); }); renderer.binding_groups.set(keypath, { binding_group: (to_reference: boolean = false) => { let binding_group = '$$binding_groups'; let _secondary_indexes = contexts; if (to_reference) { binding_group = block.renderer.reference(binding_group); _secondary_indexes = _secondary_indexes.map(name => block.renderer.reference(name)); } if (_secondary_indexes.length > 0) { let obj = x`${binding_group}[${index}]`; _secondary_indexes.forEach(secondary_index => { obj = x`${obj}[${secondary_index}]`; }); return obj; } else { return x`${binding_group}[${index}]`; } }, is_context: contexts.length > 0, contexts, index }); } return renderer.binding_groups.get(keypath); } function get_event_handler( binding: BindingWrapper, renderer: Renderer, block: Block, name: string, lhs: Node ): { uses_context: boolean; mutation: (Node | Node[]); contextual_dependencies: Set<string>; lhs?: Node; } { const contextual_dependencies = new Set<string>(binding.node.expression.contextual_dependencies); const context = block.bindings.get(name); let set_store; if (context) { const { object, property, store, snippet } = context; lhs = replace_object(lhs, snippet); contextual_dependencies.add(object.name); contextual_dependencies.add(property.name); contextual_dependencies.delete(name); if (store) { set_store = b`${store}.set(${`$${store}`});`; } } else { const object = get_object(lhs); if (object.name[0] === '$') { const store = object.name.slice(1); set_store = b`${store}.set(${object.name});`; } } const value = get_value_from_dom(renderer, binding.parent, binding, block, contextual_dependencies); const mutation = b` ${lhs} = ${value}; ${set_store} `; return { uses_context: binding.node.is_contextual || binding.node.expression.uses_context, // TODO this is messy mutation, contextual_dependencies, lhs }; } function get_value_from_dom( renderer: Renderer, element: ElementWrapper | InlineComponentWrapper, binding: BindingWrapper, block: Block, contextual_dependencies: Set<string> ) { const { node } = element; const { name } = binding.node; if (name === 'this') { return x`$$value`; } // <select bind:value='selected> if (node.name === 'select') { return node.get_static_attribute_value('multiple') === true ? x`@select_multiple_value(this)` : x`@select_value(this)`; } const type = node.get_static_attribute_value('type'); // <input type='checkbox' bind:group='foo'> if (name === 'group') { if (type === 'checkbox') { const { binding_group, contexts } = get_binding_group(renderer, binding.node, block); add_to_set(contextual_dependencies, contexts); return x`@get_binding_group_value(${binding_group()}, this.__value, this.checked)`; } return x`this.__value`; } // <input type='range|number' bind:value> if (type === 'range' || type === 'number') { return x`@to_number(this.${name})`; } if ((name === 'buffered' || name === 'seekable' || name === 'played')) { return x`@time_ranges_to_array(this.${name})`; } // everything else return x`this.${name}`; }
the_stack
import slash from 'slash2'; import defaultSettings from './defaultSettings'; const { pwa } = defaultSettings; const backend_url = process.env.API_URL || 'http://backend:8000/'; const plugins = [ ['umi-plugin-antd-icon-config', {}], [ 'umi-plugin-react', { antd: true, dva: { hmr: true, }, locale: { enable: true, default: 'pl-PL', // default true, when it is true, will use `navigator.language` overwrite default baseNavigator: true, }, dynamicImport: { loadingComponent: './components/PageLoading/index', webpackChunkName: true, level: 3, }, pwa: pwa ? { workboxPluginMode: 'InjectManifest', workboxOptions: { importWorkboxFrom: 'local', }, } : false, // default close dll, because issue https://github.com/ant-design/ant-design-pro/issues/4665 // dll features https://webpack.js.org/plugins/dll-plugin/ // dll: { // include: ['dva', 'dva/router', 'dva/saga', 'dva/fetch'], // exclude: ['@babel/runtime', 'netlify-lambda'], // }, }, ], [ 'umi-plugin-pro-block', { moveMock: false, moveService: false, modifyRequest: true, autoAddMenu: true, }, ], ]; const casesRoutes = { name: 'cases', icon: 'FileTextOutlined', path: '/cases', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/cases/list', component: './cases/CasesListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/cases/new', component: './cases/CasesDetailView', }, { name: 'edit', path: '/cases/edit/:id', component: './cases/CasesDetailView', hideInMenu: true, }, { exact: true, path: '/cases', redirect: '/cases/list' }, ], }; const usersRoutes = { name: 'users', icon: 'FileTextOutlined', path: '/users', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/users/list', component: './users/UsersListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/users/new', component: './users/UsersDetailView', }, { name: 'edit', path: '/users/edit/:id', component: './users/UsersDetailView', hideInMenu: true, }, { exact: true, path: '/users', redirect: '/users/list' }, ], }; const documentTypesRoutes = { name: 'document-types', icon: 'FileTextOutlined', path: '/documentTypes', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/documentTypes', component: './documentTypes/DocumentTypesListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/documentTypes/new', component: './documentTypes/DocumentTypesDetailView', }, { name: 'edit', path: '/documentTypes/edit/:id', component: './documentTypes/DocumentTypesDetailView', hideInMenu: true, }, ], }; const eventsRoutes = { name: 'events', icon: 'FileTextOutlined', path: '/events', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/events/list', component: './events/EventsListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/events/new', component: './events/EventsDetailView', }, { name: 'edit', path: '/events/edit/:id', component: './events/EventsDetailView', hideInMenu: true, }, { exact: true, path: '/events', redirect: '/events/list' }, ], }; const tagsRoutes = { name: 'tags', icon: 'FileTextOutlined', path: '/tags', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/tags/list', component: './tags/TagsListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/tags/new', component: './tags/TagsDetailView', }, { name: 'edit', path: '/tags/edit/:id', component: './tags/TagsDetailView', hideInMenu: true, }, { exact: true, path: '/tags', redirect: '/tags/list' }, ], }; const channelsRoutes = { name: 'channels', icon: 'FileTextOutlined', path: '/channels', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/channels/list', component: './channels/ChannelsListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/channels/new', component: './channels/ChannelsDetailView', }, { name: 'edit', path: '/channels/edit/:id', component: './channels/ChannelsDetailView', hideInMenu: true, }, { exact: true, path: '/channels', redirect: '/channels/list' }, ], }; const featuresRoutes = { name: 'features', icon: 'FileTextOutlined', path: '/features', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/features/list', component: './features/FeaturesListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/features/new', component: './features/FeaturesDetailView', }, { name: 'edit', path: '/features/edit/:id', component: './features/FeaturesDetailView', hideInMenu: true, }, { exact: true, path: '/features', redirect: '/features/list' }, ], }; const featureOptionsRoutes = { name: 'feature-options', icon: 'FileTextOutlined', path: '/featureOptions', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/featureOptions/list', component: './featureOptions/FeatureOptionsListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/featureOptions/new', component: './featureOptions/FeatureOptionsDetailView', }, { name: 'edit', path: '/featureOptions/edit/:id', component: './featureOptions/FeatureOptionsDetailView', hideInMenu: true, }, { exact: true, path: '/featureOptions', redirect: '/featureOptions/list' }, ], }; const institutionsRoutes = { name: 'institutions', icon: 'FileTextOutlined', path: '/institutions', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/institutions/list', component: './institutions/InstitutionsListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/institutions/new', component: './institutions/InstitutionsDetailView', }, { name: 'edit', path: '/institutions/edit/:id', component: './institutions/InstitutionsDetailView', hideInMenu: true, }, { exact: true, path: '/institutions', redirect: '/institutions/list' }, ], }; const lettersRoutes = { name: 'letters', icon: 'FileTextOutlined', path: '/letters', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/letters/list', component: './letters/LettersListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/letters/new', component: './letters/LettersDetailView', }, { name: 'edit', path: '/letters/edit/:id', component: './letters/LettersDetailView', hideInMenu: true, }, { exact: true, path: '/letters', redirect: '/letters/list' }, ], }; const administrativeUnitsRoutes = { name: 'administrative-units', icon: 'FileTextOutlined', path: '/administrativeUnits', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/administrativeUnits/list', component: './administrativeUnits/AdministrativeUnitsListView', }, { exact: true, path: '/administrativeUnits', redirect: '/administrativeUnits/list' }, ], }; const notesRoutes = { name: 'notes', icon: 'FileTextOutlined', path: '/notes', routes: [ { name: 'list', icon: 'FileTextOutlined', path: '/notes/list', component: './notes/NotesListView', }, { name: 'new', icon: 'FileAddOutlined', path: '/notes/new', component: './notes/NotesDetailView', }, { name: 'edit', path: '/notes/edit/:id', component: './notes/NotesDetailView', hideInMenu: true, }, { exact: true, path: '/notes', redirect: '/notes/list' }, ], }; const loginRoutes = { path: '/login', component: '../layouts/LoginLayout', hideInMenu: true, routes: [ { name: 'login.sign-in', path: '/login/sign-in', component: './login/SignInView', hideInMenu: true, }, { name: 'login.callback', path: '/login/callback', component: './login/OAuthCallbackView', }, { exact: true, path: '/login', redirect: '/login/sign-in' }, ], }; const errorRoutes = { path: '/404', component: '../layouts/LoginLayout', routes: [ { component: './exception/404', }, ], }; export default { plugins, hash: true, targets: { ie: 11, }, // umi routes: https://umijs.org/zh/guide/router.html routes: [ { path: '/*', component: '../layouts/BlankLayout', routes: [ loginRoutes, errorRoutes, { path: '/', component: '../layouts/BasicLayout', Routes: ['src/pages/Authorized'], authority: ['admin', 'user'], routes: [ casesRoutes, lettersRoutes, eventsRoutes, notesRoutes, administrativeUnitsRoutes, tagsRoutes, channelsRoutes, institutionsRoutes, featuresRoutes, featureOptionsRoutes, usersRoutes, documentTypesRoutes, { path: '/', exact: true, redirect: '/cases/list' }, { redirect: '/404' }, ], }, ], }, ], // Theme for antd: https://ant.design/docs/react/customize-theme-cn theme: { // ...darkTheme, }, ignoreMomentLocale: true, lessLoaderOptions: { javascriptEnabled: true, }, disableRedirectHoist: true, cssLoaderOptions: { modules: true, getLocalIdent: (context, _, localName) => { if ( context.resourcePath.includes('node_modules') || context.resourcePath.includes('ant.design.pro.less') || context.resourcePath.includes('global.less') ) { return localName; } const match = context.resourcePath.match(/src(.*)/); if (match && match[1]) { const antdProPath = match[1].replace('.less', ''); const arr = slash(antdProPath) .split('/') .map(a => a.replace(/([A-Z])/g, '-$1')) .map(a => a.toLowerCase()); return `antd-pro${arr.join('-')}-${localName}`.replace(/--/g, '-'); } return localName; }, }, manifest: { basePath: '/', }, chainWebpack: config => { config.module.rule('small-eod-client').parser({ amd: false }); config.plugin('env').use(require.resolve('webpack/lib/DefinePlugin'), [ { BUILD_SHA: JSON.stringify(process.env.COMMIT_SHA), BUILD_BRANCH: JSON.stringify(process.env.COMMIT_BRANCH), BUILD_DATE: JSON.stringify(new Date().toISOString()), }, ]); }, proxy: Object.fromEntries( ['api', 'admin', 'static', 'media'].map(x => [ `/${x}/`, { target: backend_url, changeOrigin: true, }, ]), ), };
the_stack
import {Array3D, InputProvider, Tensor, Optimizer, CostReduction, FeedEntry, Session, NDArrayMath, NDArray, Scalar, GraphRunnerEventObserver} from 'deeplearn'; const DEFAULT_EVAL_INTERVAL_MS = 1500; const DEFAULT_COST_INTERVAL_MS = 500; const DEFAULT_INFERENCE_EXAMPLE_INTERVAL_MS = 3000; export interface MyGraphRunnerEventObserver { batchesTrainedCallback?: (totalBatchesTrained: number) => void; discCostCallback?: (cost: Scalar) => void; genCostCallback?: (cost: Scalar) => void; metricCallback?: (metric: NDArray) => void; inferenceExamplesCallback?: (feeds: FeedEntry[][], inferenceValues: NDArray[][]) => void; inferenceExamplesPerSecCallback?: (examplesPerSec: number) => void; trainExamplesPerSecCallback?: (examplesPerSec: number) => void; totalTimeCallback?: (totalTimeSec: number) => void; doneTrainingCallback?: () => void; } export enum MetricReduction { SUM, MEAN } /** * A class that drives the training of a graph model given a dataset. It allows * the user to provide a set of callbacks for measurements like cost, accuracy, * and speed of training. */ export class MyGraphRunner { private discCostTensor: Tensor; private genCostTensor: Tensor; private discTrainFeedEntries: FeedEntry[]; private genTrainFeedEntries: FeedEntry[]; private batchSize: number; private genOptimizer: Optimizer; private discOptimizer: Optimizer; private currentTrainLoopNumBatches: number|undefined; private costIntervalMs: number; private genImageTensor: Tensor; private discPredictionFakeTensor: Tensor; private discPredictionRealTensor: Tensor; private inferenceFeedEntries: FeedEntry[]|undefined; private inferenceExampleIntervalMs: number; private inferenceExampleCount: number; // Runtime information. private isTraining: boolean; private totalBatchesTrained: number; private batchesTrainedThisRun: number; private lastComputedMetric: NDArray; private isInferring: boolean; private lastInferTimeoutID: number; private currentInferenceLoopNumPasses: number|undefined; private inferencePassesThisRun: number; private trainStartTimestamp: number; private lastCostTimestamp = 0; private lastEvalTimestamp = 0; private lastStopTimestamp: number|null; private totalIdleTimeMs = 0; private zeroScalar: Scalar; private metricBatchSizeScalar: Scalar; constructor( private math: NDArrayMath, private session: Session, private eventObserver: MyGraphRunnerEventObserver) { this.resetStatistics(); this.zeroScalar = Scalar.new(0); } resetStatistics() { this.totalBatchesTrained = 0; this.totalIdleTimeMs = 0; this.lastStopTimestamp = null; } /** * Start the training loop with an optional number of batches to train for. * Optionally takes a metric tensor and feed entries to compute periodically. * This can be used for computing accuracy, or a similar metric. */ train( discCostTensor: Tensor, genCostTensor: Tensor, discTrainFeedEntries: FeedEntry[], genTrainFeedEntries: FeedEntry[], batchSize: number, discOptimizer: Optimizer, genOptimizer: Optimizer, numBatches?: number, costIntervalMs = DEFAULT_COST_INTERVAL_MS) { this.discCostTensor = discCostTensor; this.genCostTensor = genCostTensor; this.discTrainFeedEntries = discTrainFeedEntries; this.genTrainFeedEntries = genTrainFeedEntries; this.batchSize = batchSize; this.discOptimizer = discOptimizer; this.genOptimizer = genOptimizer; this.costIntervalMs = costIntervalMs; this.currentTrainLoopNumBatches = numBatches; this.batchesTrainedThisRun = 0; this.isTraining = true; this.trainStartTimestamp = performance.now(); this.trainNetwork(); } stopTraining() { this.isTraining = false; this.lastStopTimestamp = performance.now(); } resumeTraining() { this.isTraining = true; if (this.lastStopTimestamp != null) { this.totalIdleTimeMs += performance.now() - this.lastStopTimestamp; } this.trainNetwork(); } private trainNetwork() { if (this.batchesTrainedThisRun === this.currentTrainLoopNumBatches) { this.stopTraining(); } if (!this.isTraining) { if (this.eventObserver.doneTrainingCallback != null) { this.eventObserver.doneTrainingCallback(); } return; } const start = performance.now(); const shouldComputeCost = (this.eventObserver.discCostCallback != null || this.eventObserver.genCostCallback != null) && (start - this.lastCostTimestamp > this.costIntervalMs); if (shouldComputeCost) { this.lastCostTimestamp = start; } const costReduction = shouldComputeCost ? CostReduction.MEAN : CostReduction.NONE; this.math.scope((keep, track) => { const discCost = this.session.train( this.discCostTensor, this.discTrainFeedEntries, this.batchSize, this.discOptimizer, costReduction); const genCost = this.session.train( this.genCostTensor, this.genTrainFeedEntries, this.batchSize, this.genOptimizer, costReduction); if (shouldComputeCost) { const trainTime = performance.now() - start; this.eventObserver.discCostCallback(discCost); this.eventObserver.genCostCallback(genCost); if (this.eventObserver.trainExamplesPerSecCallback != null) { const examplesPerSec = (this.batchSize * 1000 / trainTime); this.eventObserver.trainExamplesPerSecCallback(examplesPerSec); } } if (this.eventObserver.totalTimeCallback != null) { this.eventObserver.totalTimeCallback( (start - this.trainStartTimestamp) / 1000); } this.batchesTrainedThisRun++; this.totalBatchesTrained++; if (this.eventObserver.batchesTrainedCallback != null) { this.eventObserver.batchesTrainedCallback(this.totalBatchesTrained); } }); requestAnimationFrame(() => this.trainNetwork()); } infer( genImageTensor: Tensor, discPredictionFakeTensor: Tensor, discPredictionRealTensor: Tensor, inferenceFeedEntries: FeedEntry[], inferenceExampleIntervalMs = DEFAULT_INFERENCE_EXAMPLE_INTERVAL_MS, inferenceExampleCount = 5, numPasses?: number) { if (this.eventObserver.inferenceExamplesCallback == null && this.eventObserver.inferenceExamplesPerSecCallback == null) { throw new Error( 'Cannot start inference loop, no inference example or ' + 'examples/sec observer provided.'); } // Make sure the feed values are providers, and not NDArrays. for (let i = 0; i < inferenceFeedEntries.length; i++) { const feedEntry = inferenceFeedEntries[i]; if (feedEntry.data instanceof NDArray) { throw new Error( 'Cannot start inference on the model runner with feed entries of ' + 'type NDArray. Please use InputProviders.'); } } this.inferenceExampleIntervalMs = inferenceExampleIntervalMs; this.genImageTensor = genImageTensor; this.discPredictionFakeTensor = discPredictionFakeTensor; this.discPredictionRealTensor = discPredictionRealTensor; this.inferenceFeedEntries = inferenceFeedEntries; this.inferenceExampleCount = inferenceExampleCount; this.currentInferenceLoopNumPasses = numPasses; if (!this.isInferring) { this.inferencePassesThisRun = 0; requestAnimationFrame(() => this.inferNetwork()); } this.isInferring = true; } private inferNetwork() { if (!this.isInferring || this.inferencePassesThisRun === this.currentInferenceLoopNumPasses) { return; } this.math.scope((keep, track) => { const feeds: FeedEntry[][] = []; const genImageValues: NDArray[] = []; const discPredictionFakeValues: NDArray[] = []; const discPredictionRealValues: NDArray[] = []; const start = performance.now(); for (let i = 0; i < this.inferenceExampleCount; i++) { // Populate a new FeedEntry[] populated with NDArrays. const ndarrayFeedEntries: FeedEntry[] = []; const ndarrayFeedEntriesCopy: FeedEntry[] = []; for (let j = 0; j < this.inferenceFeedEntries.length; j++) { const feedEntry = this.inferenceFeedEntries[j]; const nextData = track((feedEntry.data as InputProvider).getNextCopy(this.math)); const dataCopy = track((NDArray.like(nextData))); ndarrayFeedEntries.push({ tensor: feedEntry.tensor, data: nextData }); ndarrayFeedEntriesCopy.push({ tensor: feedEntry.tensor, data: dataCopy }); } feeds.push(ndarrayFeedEntries); const evaluatedTensors = this.session.evalAll( [this.genImageTensor, this.discPredictionFakeTensor, this.discPredictionRealTensor], ndarrayFeedEntriesCopy ); genImageValues.push(track(NDArray.like(evaluatedTensors[0]))); discPredictionFakeValues.push(track(NDArray.like(evaluatedTensors[1]))); discPredictionRealValues.push(track(NDArray.like(evaluatedTensors[2]))); } if (this.eventObserver.inferenceExamplesPerSecCallback != null) { // Force a GPU download, since inference results are generally needed on // the CPU and it's more fair to include blocking on the GPU to complete // its work for the inference measurement. const inferenceExamplesPerSecTime = performance.now() - start; const examplesPerSec = (this.inferenceExampleCount * 1000 / inferenceExamplesPerSecTime); this.eventObserver.inferenceExamplesPerSecCallback(examplesPerSec); } if (this.eventObserver.inferenceExamplesCallback != null) { this.eventObserver.inferenceExamplesCallback( feeds, [genImageValues, discPredictionFakeValues, discPredictionRealValues] ); } this.inferencePassesThisRun++; }); this.lastInferTimeoutID = window.setTimeout( () => this.inferNetwork(), this.inferenceExampleIntervalMs); } stopInferring() { this.isInferring = false; window.clearTimeout(this.lastInferTimeoutID); } isInferenceRunning(): boolean { return this.isInferring; } getTotalBatchesTrained(): number { return this.totalBatchesTrained; } getLastComputedMetric(): Scalar { return this.lastComputedMetric; } setMath(math: NDArrayMath) { this.math = math; } setSession(session: Session) { this.session = session; } setInferenceExampleCount(inferenceExampleCount: number) { this.inferenceExampleCount = inferenceExampleCount; } }
the_stack
import Event from '../../event/Event'; import DOMException from '../../exception/DOMException'; import DOMExceptionNameEnum from '../../exception/DOMExceptionNameEnum'; import HTMLElement from '../html-element/HTMLElement'; import IHTMLElement from '../html-element/IHTMLElement'; import IHTMLFormElement from '../html-form-element/IHTMLFormElement'; import HTMLInputElementSelectionDirectionEnum from '../html-input-element/HTMLInputElementSelectionDirectionEnum'; import HTMLInputElementSelectionModeEnum from '../html-input-element/HTMLInputElementSelectionModeEnum'; import IHTMLTextAreaElement from './IHTMLTextAreaElement'; /** * HTML Text Area Element. * * Reference: * https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement. */ export default class HTMLTextAreaElement extends HTMLElement implements IHTMLTextAreaElement { public readonly type = 'textarea'; public _value = null; public _selectionStart = null; public _selectionEnd = null; public _selectionDirection = HTMLInputElementSelectionDirectionEnum.none; public defaultValue = ''; /** * Returns minlength. * * @returns Min length. */ public get minLength(): number { const minLength = this.getAttributeNS(null, 'minlength'); if (minLength !== null) { return parseInt(minLength); } return -1; } /** * Sets minlength. * * @param minLength Min length. */ public set minLength(minlength: number) { this.setAttributeNS(null, 'minlength', String(minlength)); } /** * Returns maxlength. * * @returns Max length. */ public get maxLength(): number { const maxLength = this.getAttributeNS(null, 'maxlength'); if (maxLength !== null) { return parseInt(maxLength); } return -1; } /** * Sets maxlength. * * @param maxlength Max length. */ public set maxLength(maxLength: number) { this.setAttributeNS(null, 'maxlength', String(maxLength)); } /** * Returns name. * * @returns Name. */ public get name(): string { return this.getAttributeNS(null, 'name') || ''; } /** * Sets name. * * @param name Name. */ public set name(name: string) { this.setAttributeNS(null, 'name', name); } /** * Returns placeholder. * * @returns Placeholder. */ public get placeholder(): string { return this.getAttributeNS(null, 'placeholder') || ''; } /** * Sets placeholder. * * @param placeholder Placeholder. */ public set placeholder(placeholder: string) { this.setAttributeNS(null, 'placeholder', placeholder); } /** * Returns inputmode. * * @returns Inputmode. */ public get inputmode(): string { return this.getAttributeNS(null, 'inputmode') || ''; } /** * Sets inputmode. * * @param inputmode Inputmode. */ public set inputmode(inputmode: string) { this.setAttributeNS(null, 'inputmode', inputmode); } /** * Returns cols. * * @returns Cols. */ public get cols(): string { return this.getAttributeNS(null, 'cols') || ''; } /** * Sets cols. * * @param cols Cols. */ public set cols(cols: string) { this.setAttributeNS(null, 'cols', cols); } /** * Returns rows. * * @returns Rows. */ public get rows(): string { return this.getAttributeNS(null, 'rows') || ''; } /** * Sets rows. * * @param rows Rows. */ public set rows(rows: string) { this.setAttributeNS(null, 'rows', rows); } /** * Returns autocomplete. * * @returns Autocomplete. */ public get autocomplete(): string { return this.getAttributeNS(null, 'autocomplete') || ''; } /** * Sets autocomplete. * * @param autocomplete Autocomplete. */ public set autocomplete(autocomplete: string) { this.setAttributeNS(null, 'autocomplete', autocomplete); } /** * Returns readOnly. * * @returns ReadOnly. */ public get readOnly(): boolean { return this.getAttributeNS(null, 'readonly') !== null; } /** * Sets readOnly. * * @param readOnly ReadOnly. */ public set readOnly(readOnly: boolean) { if (!readOnly) { this.removeAttributeNS(null, 'readonly'); } else { this.setAttributeNS(null, 'readonly', ''); } } /** * Returns disabled. * * @returns Disabled. */ public get disabled(): boolean { return this.getAttributeNS(null, 'disabled') !== null; } /** * Sets disabled. * * @param disabled Disabled. */ public set disabled(disabled: boolean) { if (!disabled) { this.removeAttributeNS(null, 'disabled'); } else { this.setAttributeNS(null, 'disabled', ''); } } /** * Returns autofocus. * * @returns Autofocus. */ public get autofocus(): boolean { return this.getAttributeNS(null, 'autofocus') !== null; } /** * Sets autofocus. * * @param autofocus Autofocus. */ public set autofocus(autofocus: boolean) { if (!autofocus) { this.removeAttributeNS(null, 'autofocus'); } else { this.setAttributeNS(null, 'autofocus', ''); } } /** * Returns required. * * @returns Required. */ public get required(): boolean { return this.getAttributeNS(null, 'required') !== null; } /** * Sets required. * * @param required Required. */ public set required(required: boolean) { if (!required) { this.removeAttributeNS(null, 'required'); } else { this.setAttributeNS(null, 'required', ''); } } /** * Returns value. * * @returns Value. */ public get value(): string { if (this._value === null) { return this.getAttributeNS(null, 'value') || ''; } return this._value; } /** * Sets value. * * @param value Value. */ public set value(value: string) { const oldValue = this._value; this._value = value; if (oldValue !== this._value) { this._selectionStart = this._value.length; this._selectionEnd = this._value.length; this._selectionDirection = HTMLInputElementSelectionDirectionEnum.none; } } /** * Returns selection start. * * @returns Selection start. */ public get selectionStart(): number { if (this._selectionStart === null) { return this.value.length; } return this._selectionStart; } /** * Sets selection start. * * @param start Start. */ public set selectionStart(start: number) { this.setSelectionRange(start, Math.max(start, this.selectionEnd), this._selectionDirection); } /** * Returns selection end. * * @returns Selection end. */ public get selectionEnd(): number { if (this._selectionEnd === null) { return this.value.length; } return this._selectionEnd; } /** * Sets selection end. * * @param end End. */ public set selectionEnd(end: number) { this.setSelectionRange(this.selectionStart, end, this._selectionDirection); } /** * Returns selection direction. * * @returns Selection direction. */ public get selectionDirection(): string { return this._selectionDirection; } /** * Sets selection direction. * * @param direction Direction. */ public set selectionDirection(direction: string) { this.setSelectionRange(this._selectionStart, this._selectionEnd, direction); } /** * Returns the parent form element. * * @returns Form. */ public get form(): IHTMLFormElement { let parent = <IHTMLElement>this.parentNode; while (parent && parent.tagName !== 'FORM') { parent = <IHTMLElement>this.parentNode; } return <IHTMLFormElement>parent; } /** * Returns text length. * * @param Text Length. */ public get textLength(): number { return this.value.length; } /** * Set selection range. * * @param start Start. * @param end End. * @param [direction="none"] Direction. */ public setSelectionRange(start: number, end: number, direction = 'none'): void { this._selectionEnd = Math.min(end, this.value.length); this._selectionStart = Math.min(start, this._selectionEnd); this._selectionDirection = direction === HTMLInputElementSelectionDirectionEnum.forward || direction === HTMLInputElementSelectionDirectionEnum.backward ? direction : HTMLInputElementSelectionDirectionEnum.none; this.dispatchEvent(new Event('select', { bubbles: true, cancelable: true })); } /** * Set range text. * * @param replacement Replacement. * @param [start] Start. * @param [end] End. * @param [direction] Direction. * @param selectionMode */ public setRangeText( replacement: string, start: number = null, end: number = null, selectionMode = HTMLInputElementSelectionModeEnum.preserve ): void { if (start === null) { start = this._selectionStart; } if (end === null) { end = this._selectionEnd; } if (start > end) { throw new DOMException( 'The index is not in the allowed range.', DOMExceptionNameEnum.invalidStateError ); } start = Math.min(start, this.value.length); end = Math.min(end, this.value.length); const val = this.value; let selectionStart = this._selectionStart; let selectionEnd = this._selectionEnd; this.value = val.slice(0, start) + replacement + val.slice(end); const newEnd = start + this.value.length; switch (selectionMode) { case HTMLInputElementSelectionModeEnum.select: this.setSelectionRange(start, newEnd); break; case HTMLInputElementSelectionModeEnum.start: this.setSelectionRange(start, start); break; case HTMLInputElementSelectionModeEnum.end: this.setSelectionRange(newEnd, newEnd); break; default: const delta = replacement.length - (end - start); if (selectionStart > end) { selectionStart += delta; } else if (selectionStart > start) { selectionStart = start; } if (selectionEnd > end) { selectionEnd += delta; } else if (selectionEnd > start) { selectionEnd = newEnd; } this.setSelectionRange(selectionStart, selectionEnd); break; } } /** * Checks validity. * * @returns "true" if validation does'nt fail. */ public checkValidity(): boolean { return true; } /** * Clones a node. * * @override * @param [deep=false] "true" to clone deep. * @returns Cloned node. */ public cloneNode(deep = false): IHTMLTextAreaElement { const clone = <HTMLTextAreaElement>super.cloneNode(deep); clone._value = this._value; clone._selectionStart = this._selectionStart; clone._selectionEnd = this._selectionEnd; clone._selectionDirection = this._selectionDirection; clone.defaultValue = this.defaultValue; return clone; } }
the_stack
import { EventEmitter } from 'events' import { applyReducer, Operation } from 'fast-json-patch' import { camelCase, omit } from 'lodash' import { FORMAT_TEXT_MAP, SpanContext, Tracer } from 'opentracing' import { Observable, Subscription, Symbol } from 'rxjs' import { inspect } from 'util' import { ErrorCodes, Message, StreamMessageReader as VSCodeStreamMessageReader, StreamMessageWriter as VSCodeStreamMessageWriter, } from 'vscode-jsonrpc' import { isNotificationMessage, isRequestMessage, isResponseMessage, NotificationMessage, RequestMessage, ResponseMessage, } from 'vscode-jsonrpc/lib/messages' import { Logger, NoopLogger } from './logging' import { InitializeParams, PartialResultParams } from './request-type' import { TypeScriptService } from './typescript-service' /** * Interface for JSON RPC messages with tracing metadata */ export interface HasMeta { meta: { [key: string]: any } } /** * Returns true if the passed argument has a meta field */ function hasMeta(candidate: any): candidate is HasMeta { return ( typeof candidate === 'object' && candidate !== null && typeof candidate.meta === 'object' && candidate.meta !== null ) } /** * Returns true if the passed argument is an object with a `.then()` method */ function isPromiseLike(candidate: any): candidate is PromiseLike<any> { return typeof candidate === 'object' && candidate !== null && typeof candidate.then === 'function' } /** * Returns true if the passed argument is an object with a `[Symbol.observable]` method */ function isObservable(candidate: any): candidate is Observable<any> { return typeof candidate === 'object' && candidate !== null && typeof candidate[Symbol.observable] === 'function' } export interface MessageLogOptions { /** Logger to use */ logger?: Logger /** Whether to log all messages */ logMessages?: boolean } /** * Takes a NodeJS ReadableStream and emits parsed messages received on the stream. * In opposite to StreamMessageReader, supports multiple listeners and is compatible with Observables */ export class MessageEmitter extends EventEmitter { constructor(input: NodeJS.ReadableStream, options: MessageLogOptions = {}) { super() const reader = new VSCodeStreamMessageReader(input) // Forward events reader.listen(msg => { this.emit('message', msg) }) reader.onError(err => { this.emit('error', err) }) reader.onClose(() => { this.emit('close') }) this.setMaxListeners(Infinity) // Register message listener to log messages if configured if (options.logMessages && options.logger) { const logger = options.logger this.on('message', message => { logger.log('-->', message) }) } } /** Emitted when a new JSON RPC message was received on the input stream */ public on(event: 'message', listener: (message: Message) => void): this /** Emitted when the underlying input stream emitted an error */ public on(event: 'error', listener: (error: Error) => void): this /** Emitted when the underlying input stream was closed */ public on(event: 'close', listener: () => void): this /* istanbul ignore next */ public on(event: string, listener: (arg?: any) => void): this { return super.on(event, listener) } /** Emitted when a new JSON RPC message was received on the input stream */ public once(event: 'message', listener: (message: Message) => void): this /** Emitted when the underlying input stream emitted an error */ public once(event: 'error', listener: (error: Error) => void): this /** Emitted when the underlying input stream was closed */ public once(event: 'close', listener: () => void): this /* istanbul ignore next */ public once(event: string, listener: (arg?: any) => void): this { return super.on(event, listener) } } /** * Wraps vscode-jsonrpcs StreamMessageWriter to support logging messages, * decouple our code from the vscode-jsonrpc module and provide a more * consistent event API */ export class MessageWriter { private logger: Logger private logMessages: boolean private vscodeWriter: VSCodeStreamMessageWriter /** * @param output The output stream to write to (e.g. STDOUT or a socket) * @param options */ constructor(output: NodeJS.WritableStream, options: MessageLogOptions = {}) { this.vscodeWriter = new VSCodeStreamMessageWriter(output) this.logger = options.logger || new NoopLogger() this.logMessages = !!options.logMessages } /** * Writes a JSON RPC message to the output stream. * Logs it if configured * * @param message A complete JSON RPC message object */ public write(message: RequestMessage | NotificationMessage | ResponseMessage): void { if (this.logMessages) { this.logger.log('<--', message) } this.vscodeWriter.write(message) } } export interface RegisterLanguageHandlerOptions { logger?: Logger /** An opentracing-compatible tracer */ tracer?: Tracer } /** * Registers all method implementations of a LanguageHandler on a connection * * @param messageEmitter MessageEmitter to listen on * @param messageWriter MessageWriter to write to * @param handler TypeScriptService object that contains methods for all methods to be handled */ export function registerLanguageHandler( messageEmitter: MessageEmitter, messageWriter: MessageWriter, handler: TypeScriptService, options: RegisterLanguageHandlerOptions = {} ): void { const logger = options.logger || new NoopLogger() const tracer = options.tracer || new Tracer() /** Tracks Subscriptions for results to unsubscribe them on $/cancelRequest */ const subscriptions = new Map<string | number, Subscription>() /** * Whether the handler is in an initialized state. * `initialize` sets this to true, `shutdown` to false. * Used to determine whether a manual `shutdown` call is needed on error/close */ let initialized = false /** Whether the client supports streaming with $/partialResult */ let streaming = false messageEmitter.on('message', async message => { // Ignore responses if (isResponseMessage(message)) { return } if (!isRequestMessage(message) && !isNotificationMessage(message)) { logger.error('Received invalid message:', message) return } switch (message.method) { case 'initialize': initialized = true streaming = !!(message.params as InitializeParams).capabilities.streaming break case 'shutdown': initialized = false break case 'exit': // Ignore exit notification, it's not the responsibility of the TypeScriptService to handle it, // but the TCP / STDIO server which needs to close the socket or kill the process for (const subscription of subscriptions.values()) { subscription.unsubscribe() } return case '$/cancelRequest': // Cancel another request by unsubscribing from the Observable const subscription = subscriptions.get(message.params.id) if (!subscription) { logger.warn(`$/cancelRequest for unknown request ID ${message.params.id}`) return } subscription.unsubscribe() subscriptions.delete(message.params.id) messageWriter.write({ jsonrpc: '2.0', id: message.params.id, error: { message: 'Request cancelled', code: ErrorCodes.RequestCancelled, }, }) return } const method = camelCase(message.method) let context: SpanContext | undefined // If message is request and has tracing metadata, extract the span context if (isRequestMessage(message) && hasMeta(message)) { context = tracer.extract(FORMAT_TEXT_MAP, message.meta) || undefined } const span = tracer.startSpan('Handle ' + message.method, { childOf: context }) span.setTag('params', inspect(message.params)) if (typeof (handler as any)[method] !== 'function') { // Method not implemented if (isRequestMessage(message)) { messageWriter.write({ jsonrpc: '2.0', id: message.id, error: { code: ErrorCodes.MethodNotFound, message: `Method ${method} not implemented`, }, }) } else { logger.warn(`Method ${method} not implemented`) } return } // Call handler method with params and span let observable: Observable<Operation> try { // Convert return value to Observable const returnValue = (handler as any)[method](message.params, span) if (isObservable(returnValue)) { observable = returnValue } else if (isPromiseLike(returnValue)) { observable = Observable.from(returnValue) } else { observable = Observable.of(returnValue) } } catch (err) { observable = Observable.throw(err) } if (isRequestMessage(message)) { const subscription = observable .do(patch => { if (streaming) { span.log({ event: 'partialResult', patch }) // Send $/partialResult for partial result patches only if client supports it messageWriter.write({ jsonrpc: '2.0', method: '$/partialResult', params: { id: message.id, patch: [patch], } as PartialResultParams, }) } }) // Build up final result for BC // TODO send null if client declared streaming capability .reduce<Operation, any>(applyReducer, null) .finally(() => { // Finish span span.finish() // Delete subscription from Map // Make sure to not run this before subscription.set() was called // (in case the Observable is synchronous) process.nextTick(() => { subscriptions.delete(message.id) }) }) .subscribe( result => { // Send final result messageWriter.write({ jsonrpc: '2.0', id: message.id, result, }) }, err => { // Set error on span span.setTag('error', true) span.log({ event: 'error', 'error.object': err, message: err.message, stack: err.stack }) // Log error logger.error(`Handler for ${message.method} failed:`, err, '\nMessage:', message) // Send error response messageWriter.write({ jsonrpc: '2.0', id: message.id, error: { message: err.message + '', code: typeof err.code === 'number' ? err.code : ErrorCodes.UnknownErrorCode, data: omit(err, ['message', 'code']), }, }) } ) // Save subscription for $/cancelRequest subscriptions.set(message.id, subscription) } else { // For notifications, still subscribe and log potential error observable.subscribe(undefined, err => { logger.error(`Handle ${method}:`, err) }) } }) // On stream close, shutdown handler if it was initialized messageEmitter.once('close', () => { // Cancel all outstanding requests for (const subscription of subscriptions.values()) { subscription.unsubscribe() } if (initialized) { initialized = false logger.error('Stream was closed without shutdown notification') handler.shutdown() } }) // On stream error, shutdown handler if it was initialized messageEmitter.once('error', err => { // Cancel all outstanding requests for (const subscription of subscriptions.values()) { subscription.unsubscribe() } if (initialized) { initialized = false logger.error('Stream:', err) handler.shutdown() } }) }
the_stack
import { SpreadsheetModel, Spreadsheet, BasicModule } from '../../../src/spreadsheet/index'; import { SpreadsheetHelper } from '../util/spreadsheethelper.spec'; import { defaultData, productData } from '../util/datasource.spec'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { CellModel, getModel, SheetModel, RowModel } from '../../../src/workbook/index'; import { EmitType, setCurrencyCode } from '@syncfusion/ej2-base'; Spreadsheet.Inject(BasicModule); describe('Spreadsheet base module ->', () => { let helper: SpreadsheetHelper; let model: SpreadsheetModel; beforeAll(() => { helper = new SpreadsheetHelper('spreadsheet'); }); describe('Render checking ->', () => { afterEach(() => { helper.invoke('destroy'); }); it('Local data bind testing', (done: Function) => { let dataBound: EmitType<Object> = () => { setTimeout(() => { let sheets: SheetModel[] = helper.getInstance().sheets; expect(sheets.length).toBe(1); expect(sheets[0].rows.length).toBe(11); expect(sheets[0].rows[0].cells.length).toBe(8); done(); }, 30); }; model = { sheets: [{ ranges: [{ dataSource: defaultData }] }], dataBound: dataBound }; helper.initializeSpreadsheet(model); }); it('Cell data bind testing', (done: Function) => { let dataBound: EmitType<Object> = () => { setTimeout(() => { helper.invoke('getData', ['Sheet1!D1']).then((values: Map<string, CellModel>) => { expect(values.get('D1').value).toEqual('10.1'); }); helper.invoke('getData', ['Sheet1!G1']).then((values: Map<string, CellModel>) => { expect(values.get('G1').value.toString()).toBe('30'); expect(values.get('G1').formula).toEqual('=SUM(10,20)'); done(); }); }, 30); }; model = { sheets: [{ rows: [ { index: 0, cells: [ { value: 'JavaScript' }, { value: '10' }, { value: '100' }, { value: '10.1' }, { index: 5, value: 'SUM' }, { formula: '=SUM(10,20)' }, { formula: '=SUM(B1,10)' }, { formula: '=SUM(20,B1)' }, { formula: '=SUM(B1,C1,D1)' }, { formula: '=SUM(B1:B5, 50)' }, { formula: '=SUM(Sheet1!C2, 10)' }, { formula: '=SUM(Sheet2!C1, 10)' }, { formula: '=SUM(Sheet2!C5, 10)' } ] }, { index: 1, cells: [ { value: 'Angular' }, { value: '20' }, { value: '200' }, { value: '20.2' } ] }, { index: 2, cells: [ { value: 'React' }, { value: '30' }, { value: '300' }, { value: '30.3' } ] }, { index: 3, cells: [ { value: 'Vue' }, { value: '40' }, { value: '400' }, { value: '40.4' } ] }, { index: 4, cells: [ { value: 'Asp.Net Core' }, { value: '50' }, { value: '500' }, { value: '50.5' } ] } ], columns: [ { width: 120 } ] }, { rows: [ { index: 0, cells: [ { value: 'JavaScript' }, { value: '10' }, { value: '100' }, { value: '10.1' }, { index: 5, value: 'SUM' }, { formula: '=SUM(10,20)' }, { formula: '=SUM(B1,10)' }, { formula: '=SUM(20,B1)' }, { formula: '=SUM(B1,C1,D1)' }, { formula: '=SUM(B1:B5, 50)' }, { formula: '=SUM(Sheet2!C2, 10)' }, { formula: '=SUM(Sheet1!C1, 10)' }, { formula: '=SUM(Sheet1!C5, 10)' } ] }, { index: 1, cells: [ { value: 'Angular' }, { value: '20' }, { value: '200' }, { value: '20.2' } ] }, { index: 2, cells: [ { value: 'React' }, { value: '30' }, { value: '300' }, { value: '30.3' } ] }, { index: 3, cells: [ { value: 'Vue' }, { value: '40' }, { value: '400' }, { value: '40.4' } ] }, { index: 4, cells: [ { value: 'Asp.Net Core' }, { value: '50' }, { value: '500' }, { value: '50.5' } ] } ], columns: [ { width: 120 } ] }], dataBound: dataBound }; helper.initializeSpreadsheet(model); }); it('Column width testing', (done: Function) => { let dataBound: EmitType<Object> = () => { setTimeout(() => { let td: HTMLTableCellElement = helper.invoke('getCell', [0, 0]); expect(getComputedStyle(td).width).toBe('130px'); td = helper.invoke('getCell', [0, 1]); expect(getComputedStyle(td).width).toBe('92px'); td = helper.invoke('getCell', [0, 2]); expect(getComputedStyle(td).width).toBe('96px'); done(); }, 30); }; model = { sheets: [{ ranges: [{ dataSource: defaultData }], columns: [ { width: 130 }, { width: 92 }, { width: 96 } ] }], dataBound: dataBound }; helper.initializeSpreadsheet(model); }); it('Defined names testing', (done: Function) => { let dataBound: EmitType<Object> = () => { setTimeout(() => { let nameBoxElem: HTMLElement = helper.getElementFromSpreadsheet('.e-name-box .e-ddl-icon'); helper.triggerMouseAction('mousedown', null, nameBoxElem, nameBoxElem); nameBoxElem.click(); setTimeout(() => { helper.click('#spreadsheet_name_box_popup .e-item-focus'); setTimeout(() => { expect(helper.getInstance().sheets[0].selectedRange).toEqual('B1:B1'); done(); }, 20); }, 20); }, 30); }; model = { sheets: [{ ranges: [{ dataSource: defaultData }], columns: [ { width: 130 }, { width: 92 }, { width: 96 } ] }, { ranges: [{ dataSource: defaultData }] } ], definedNames: [ { name: 'value', refersTo: '=Sheet1!B1' }, { name: 'Range', refersTo: '=Sheet1!B1:B5' }, { name: 'Cross_Range', refersTo: '=Sheet2!C5:C10' }, ], dataBound: dataBound }; helper.initializeSpreadsheet(model); }); }); describe('UI interaction checking ->', () => { afterEach(() => { helper.invoke('destroy'); }); it('Column scrolling testing', (done: Function) => { let dataBound: EmitType<Object> = () => { setTimeout(() => { //As of now, checked for code coverage. helper.getContentElement().scroll(1500, 0); setTimeout(() => { helper.getContentElement().scroll(15000, 0); setTimeout(() => { done(); }, 10); }, 10); }, 30); }; model = { sheets: [{ ranges: [{ dataSource: defaultData }] }], dataBound: dataBound }; helper.initializeSpreadsheet(model); }); it('Row scrolling testing', (done: Function) => { let dataBound: EmitType<Object> = () => { setTimeout(() => { //As of now, checked for code coverage. helper.getContentElement().scroll(0, 400); setTimeout(() => { helper.getContentElement().scroll(0, 5000); setTimeout(() => { done(); }, 10); }, 10); }, 30); }; model = { sheets: [{ ranges: [{ dataSource: defaultData }] }], dataBound: dataBound }; helper.initializeSpreadsheet(model); }); // it('Non-virtual mode -> Column scrolling testing', (done: Function) => { // let dataBound: EmitType<Object> = () => { // setTimeout(() => { // //As of now, checked for code coverage. // helper.getContentElement().scroll(1500, 0); // setTimeout(() => { // done(); // }, 10); // }, 30); // }; // model = { // sheets: [{ // ranges: [{ dataSource: defaultData }] // }], // scrollSettings: { // enableVirtualization: false // }, // dataBound: dataBound // }; // helper.initializeSpreadsheet(model); // }); // it('Non-virtual mode -> Row scrolling testing', (done: Function) => { // let dataBound: EmitType<Object> = () => { // setTimeout(() => { // //As of now, checked for code coverage. // helper.getContentElement().scroll(0, 1500); // setTimeout(() => { // done(); // }, 10); // }, 30); // }; // model = { // sheets: [{ // ranges: [{ dataSource: defaultData }] // }], // scrollSettings: { // enableVirtualization: false // }, // dataBound: dataBound // }; // helper.initializeSpreadsheet(model); // }); }); describe('Property checking ->', () => { afterEach(() => { helper.invoke('destroy'); }); it('cssClass testing', (done: Function) => { model = { cssClass: 'e-custom' }; helper.initializeSpreadsheet(model); expect(helper.hasClass('e-custom')).toBeTruthy(); done(); }); }); describe('OnProperty change checking ->', () => { beforeAll((done: Function) => { model = { sheets: [ { ranges: [{ dataSource: defaultData }] }, { ranges: [{ dataSource: productData }] } ] }; helper.initializeSpreadsheet(model, done); }); afterAll(() => { helper.invoke('destroy'); }); it('enableRtl testing', (done: Function) => { expect(helper.hasClass('e-rtl', helper.getSheetPanelElement())).toBeFalsy(); helper.setModel('enableRtl', true); expect(helper.hasClass('e-rtl', helper.getSheetPanelElement())).toBeTruthy(); // helper.setModel('enableRtl', false); // expect(helper.hasClass('e-rtl', helper.getSheetPanelElement())).toBeFalsy(); done(); }); it('cssClass testing', (done: Function) => { helper.setModel('cssClass', 'e-custom e-custom1'); expect(helper.hasClass('e-custom')).toBeTruthy(); expect(helper.hasClass('e-custom1')).toBeTruthy(); helper.setModel('cssClass', ''); expect(helper.hasClass('e-custom')).toBeFalsy(); expect(helper.hasClass('e-custom1')).toBeFalsy(); done(); }); it('activeSheetIndex testing', (done: Function) => { helper.setModel('activeSheetIndex', 1); helper.eventHandler('dataBound', (args: EmitType<Object>) => { setTimeout(() => { if (helper.getModel('activeSheetIndex') === 0) { helper.eventHandler('dataBound', null); done(); } else { expect(helper.getModel('activeSheetIndex')).toBe(1); let td: HTMLTableCellElement = helper.invoke('getCell', [0, 0]); expect(td.textContent).toBe('ProductID'); helper.setModel('activeSheetIndex', 0); } }, 30); }); }); it('width testing', (done: Function) => { helper.setModel('width', 1000); expect(helper.getElement().style.width).toBe('1000px'); done(); }); it('height testing', (done: Function) => { helper.setModel('height', 500); expect(helper.getElement().style.height).toBe('500px'); done(); }); }); describe('Methods checking ->', () => { beforeAll((done: Function) => { model = { sheets: [ { ranges: [{ dataSource: defaultData }] }, {} ] }; helper.initializeSpreadsheet(model, done); }); afterAll(() => { helper.invoke('destroy'); }); it('getCell testing', (done: Function) => { let td: HTMLTableCellElement = helper.invoke('getCell', [10, 10]); expect(helper.hasClass('e-cell', td)).toBeTruthy(); expect(td.getAttribute('aria-colindex')).toEqual('11'); done(); }); it('getRow testing', (done: Function) => { let tr: HTMLTableRowElement = helper.invoke('getRow', [10]); expect(helper.hasClass('e-row', tr)).toBeTruthy(); expect(tr.getAttribute('aria-rowindex')).toEqual('11'); done(); }); //Checked for code coverage. it('resize testing', (done: Function) => { document.body.style.height = '120%'; helper.invoke('resize'); done(); }); it('showSpinner testing', (done: Function) => { let spinnerElem: HTMLElement = helper.getSpinnerElement(); helper.invoke('showSpinner'); expect(helper.hasClass('e-spin-show', spinnerElem)).toBeTruthy(); done(); }); it('hideSpinner testing', (done: Function) => { let spinnerElem: HTMLElement = helper.getSpinnerElement(); helper.invoke('hideSpinner'); expect(helper.hasClass('e-spin-hide', spinnerElem)).toBeTruthy(); done(); }); it('goTo testing', (done: Function) => { // let content: HTMLElement = helper.getContentElement(); // let rhdr: HTMLElement = helper.getRowHeaderElement(); // let chdr: HTMLElement = helper.getColHeaderElement(); helper.invoke('goTo', ['Z100']); setTimeout(() => { // expect(content.querySelector('tr[aria-rowindex="100"]')).toBeDefined(); // expect(helper.getInstance().sheets[0].topLeftCell).toEqual('Z100'); // expect(content.scrollTop).toEqual(1980); // expect(rhdr.scrollTop).toEqual(1980); // expect(content.scrollLeft).toEqual(1600); // expect(chdr.scrollLeft).toEqual(1600); helper.invoke('goTo', ['A1']); // setTimeout(() => { // expect(content.querySelector('tr[aria-rowindex="1"]')).toBeDefined(); // expect(helper.getInstance().sheets[0].topLeftCell).toEqual('A1'); // expect(content.scrollTop).toEqual(0); // expect(rhdr.scrollTop).toEqual(0); // expect(content.scrollLeft).toEqual(0); // expect(chdr.scrollLeft).toEqual(0); // done(); // }); done(); }, 10); }); it('selectRange testing', (done: Function) => { helper.invoke('selectRange', ['D1']); expect(helper.getInstance().sheets[0].selectedRange).toEqual('D1:D1'); done(); }); it('cut testing', (done: Function) => { helper.invoke('cut').then(() => { helper.invoke('selectRange', ['K1']); helper.invoke('paste', ['K1']); helper.invoke('getData', ['Sheet1!K1']).then((values: Map<string, CellModel>) => { expect(values.get('K1').value).toEqual('Quantity'); done(); }); }); }); it('copy testing', (done: Function) => { helper.invoke('copy').then(() => { helper.invoke('selectRange', ['K2']); helper.invoke('paste', ['K2']); helper.invoke('getData', ['Sheet1!K2']).then((values: Map<string, CellModel>) => { expect(values.get('K2').value).toEqual('Quantity'); done(); }); }) }); it('paste testing', (done: Function) => { helper.invoke('selectRange', ['K1']); helper.invoke('copy').then(() => { helper.invoke('selectRange', ['K3']); helper.invoke('paste', ['K3']); helper.invoke('getData', ['Sheet1!K3']).then((values: Map<string, CellModel>) => { expect(values.get('K3').value).toEqual('Quantity'); done(); }); }); }); it('setUsedRange testing', (done: Function) => { helper.invoke('setUsedRange', [11, 12]); expect(helper.getInstance().sheets[0].usedRange.rowIndex).toEqual(11); expect(helper.getInstance().sheets[0].usedRange.colIndex).toEqual(12); done(); }); it('getRowHeaderContent testing', (done: Function) => { expect(helper.invoke('getRowHeaderContent')).not.toBeNull(); done(); }); it('getColumnHeaderContent testing', (done: Function) => { expect(helper.invoke('getColumnHeaderContent')).not.toBeNull(); done(); }); it('getMainContent testing', (done: Function) => { expect(helper.invoke('getMainContent')).not.toBeNull(); done(); }); it('getContentTable testing', (done: Function) => { expect(helper.invoke('getContentTable')).not.toBeNull(); done(); }); it('getRowHeaderTable testing', (done: Function) => { expect(helper.invoke('getRowHeaderTable')).not.toBeNull(); done(); }); it('getColHeaderTable testing', (done: Function) => { expect(helper.invoke('getColHeaderTable')).not.toBeNull(); done(); }); it('isMobileView testing', (done: Function) => { expect(helper.invoke('isMobileView')).toBeFalsy(); done(); }); it('getModuleName testing', (done: Function) => { expect(helper.invoke('getModuleName')).toBe('spreadsheet'); done(); }); it('setRowHeight testing', (done: Function) => { helper.invoke('setRowHeight', [100, 2, 1]); let tr: HTMLTableRowElement = helper.invoke('getRow', [2]); expect(tr.style.height).toBe('100px'); done(); }); it('refreshNode testing', (done: Function) => { let td: HTMLTableCellElement = helper.invoke('getCell', [0, 8]); helper.invoke('refreshNode', [td, { result: 'test' }]); expect(td.textContent).toBe('test'); done(); }); it('startEdit testing', (done: Function) => { helper.invoke('selectRange', ['K3']); helper.invoke('startEdit'); let editorElem: HTMLElement = helper.getElement('.e-spreadsheet-edit'); expect(helper.getInstance().isEdit).toBeTruthy(); setTimeout(() => { expect(editorElem.textContent).toBe('Quantity'); editorElem.textContent = 'Test'; helper.triggerKeyNativeEvent(17); //To update internal props. done(); }, 20); }); it('endEdit testing', (done: Function) => { helper.invoke('endEdit'); expect(helper.getInstance().isEdit).toBeFalsy(); helper.invoke('getData', ['Sheet1!K3']).then((values: Map<string, CellModel>) => { expect(values.get('K3').value).toEqual('Test'); done(); }); }); it('closeEdit testing', (done: Function) => { helper.invoke('startEdit'); let editorElem: HTMLElement = helper.getElement('.e-spreadsheet-edit'); expect(helper.getInstance().isEdit).toBeTruthy(); setTimeout(() => { expect(editorElem.textContent).toBe('Test'); editorElem.textContent = 'Quantity'; helper.triggerKeyNativeEvent(17); //To update internal props. helper.invoke('closeEdit'); expect(helper.getInstance().isEdit).toBeFalsy(); helper.invoke('getData', ['Sheet1!K3']).then((values: Map<string, CellModel>) => { expect(values.get('K3').value).toEqual('Test'); done(); }); }, 20); }); it('clearRange testing', (done: Function) => { helper.invoke('clearRange', ['K3']); helper.invoke('getData', ['Sheet1!K3']).then((values: Map<string, CellModel>) => { expect(values.get('K3').value).toBeUndefined(); done(); }); }); it('getModel testing', () => { let sheets: SheetModel[] = helper.getInstance().sheets; expect(getModel(sheets, 0)).not.toBeNull(); let rows: RowModel[] = helper.getInstance().sheets[0].rows; expect(getModel(rows, 5)).not.toBeNull(); }); it('addDefinedName testing', () => { expect(helper.getInstance().definedNames.length).toBe(0); let result: boolean = helper.invoke('addDefinedName', [{ name: 'TestName', refersTo: 'Sheet1!A1:A10' }]); expect(result).toBeTruthy(); expect(helper.getInstance().definedNames.length).toBe(1); expect(helper.getInstance().definedNames[0].name).toBe('TestName'); }); it('removeDefinedName testing', () => { expect(helper.getInstance().definedNames.length).toBe(1); let result: boolean = helper.invoke('removeDefinedName', ['TestName']); expect(result).toBeTruthy(); expect(helper.getInstance().definedNames.length).toBe(0); }); it('refresh', (done: Function) => { helper.invoke('refresh', []); setTimeout(() => { expect(JSON.stringify(helper.getInstance().sheets[0].rows[0].cells[0])).toBe('{"value":"Item Name"}'); expect(helper.invoke('getCell', [1, 0]).textContent).toBe('Casual Shoes'); done(); }); }); it('setColumnWidth testing', (done: Function) => { helper.invoke('setColWidth', [130, 1]); expect(helper.getInstance().sheets[0].columns[1].width).toBe(130); // expect(getComputedStyle(helper.invoke('getCell', [0, 1])).width).toBe('130px'); // Check this now // expect(getComputedStyle(helper.getColHeaderElement().querySelector('.e-header-row').children[1]).width).toBe('130px'); // Check this it only fails in CI machine helper.invoke('setColWidth', [120, 2, 1]); expect(helper.getInstance().sheets[1].columns[2].width).toBe(120); done(); }); it('updateUndoRedoCollection', (done: Function) => { helper.invoke('getCell', [0, 0]).classList.add('customClass'); helper.invoke('updateUndoRedoCollection', [{ eventArgs: { class: 'customClass', rowIdx: 0, colIdx: 0, action: 'customCSS' } }]); expect(helper.getElementFromSpreadsheet('#' + helper.id + '_undo').parentElement.classList).not.toBe('e-overlay'); helper.getInstance().actionComplete = (args: any) => { expect(args.eventArgs.action).toBe('customCSS'); }; helper.click('#' + helper.id + '_undo'); helper.getInstance().actionComplete = undefined; done(); }); it('addCustomFunction', (done: Function) => { (window as any).CustomFuntion = (num: number) => Math.sqrt(num); helper.invoke('addCustomFunction', ["CustomFuntion", "SQRT"]); helper.edit('J5', '=SQRT(D2)'); expect(helper.invoke('getCell', [4, 9]).textContent).toBe('3.162278'); expect(helper.getInstance().sheets[0].rows[4].cells[9].value).toBe("3.162278"); done(); }); }); describe('OnProperty change checking ->', () => { beforeAll((done: Function) => { model = { sheets: [ { ranges: [{ dataSource: defaultData }] } ] }; helper.initializeSpreadsheet(model, done); }); afterAll(() => { helper.invoke('destroy'); }); it('showRibbon', (done: Function) => { helper.getInstance().showRibbon = false; helper.getInstance().dataBind(); expect(helper.getRibbonElement()).toBeNull(); helper.getInstance().showRibbon = true; helper.getInstance().dataBind(); expect(helper.getRibbonElement()).not.toBeNull(); done(); }); it('showFormulaBar', (done: Function) => { helper.getInstance().showFormulaBar = false; helper.getInstance().dataBind(); expect(helper.getFormulaBarElement()).toBeNull(); helper.getInstance().showFormulaBar = true; helper.getInstance().dataBind(); expect(helper.getFormulaBarElement()).not.toBeNull(); done(); }); it('showSheetTabs', (done: Function) => { helper.getInstance().showSheetTabs = false; helper.getInstance().dataBind(); expect(helper.getElementFromSpreadsheet('.e-sheet-tab-panel')).toBeNull(); helper.getInstance().showSheetTabs = true; helper.getInstance().dataBind(); expect(helper.getElementFromSpreadsheet('.e-sheet-tab-panel')).not.toBeNull(); done(); }); it('cellStyle', (done: Function) => { helper.getInstance().cellStyle = { fontWeight: 'bold', fontSize: '20pt' }; helper.getInstance().dataBind(); setTimeout(() => { expect(helper.invoke('getCell', [0, 0]).style.fontSize).toBe('20pt'); expect(helper.invoke('getCell', [1, 0]).style.fontSize).toBe('20pt'); expect(helper.invoke('getCell', [1, 0]).style.fontWeight).toBe('bold'); helper.getInstance().cellStyle = { fontWeight: 'normal', fontSize: '11pt' }; helper.getInstance().dataBind(); // setTimeout(() => { // This case need to be fixed // expect(helper.invoke('getCell', [0, 0]).style.fontSize).toBe('11pt'); // expect(helper.invoke('getCell', [1, 0]).style.fontSize).toBe('11pt'); // expect(helper.invoke('getCell', [1, 0]).style.fontWeight).toBe('normal'); done(); // }); }); }); it('allowEditing', (done: Function) => { helper.getInstance().allowEditing = false; helper.getInstance().dataBind(); expect(helper.getInstance().editModule).toBeUndefined(); helper.getInstance().allowEditing = true; helper.getInstance().dataBind(); expect(helper.getInstance().editModule).not.toBeUndefined(); done(); }); it('allowInsert', (done: Function) => { helper.getInstance().allowInsert = false; helper.getInstance().dataBind(); expect(helper.getElementFromSpreadsheet('.e-add-sheet-tab').classList).toContain('e-disabled'); helper.getInstance().allowInsert = true; helper.getInstance().dataBind(); expect(helper.getElementFromSpreadsheet('.e-add-sheet-tab').classList).not.toContain('e-disabled'); done(); }); it('locale', (done: Function) => { helper.getInstance().locale = 'en-GB'; helper.getInstance().dataBind(); done(); }); }); // describe('Device Mode Checking ->', () => { // beforeAll(() => { // Browser.userAgent = helper.androidUserAgent; // }); // afterAll(() => { // Browser.userAgent = ''; // }); // afterEach(() => { // helper.invoke('destroy'); // }); // it('Render testing', (done: Function) => { // helper.initializeSpreadsheet(model, done); // expect(helper.hasClass('e-mobile-view')).toBeTruthy(); // }); // it('isMobileView method testing', (done: Function) => { // expect(helper.invoke('isMobileView')).toBeTruthy(); // done(); // }); // }); describe('CR-Issues ->', () => { describe('I266607 ->', () => { beforeEach((done: Function) => { model = { sheets: [{ rows: [{ cells: [{ value: 'columTitle', style: { textAlign: 'left', backgroundColor: '#FFFF33' } }] }], rowCount: 50, colCount: 50 }]}; helper.initializeSpreadsheet(model, done); }); afterEach(() => { helper.invoke('destroy'); }); it('spreedsheet-dataSource-Hidetab (Double time header created while updating the sheet model in the button click)', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.sheets = [{ rows: [{ cells: [{ value: 'columTitle', style: { textAlign: 'left', backgroundColor: '#FFFF33' } }] }], rowCount: 50, colCount: 50 }]; setTimeout((): void => { expect(helper.getElement().querySelectorAll('.e-colhdr-table').length).toBe(1); expect(helper.getElement().querySelectorAll('.e-rowhdr-table').length).toBe(1); done(); }); }); }); describe('I256901 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ rows: [{ cells: [{ value: 'Order ID' }, { value: 'Customer ID' }, { value: 'Employee ID' }, { value: 'Ship Name' }, { value: 'Ship City' }, { value: 'Ship Address' }] }, { cells: [{ value: '10248' }, { value: 'VINET' }, { value: '5' }, { value: 'Vins et alcools Chevalier' }, { value: 'Reims' }, { value: '59 rue de lAbbaye' }] }, { cells: [{ value: '10249' }, { value: 'TOMSP' }, { value: '6' }, { value: 'Toms Spezialitäten' }, { value: 'Münster' }, { value: 'Luisenstr. 48' }] }, { cells: [{ value: '10250' }, { value: 'HANAR' }, { value: '4' }, { value: 'Hanari Carnes' }, { value: 'Rio de Janeiro' }, { value: 'Rua do Paço, 67' }] }] }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Used range not setting properly while using cell data binding', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].usedRange.rowIndex).toBe(3); expect(spreadsheet.sheets[0].usedRange.colIndex).toBe(5); done(); }); }); describe('I316103 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ colCount: 5, rowCount: 10, columns: [ { width: 30 }, { width: 35 }, { width: 40 }, { width: 30 }, { width: 30 } ], rows: [{ cells: [{ value: 'Welcome!' }] }] }], scrollSettings: { enableVirtualization: false, isFinite: true }, }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Need to improve the cell selection with limited column count in virtualization false', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].columns[0].width).toBe(30); expect(helper.invoke('getCell', [0, 0]).getBoundingClientRect().width).toBe(30); expect(spreadsheet.sheets[0].columns[2].width).toBe(40); expect(helper.invoke('getCell', [0, 2]).getBoundingClientRect().width).toBe(40); expect(helper.getElement('#' + helper.id + '_main_content').style.width).toBe('165px'); spreadsheet.sheets[0].rowCount = 100; spreadsheet.sheets[0].colCount = 100; spreadsheet.dataBind(); setTimeout((): void => { expect(helper.getElement('#' + helper.id + '_main_content').style.width).toBe('calc(100% - 30px)'); done(); }); }); }); describe('fb22391 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('getData doesnot work (Pass args in GetData method without sheet name)', (done: Function) => { helper.invoke('getData', ['A1:A2']).then((cells: Map<string, CellModel>): void => { cells.forEach((cell: CellModel, key: string): void => { if (key === 'A1') { expect(cell.value).toBe('Item Name'); } else { expect(cell.value).toBe('Casual Shoes'); } }); done(); }); }); }); describe('I314986 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }], allowInsert: false }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Need to fix the destroy method issue with allowInsert as false (allowInsert property onproperty change checking)', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.allowInsert).toBeFalsy(); const addSheetBtn: HTMLButtonElement = helper.getElement('#' + helper.id + ' .e-add-sheet-tab'); expect(addSheetBtn.disabled).toBeTruthy(); expect(addSheetBtn.classList.contains('e-disabled')).toBeTruthy(); spreadsheet.allowInsert = true; spreadsheet.dataBind(); expect(addSheetBtn.disabled).toBeFalsy(); expect(addSheetBtn.classList.contains('e-disabled')).toBeFalsy(); done(); }); }); describe('I296145 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ rows: [{ cells: [{ value: '987.65' }] }] }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Number value not updated properly with the property binding', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].rows[0].cells[0].value).toBe('987.65'); expect(spreadsheet.sheets[0].rows[0].cells[0].format).toBeUndefined(); helper.getElement('#' + helper.id + '_number_format').click(); helper.getElement('#' + helper.id + '_number_format-popup .e-item:nth-child(2)').click(); expect(spreadsheet.sheets[0].rows[0].cells[0].value).toBe('987.65'); expect(spreadsheet.sheets[0].rows[0].cells[0].format).toBe('0.00'); done(); }); }); describe('I296132, I297067 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet( { sheets: [{ ranges: [{ dataSource: [{ "Customer Name": "* Deluxe Queen Room - General\r\n" }] }] }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Console issue while providing the incorrect Datasource format', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].rows[1].cells[0].value).toBe('* Deluxe Queen Room - General\r\n'); expect(helper.invoke('getCell', [1, 0]).textContent).toBe('* Deluxe Queen Room - General\r\n'); done(); }); }); describe('I288573, I293791 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({}, done); }); afterEach(() => { helper.invoke('destroy'); }); it('String value its display as date format', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.updateCell({value: '(220 - 230)' }, 'B2'); expect(spreadsheet.sheets[0].rows[1].cells[1].value).toBe('(220 - 230)'); expect(spreadsheet.sheets[0].rows[1].cells[1].format).toBeUndefined(); expect(helper.invoke('getCell', [1, 1]).textContent).toBe('(220 - 230)'); done(); }); }); describe('I252011, F152303, F152528, I281279, I284628, I297999 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Dynamic data binding support', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].rows[0].cells[0].value).toBe('Item Name'); spreadsheet.sheets = [{ranges: [{ dataSource: [{ 'Name': 'Sridhar' }], startCell: 'E5' }]}]; spreadsheet.dataBind(); setTimeout((): void => { expect(spreadsheet.sheets[0].rows[4].cells[4].value).toBe('Name'); expect(helper.invoke('getCell', [4, 4]).textContent).toBe('Name'); expect(spreadsheet.sheets[0].rows[5].cells[4].value).toBe('Sridhar'); expect(helper.invoke('getCell', [5, 4]).textContent).toBe('Sridhar'); done(); }, 20); }); }); describe('I312853 ->', () => { let actionBeginCalled: boolean = false; let actionCompleteCalled: boolean = false; beforeEach((done: Function) => { helper.initializeSpreadsheet({ actionBegin: (args: any): void => { if (args.action === 'renameSheet') { actionBeginCalled = true; } }, actionComplete: (args: any): void => { if (args.action === 'renameSheet') { actionCompleteCalled = true; } } }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Trigger actionBegin and actionComplete event for sheet rename action', (done: Function) => { expect(actionBeginCalled).toBeFalsy(); expect(actionCompleteCalled).toBeFalsy(); const item: HTMLElement = helper.getElement('#' + helper.id + ' .e-sheet-tab .e-toolbar-item.e-active'); helper.triggerMouseAction( 'dblclick', { x: item.getBoundingClientRect().left + 1, y: item.getBoundingClientRect().top + 1 }, item.parentElement, item); const renameInput: HTMLInputElement = helper.getElement('#' + helper.id + '_rename_input'); renameInput.value = 'Changed'; helper.triggerMouseAction( 'mousedown', { x: document.body.getBoundingClientRect().left + 1, y: document.body.getBoundingClientRect().top + 1 }, document, document.body); setTimeout((): void => { expect(helper.getInstance().sheets[0].name).toBe('Changed'); expect(actionBeginCalled).toBeTruthy(); expect(actionCompleteCalled).toBeTruthy(); done(); }); }); }); describe('I264109, F162113 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({}, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Error alert when named range given with space', (done: Function) => { helper.invoke('addDefinedName', [{ name: 'demo check', refersTo: 'Sheet1!A1:B5' }]); setTimeout((): void => { const dialog: HTMLElement = helper.getElement('#' + helper.id + ' .e-dialog.e-popup-open'); expect(!!dialog).toBeTruthy(); expect(dialog.querySelector('.e-dlg-content').textContent).toBe('The name that you entered is not valid.'); helper.getInstance().serviceLocator.getService('dialog').hide(); done(); }); }); }); describe('F163837 ->', () => { beforeEach((done: Function) => { setCurrencyCode('EUR'); helper.initializeSpreadsheet({ sheets: [{ rows: [{ cells: [{ value: '7', format: '$#,##0.00' }] }] }] }, done); }); afterEach(() => { helper.invoke('destroy'); setCurrencyCode('USD'); }); it('Speadsheet globalization - setCurrencyCode conflict with component language', (done: Function) => { expect(helper.invoke('getCell', [0, 0]).textContent).toBe('€7.00'); helper.getElement('#' + helper.id + '_number_format').click(); expect(helper.getElement('#' + helper.id + '_Currency .e-numformat-preview-text').textContent).toBe('€7.00'); done(); }); }); describe('fb24579 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ showHeaders: false }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Gridlines disappear when "Hide Headers" option is selected and sheet is scrolled to right', (done: Function) => { expect(helper.getElement('#' + helper.id + '_sheet').classList).toContain('e-hide-headers'); helper.invoke('goTo', ['AA30']); setTimeout((): void => { expect(helper.getInstance().sheets[0].topLeftCell).toBe('AA30'); expect(helper.invoke('getScrollElement').scrollLeft).toBeGreaterThan(0); expect(helper.invoke('getMainContent').scrollLeft).toBeGreaterThan(0); expect(helper.invoke('getCell', [29, 26])).toBeDefined(0); done(); }, 20); }); }); describe('I312024 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet( { sheets: [{ rows: [{ cells: [{ value: '1' }] }, { cells: [{ value: '2' }] }, { cells: [{ value: '3' }] }, { cells: [{ formula: '=SUM(A1:A3)' }] }] }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('sheets property issue in onPropertychange action', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); expect(spreadsheet.sheets.length).toBe(1); spreadsheet.sheets = [{}, {}, {}]; setTimeout((): void => { expect(spreadsheet.sheets.length).toBe(3); expect(spreadsheet.sheets[0].rows.length).toBe(0); expect(helper.getElements('#' + helper.id + ' .e-sheet-tabs-items .e-toolbar-item').length).toBe(3); done(); }, 20); }); }); }); });
the_stack
import { Home_articlesConnection } from "__generated__/Home_articlesConnection.graphql" import { Home_featured } from "__generated__/Home_featured.graphql" import { Home_homePageAbove } from "__generated__/Home_homePageAbove.graphql" import { Home_homePageBelow } from "__generated__/Home_homePageBelow.graphql" import { Home_meAbove } from "__generated__/Home_meAbove.graphql" import { Home_meBelow } from "__generated__/Home_meBelow.graphql" import { Home_showsByFollowedArtists } from "__generated__/Home_showsByFollowedArtists.graphql" import { HomeAboveTheFoldQuery } from "__generated__/HomeAboveTheFoldQuery.graphql" import { HomeBelowTheFoldQuery } from "__generated__/HomeBelowTheFoldQuery.graphql" import { AboveTheFoldFlatList } from "lib/Components/AboveTheFoldFlatList" import { ArtistRailFragmentContainer } from "lib/Components/Home/ArtistRails/ArtistRail" import { RecommendedArtistsRailFragmentContainer } from "lib/Components/Home/ArtistRails/RecommendedArtistsRail" import { LotsByFollowedArtistsRailContainer } from "lib/Components/LotsByArtistsYouFollowRail/LotsByFollowedArtistsRail" import { defaultEnvironment } from "lib/relay/createEnvironment" import { ArtworkRailFragmentContainer } from "lib/Scenes/Home/Components/ArtworkRail" import { AuctionResultsRailFragmentContainer } from "lib/Scenes/Home/Components/AuctionResultsRail" import { CollectionsRailFragmentContainer } from "lib/Scenes/Home/Components/CollectionsRail" import { EmailConfirmationBannerFragmentContainer } from "lib/Scenes/Home/Components/EmailConfirmationBanner" import { FairsRailFragmentContainer } from "lib/Scenes/Home/Components/FairsRail" import { SalesRailFragmentContainer } from "lib/Scenes/Home/Components/SalesRail" import { GlobalStore, useFeatureFlag } from "lib/store/GlobalStore" import { AboveTheFoldQueryRenderer } from "lib/utils/AboveTheFoldQueryRenderer" import { isPad } from "lib/utils/hardware" import { PlaceholderBox, PlaceholderText, ProvidePlaceholderContext, RandomWidthPlaceholderText, useMemoizedRandom, } from "lib/utils/placeholders" import { ProvideScreenTracking, Schema } from "lib/utils/track" import { useTreatment } from "lib/utils/useExperiments" import { compact, times } from "lodash" import { ArtsyLogoIcon, Box, Flex, Join, Spacer } from "palette" import React, { createRef, RefObject, useEffect, useRef, useState } from "react" import { Alert, RefreshControl, View, ViewProps } from "react-native" import { createRefetchContainer, graphql, RelayRefetchProp } from "react-relay" import { articlesDefaultVariables } from "../Articles/Articles" import { lotsByArtistsYouFollowDefaultVariables } from "../LotsByArtistsYouFollow/LotsByArtistsYouFollow" import { ViewingRoomsHomeRail } from "../ViewingRoom/Components/ViewingRoomsHomeRail" import { ArticlesRailFragmentContainer } from "./Components/ArticlesRail" import { HomeHeroContainer } from "./Components/HomeHero" import { NewWorksForYouRailContainer } from "./Components/NewWorksForYouRail" import { ShowsRailFragmentContainer } from "./Components/ShowsRail" import { TroveFragmentContainer } from "./Components/Trove" import { RailScrollRef } from "./Components/types" const MODULE_SEPARATOR_HEIGHT = 6 interface HomeModule { title: string subtitle?: string type: string data: any hidden?: boolean prefetchUrl?: string prefetchVariables?: object } interface Props extends ViewProps { articlesConnection: Home_articlesConnection | null showsByFollowedArtists: Home_showsByFollowedArtists | null featured: Home_featured | null homePageAbove: Home_homePageAbove | null homePageBelow: Home_homePageBelow | null loading: boolean meAbove: Home_meAbove | null meBelow: Home_meBelow | null relay: RelayRefetchProp } const Home = (props: Props) => { const { homePageAbove, homePageBelow, meAbove, meBelow, articlesConnection, showsByFollowedArtists, featured, loading, relay, } = props const enableAuctionResultsByFollowedArtists = useFeatureFlag("ARHomeAuctionResultsByFollowedArtists") const enableViewingRooms = useFeatureFlag("AREnableViewingRooms") const enableTrove = useFeatureFlag("AREnableTrove") const enableNewNewWorksForYouRail = useFeatureFlag("AREnableNewWorksForYou") const enableShowsForYouRail = useFeatureFlag("AREnableShowsRail") const newWorksTreatment = useTreatment("HomeScreenWorksForYouVsWorksByArtistsYouFollow") const artistRecommendationsTreatment = useTreatment("HomeScreenArtistRecommendations") const newWorks = enableNewNewWorksForYouRail && newWorksTreatment === "worksForYou" ? { title: "New Works for You", type: "newWorksForYou", data: meAbove, prefetchUrl: "/new-works-for-you", } : { title: "New Works by Artists You Follow", type: "artwork", data: homePageAbove?.followedArtistsArtworkModule, prefetchUrl: "/works-for-you", } const artistRecommendations = artistRecommendationsTreatment === "newArtistRecommendations" ? { title: "Recommended Artists", type: "recommended-artists", data: meAbove, } : { title: "Recommended Artists", type: "artist", data: homePageAbove?.recommendedArtistsArtistModule, } // Make sure to include enough modules in the above-the-fold query to cover the whole screen!. let modules: HomeModule[] = compact([ // Above-The-Fold Modules newWorks, { title: "Your Active Bids", type: "artwork", data: homePageAbove?.activeBidsArtworkModule }, artistRecommendations, { title: "Auction Lots for You Ending Soon", type: "lotsByFollowedArtists", data: meAbove, prefetchUrl: "/lots-by-artists-you-follow", prefetchVariables: lotsByArtistsYouFollowDefaultVariables(), }, { title: "Auctions", subtitle: "Discover and bid on works for you", type: "sales", data: homePageAbove?.salesModule, prefetchUrl: "/auctions", }, // Below-The-Fold Modules { title: "Auction Results for Artists You Follow", type: "auction-results", data: meBelow, hidden: !enableAuctionResultsByFollowedArtists, prefetchUrl: "/auction-results-for-artists-you-follow", }, { title: "Market News", type: "articles", data: articlesConnection, hidden: !articlesConnection, prefetchUrl: "/articles", prefetchVariables: articlesDefaultVariables, }, { title: "Shows for You", type: "shows", data: showsByFollowedArtists, hidden: !enableShowsForYouRail, }, { title: "Trove", type: "trove", data: homePageBelow, hidden: !enableTrove }, { title: "Viewing Rooms", type: "viewing-rooms", data: featured, hidden: !enableViewingRooms, prefetchUrl: "/viewing-rooms", }, { title: "Collections", subtitle: "The newest works curated by Artsy", type: "collections", data: homePageBelow?.marketingCollectionsModule, }, { title: "Featured Fairs", subtitle: "See works in top art fairs", type: "fairs", data: homePageBelow?.fairsModule, }, { title: "Popular Artists", type: "artist", data: homePageBelow?.popularArtistsArtistModule }, { title: "Recently Viewed", type: "artwork", data: homePageBelow?.recentlyViewedWorksArtworkModule }, { title: "Similar to Works You've Viewed", type: "artwork", data: homePageBelow?.similarToRecentlyViewedArtworkModule, }, ]) modules = modules.filter((module) => !module.hidden && module.data) const { isRefreshing, handleRefresh, scrollRefs } = useHandleRefresh(relay, modules) return ( <ProvideScreenTracking info={{ context_screen: Schema.PageNames.Home, context_screen_owner_type: null as any, }} > <View style={{ flex: 1 }}> <AboveTheFoldFlatList<HomeModule> data={modules} initialNumToRender={5} refreshControl={<RefreshControl refreshing={isRefreshing} onRefresh={handleRefresh} />} prefetchUrlExtractor={(item) => item?.prefetchUrl} prefetchVariablesExtractor={(item) => item?.prefetchVariables} renderItem={({ item, index }) => { if (!item.data) { return <></> } switch (item.type) { case "articles": return ( <ArticlesRailFragmentContainer title={item.title} articlesConnection={item.data} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "artist": return ( <ArtistRailFragmentContainer title={item.title} rail={item.data} scrollRef={scrollRefs.current[index]} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "artwork": return ( <ArtworkRailFragmentContainer title={item.title} rail={item.data || null} scrollRef={scrollRefs.current[index]} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "auction-results": return ( <AuctionResultsRailFragmentContainer title={item.title} me={item.data} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "collections": return ( <CollectionsRailFragmentContainer title={item.title} collectionsModule={item.data} scrollRef={scrollRefs.current[index]} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "fairs": return ( <FairsRailFragmentContainer title={item.title} subtitle={item.subtitle} fairsModule={item.data} scrollRef={scrollRefs.current[index]} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "lotsByFollowedArtists": return ( <LotsByFollowedArtistsRailContainer title={item.title} me={item.data} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "newWorksForYou": return ( <NewWorksForYouRailContainer title={item.title} me={item.data} scrollRef={scrollRefs.current[index]} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "recommended-artists": return ( <RecommendedArtistsRailFragmentContainer title={item.title} me={item.data} scrollRef={scrollRefs.current[index]} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "sales": return ( <SalesRailFragmentContainer title={item.title} salesModule={item.data} scrollRef={scrollRefs.current[index]} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "shows": return ( <ShowsRailFragmentContainer title={item.title} showsConnection={item.data} mb={MODULE_SEPARATOR_HEIGHT} /> ) case "trove": return <TroveFragmentContainer trove={item.data} mb={MODULE_SEPARATOR_HEIGHT} /> case "viewing-rooms": return <ViewingRoomsHomeRail title={item.title} featured={item.data} mb={MODULE_SEPARATOR_HEIGHT} /> default: return null } }} ListHeaderComponent={HomeHeader} ListFooterComponent={() => <Flex mb={3}>{!!loading && <BelowTheFoldPlaceholder />}</Flex>} keyExtractor={(_item, index) => String(index)} /> {!!meAbove && <EmailConfirmationBannerFragmentContainer me={meAbove} />} </View> </ProvideScreenTracking> ) } const HomeHeader: React.FC<{ homePageAbove: Home_homePageAbove | null }> = ({ homePageAbove }) => { return ( <Box mb={1} mt={2}> <Flex alignItems="center"> <ArtsyLogoIcon scale={0.75} /> </Flex> <Spacer mb="15px" /> {!!homePageAbove && <HomeHeroContainer homePage={homePageAbove} />} <Spacer mb="2" /> </Box> ) } const useHandleRefresh = (relay: RelayRefetchProp, modules: any[]) => { const scrollRefs = useRef<Array<RefObject<RailScrollRef>>>(modules.map((_) => createRef())) const scrollRailsToTop = () => scrollRefs.current.forEach((r) => r.current?.scrollToTop()) const [isRefreshing, setIsRefreshing] = useState(false) const handleRefresh = async () => { setIsRefreshing(true) relay.refetch( { heroImageVersion: isPad() ? "WIDE" : "NARROW" }, {}, (error) => { if (error) { console.error("Home.tsx - Error refreshing ForYou rails:", error.message) } setIsRefreshing(false) scrollRailsToTop() }, { force: true } ) } return { scrollRefs, isRefreshing, handleRefresh } } export const HomeFragmentContainer = createRefetchContainer( Home, { // Make sure not to include modules that are part of "homePageBelow" homePageAbove: graphql` fragment Home_homePageAbove on HomePage @argumentDefinitions(heroImageVersion: { type: "HomePageHeroUnitImageVersion" }) { followedArtistsArtworkModule: artworkModule(key: FOLLOWED_ARTISTS) { id ...ArtworkRail_rail } activeBidsArtworkModule: artworkModule(key: ACTIVE_BIDS) { id ...ArtworkRail_rail } salesModule { ...SalesRail_salesModule } recommendedArtistsArtistModule: artistModule(key: SUGGESTED) { id ...ArtistRail_rail } ...HomeHero_homePage @arguments(heroImageVersion: $heroImageVersion) } `, // Make sure to exclude all modules that are part of "homePageAbove" homePageBelow: graphql` fragment Home_homePageBelow on HomePage @argumentDefinitions(heroImageVersion: { type: "HomePageHeroUnitImageVersion" }) { recentlyViewedWorksArtworkModule: artworkModule(key: RECENTLY_VIEWED_WORKS) { id ...ArtworkRail_rail } similarToRecentlyViewedArtworkModule: artworkModule(key: SIMILAR_TO_RECENTLY_VIEWED) { id ...ArtworkRail_rail } popularArtistsArtistModule: artistModule(key: POPULAR) { id ...ArtistRail_rail } fairsModule { ...FairsRail_fairsModule } marketingCollectionsModule { ...CollectionsRail_collectionsModule } ...HomeHero_homePage @arguments(heroImageVersion: $heroImageVersion) ...Trove_trove @arguments(heroImageVersion: $heroImageVersion) } `, meAbove: graphql` fragment Home_meAbove on Me { ...EmailConfirmationBanner_me ...LotsByFollowedArtistsRail_me ...NewWorksForYouRail_me ...RecommendedArtistsRail_me } `, meBelow: graphql` fragment Home_meBelow on Me { ...AuctionResultsRail_me } `, articlesConnection: graphql` fragment Home_articlesConnection on ArticleConnection { ...ArticlesRail_articlesConnection } `, showsByFollowedArtists: graphql` fragment Home_showsByFollowedArtists on ShowConnection { ...ShowsRail_showsConnection } `, featured: graphql` fragment Home_featured on ViewingRoomConnection { ...ViewingRoomsListFeatured_featured } `, }, graphql` query HomeRefetchQuery($heroImageVersion: HomePageHeroUnitImageVersion!) { homePage @optionalField { ...Home_homePageAbove @arguments(heroImageVersion: $heroImageVersion) } homePageBelow: homePage @optionalField { ...Home_homePageBelow @arguments(heroImageVersion: $heroImageVersion) } me @optionalField { ...Home_meAbove ...AuctionResultsRail_me ...RecommendedArtistsRail_me ...NewWorksForYouRail_me showsByFollowedArtists(first: 10, status: RUNNING_AND_UPCOMING) @optionalField { ...Home_showsByFollowedArtists } } meBelow: me @optionalField { ...Home_meBelow } featured: viewingRooms(featured: true) @optionalField { ...Home_featured } articlesConnection(first: 10, sort: PUBLISHED_AT_DESC, inEditorialFeed: true) @optionalField { ...Home_articlesConnection } } ` ) const ModuleSeparator = () => <Spacer mb={MODULE_SEPARATOR_HEIGHT} /> const BelowTheFoldPlaceholder: React.FC = () => { const enableViewingRooms = useFeatureFlag("AREnableViewingRooms") return ( <ProvidePlaceholderContext> <Flex> {!!enableViewingRooms && ( <Flex ml="2" mt="3"> <RandomWidthPlaceholderText minWidth={100} maxWidth={200} marginBottom={20} /> <Flex flexDirection="row"> {times(4).map((i) => ( <PlaceholderBox key={i} width={280} height={370} marginRight={15} /> ))} </Flex> </Flex> )} {times(2).map((r) => ( <Box key={r}> <ModuleSeparator /> <Box ml={2} mr={2}> <RandomWidthPlaceholderText minWidth={100} maxWidth={200} /> <Flex flexDirection="row"> <Join separator={<Spacer width={15} />}> {times(10).map((index) => ( <PlaceholderBox key={index} height={270} width={270} /> ))} </Join> <Spacer mb={2} /> </Flex> </Box> </Box> ))} </Flex> </ProvidePlaceholderContext> ) } const HomePlaceholder: React.FC<{}> = () => { const enableViewingRooms = useFeatureFlag("AREnableViewingRooms") return ( <Flex> <Box mb={1} mt={2}> <Flex alignItems="center"> <ArtsyLogoIcon scale={0.75} /> </Flex> </Box> <Spacer mb={4} /> { // Small tiles to mimic the artwork rails times(2).map((r) => ( <Box key={r} ml={2} mr={2}> <RandomWidthPlaceholderText minWidth={100} maxWidth={200} /> <Flex flexDirection="row" mt={1}> <Join separator={<Spacer width={15} />}> {times(3 + useMemoizedRandom() * 10).map((index) => ( <Flex key={index}> <PlaceholderBox height={120} width={120} /> <Spacer mb={2} /> <PlaceholderText width={120} /> <RandomWidthPlaceholderText minWidth={30} maxWidth={90} /> <ModuleSeparator /> </Flex> ))} </Join> </Flex> </Box> )) } {/* Larger tiles to mimic the fairs, sales, and collections rails */} <Box ml={2} mr={2}> <RandomWidthPlaceholderText minWidth={100} maxWidth={200} /> <Flex flexDirection="row" mt={1}> <Join separator={<Spacer width={15} />}> {times(10).map((index) => ( <PlaceholderBox key={index} height={270} width={270} /> ))} </Join> <ModuleSeparator /> </Flex> </Box> {!!enableViewingRooms && ( <Flex ml="2" mt="3"> <RandomWidthPlaceholderText minWidth={100} maxWidth={200} marginBottom={20} /> <Flex flexDirection="row"> {times(4).map((i) => ( <PlaceholderBox key={i} width={280} height={370} marginRight={15} /> ))} </Flex> </Flex> )} </Flex> ) } const messages = { confirmed: { title: "Email Confirmed", message: "Your email has been confirmed.", }, already_confirmed: { title: "Already Confirmed", message: "You have already confirmed your email.", }, invalid_token: { title: "Error", message: "An error has occurred. Please contact supportartsy.net.", }, blank_token: { title: "Error", message: "An error has occurred. Please contact supportartsy.net.", }, expired_token: { title: "Link Expired", message: "Link expired. Please request a new verification email below.", }, } export const HomeQueryRenderer: React.FC = () => { const { flash_message } = GlobalStore.useAppState((state) => state.bottomTabs.sessionState.tabProps.home ?? {}) as { flash_message?: string } useEffect(() => { if (flash_message) { const message = messages[flash_message as keyof typeof messages] if (!message) { console.error(`Invalid flash_message type ${JSON.stringify(flash_message)}`) return } Alert.alert(message.title, message.message, [{ text: "Ok" }]) // reset the tab props because we don't want this message to show again // if the home screen remounts for whatever reason. GlobalStore.actions.bottomTabs.setTabProps({ tab: "home", props: {} }) } }, [flash_message]) return ( <AboveTheFoldQueryRenderer<HomeAboveTheFoldQuery, HomeBelowTheFoldQuery> environment={defaultEnvironment} above={{ query: graphql` query HomeAboveTheFoldQuery($heroImageVersion: HomePageHeroUnitImageVersion) { homePage @optionalField { ...Home_homePageAbove @arguments(heroImageVersion: $heroImageVersion) } me @optionalField { ...Home_meAbove ...NewWorksForYouRail_me } articlesConnection(first: 10, sort: PUBLISHED_AT_DESC, inEditorialFeed: true) @optionalField { ...Home_articlesConnection } } `, variables: { heroImageVersion: isPad() ? "WIDE" : "NARROW" }, }} below={{ query: graphql` query HomeBelowTheFoldQuery($heroImageVersion: HomePageHeroUnitImageVersion) { homePage @optionalField { ...Home_homePageBelow @arguments(heroImageVersion: $heroImageVersion) } featured: viewingRooms(featured: true) @optionalField { ...Home_featured } me @optionalField { ...Home_meBelow ...RecommendedArtistsRail_me ...AuctionResultsRail_me showsByFollowedArtists(first: 10, status: RUNNING_AND_UPCOMING) @optionalField { ...Home_showsByFollowedArtists } } } `, variables: { heroImageVersion: isPad() ? "WIDE" : "NARROW" }, }} render={{ renderComponent: ({ above, below }) => { if (!above) { throw new Error("no data") } return ( <HomeFragmentContainer articlesConnection={above?.articlesConnection ?? null} showsByFollowedArtists={below?.me?.showsByFollowedArtists ?? null} featured={below ? below.featured : null} homePageAbove={above.homePage} homePageBelow={below ? below.homePage : null} meAbove={above.me} meBelow={below ? below.me : null} loading={!below} /> ) }, renderPlaceholder: () => <HomePlaceholder />, }} cacheConfig={{ force: true }} belowTheFoldTimeout={100} /> ) }
the_stack
import { GlobalProps } from 'ojs/ojvcomponent'; import { ComponentChildren } from 'preact'; import { IntlDateTimeConverter, DateTimeConverter } from '../ojconverter-datetime'; import ColorConverter = require('../ojconverter-color'); import { IntlNumberConverter, NumberConverter } from '../ojconverter-number'; import RequiredValidator = require('../ojvalidator-required'); import RegExpValidator = require('../ojvalidator-regexp'); import NumberRangeValidator = require('../ojvalidator-numberrange'); import LengthValidator = require('../ojvalidator-length'); import DateTimeRangeValidator = require('../ojvalidator-datetimerange'); import DateRestrictionValidator = require('../ojvalidator-daterestriction'); import AsyncValidator = require('../ojvalidator-async'); import Validator = require('../ojvalidator'); import Converter = require('../ojconverter'); import { Validation } from '../ojvalidationfactory-base'; import { editableValue, editableValueEventMap, editableValueSettableProperties } from '../ojeditablevalue'; import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface inputBase<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> extends editableValue<V, SP, SV, RV> { asyncValidators: Array<AsyncValidator<V>>; autocomplete: 'on' | 'off' | string; autofocus: boolean; displayOptions?: { converterHint?: 'display' | 'none'; helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages?: 'display' | 'none'; validatorHint?: 'display' | 'none'; }; labelledBy: string | null; placeholder: string; readonly rawValue: RV; readonly: boolean; required: boolean; validators: Array<Validator<V> | AsyncValidator<V>> | null; translations: { accessibleMaxLengthExceeded?: string; accessibleMaxLengthRemaining?: string; regexp?: { messageDetail?: string; messageSummary?: string; }; required?: { hint?: string; messageDetail?: string; messageSummary?: string; }; }; addEventListener<T extends keyof inputBaseEventMap<V, SP, SV, RV>>(type: T, listener: (this: HTMLElement, ev: inputBaseEventMap<V, SP, SV, RV>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof inputBaseSettableProperties<V, SV, RV>>(property: T): inputBase<V, SP, SV, RV>[T]; getProperty(property: string): any; setProperty<T extends keyof inputBaseSettableProperties<V, SV, RV>>(property: T, value: inputBaseSettableProperties<V, SV, RV>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, inputBaseSettableProperties<V, SV, RV>>): void; setProperties(properties: inputBaseSettablePropertiesLenient<V, SV, RV>): void; refresh(): void; validate(): Promise<'valid' | 'invalid'>; } export namespace inputBase { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type asyncValidatorsChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = JetElementCustomEvent<inputBase<V, SP, SV, RV>["asyncValidators"]>; // tslint:disable-next-line interface-over-type-literal type autocompleteChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = JetElementCustomEvent<inputBase<V, SP, SV, RV>["autocomplete"]>; // tslint:disable-next-line interface-over-type-literal type autofocusChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = JetElementCustomEvent<inputBase<V, SP, SV, RV>["autofocus"]>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = JetElementCustomEvent<inputBase<V, SP, SV, RV>["displayOptions"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = JetElementCustomEvent<inputBase<V, SP, SV, RV>["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = JetElementCustomEvent<inputBase<V, SP, SV, RV>["placeholder"]>; // tslint:disable-next-line interface-over-type-literal type rawValueChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = JetElementCustomEvent<inputBase<V, SP, SV, RV>["rawValue"]>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = JetElementCustomEvent<inputBase<V, SP, SV, RV>["readonly"]>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = JetElementCustomEvent<inputBase<V, SP, SV, RV>["required"]>; // tslint:disable-next-line interface-over-type-literal type validatorsChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = JetElementCustomEvent<inputBase<V, SP, SV, RV>["validators"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type describedByChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = editableValue.describedByChanged<V, SP, SV, RV>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = editableValue.disabledChanged<V, SP, SV, RV>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = editableValue.helpChanged<V, SP, SV, RV>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = editableValue.helpHintsChanged<V, SP, SV, RV>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = editableValue.labelEdgeChanged<V, SP, SV, RV>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = editableValue.labelHintChanged<V, SP, SV, RV>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = editableValue.messagesCustomChanged<V, SP, SV, RV>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = editableValue.userAssistanceDensityChanged<V, SP, SV, RV>; // tslint:disable-next-line interface-over-type-literal type validChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = editableValue.validChanged<V, SP, SV, RV>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> = editableValue.valueChanged<V, SP, SV, RV>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface inputBaseEventMap<V, SP extends inputBaseSettableProperties<V, SV>, SV = V, RV = V> extends editableValueEventMap<V, SP, SV, RV> { 'ojAnimateEnd': inputBase.ojAnimateEnd; 'ojAnimateStart': inputBase.ojAnimateStart; 'asyncValidatorsChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["asyncValidators"]>; 'autocompleteChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["autocomplete"]>; 'autofocusChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["autofocus"]>; 'displayOptionsChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["displayOptions"]>; 'labelledByChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["labelledBy"]>; 'placeholderChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["placeholder"]>; 'rawValueChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["rawValue"]>; 'readonlyChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["readonly"]>; 'requiredChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["required"]>; 'validatorsChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["validators"]>; 'describedByChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["describedBy"]>; 'disabledChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["disabled"]>; 'helpChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["help"]>; 'helpHintsChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["helpHints"]>; 'labelEdgeChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["labelEdge"]>; 'labelHintChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["labelHint"]>; 'messagesCustomChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["messagesCustom"]>; 'userAssistanceDensityChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["userAssistanceDensity"]>; 'validChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["valid"]>; 'valueChanged': JetElementCustomEvent<inputBase<V, SP, SV, RV>["value"]>; } export interface inputBaseSettableProperties<V, SV = V, RV = V> extends editableValueSettableProperties<V, SV, RV> { asyncValidators: Array<AsyncValidator<V>>; autocomplete: 'on' | 'off' | string; autofocus: boolean; displayOptions?: { converterHint?: 'display' | 'none'; helpInstruction?: Array<'notewindow' | 'none'> | 'notewindow' | 'none'; messages?: 'display' | 'none'; validatorHint?: 'display' | 'none'; }; labelledBy: string | null; placeholder: string; readonly rawValue: RV; readonly: boolean; required: boolean; validators: Array<Validator<V> | AsyncValidator<V>> | null; translations: { accessibleMaxLengthExceeded?: string; accessibleMaxLengthRemaining?: string; regexp?: { messageDetail?: string; messageSummary?: string; }; required?: { hint?: string; messageDetail?: string; messageSummary?: string; }; }; } export interface inputBaseSettablePropertiesLenient<V, SV = V, RV = V> extends Partial<inputBaseSettableProperties<V, SV, RV>> { [key: string]: any; } export interface ojInputPassword<V = string> extends inputBase<V, ojInputPasswordSettableProperties<V>> { maskIcon: 'hidden' | 'visible'; value: V | null; translations: { accessibleHidePassword?: string; accessibleMaxLengthExceeded?: string; accessibleMaxLengthRemaining?: string; accessibleShowPassword?: string; regexp?: { messageDetail?: string; messageSummary?: string; }; required?: { hint?: string; messageDetail?: string; messageSummary?: string; }; }; addEventListener<T extends keyof ojInputPasswordEventMap<V>>(type: T, listener: (this: HTMLElement, ev: ojInputPasswordEventMap<V>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojInputPasswordSettableProperties<V>>(property: T): ojInputPassword<V>[T]; getProperty(property: string): any; setProperty<T extends keyof ojInputPasswordSettableProperties<V>>(property: T, value: ojInputPasswordSettableProperties<V>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojInputPasswordSettableProperties<V>>): void; setProperties(properties: ojInputPasswordSettablePropertiesLenient<V>): void; } export namespace ojInputPassword { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type maskIconChanged<V = string> = JetElementCustomEvent<ojInputPassword<V>["maskIcon"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V = string> = JetElementCustomEvent<ojInputPassword<V>["value"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type asyncValidatorsChanged<V = string> = inputBase.asyncValidatorsChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autocompleteChanged<V = string> = inputBase.autocompleteChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autofocusChanged<V = string> = inputBase.autofocusChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type describedByChanged<V = string> = inputBase.describedByChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V = string> = inputBase.disabledChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged<V = string> = inputBase.displayOptionsChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V = string> = inputBase.helpChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V = string> = inputBase.helpHintsChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V = string> = inputBase.labelEdgeChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V = string> = inputBase.labelHintChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V = string> = inputBase.labelledByChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V = string> = inputBase.messagesCustomChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V = string> = inputBase.placeholderChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type rawValueChanged<V = string> = inputBase.rawValueChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V = string> = inputBase.readonlyChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V = string> = inputBase.requiredChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V = string> = inputBase.userAssistanceDensityChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validChanged<V = string> = inputBase.validChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validatorsChanged<V = string> = inputBase.validatorsChanged<V, ojInputPasswordSettableProperties<V>>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ojInputPasswordEventMap<V = string> extends inputBaseEventMap<V, ojInputPasswordSettableProperties<V>> { 'ojAnimateEnd': ojInputPassword.ojAnimateEnd; 'ojAnimateStart': ojInputPassword.ojAnimateStart; 'maskIconChanged': JetElementCustomEvent<ojInputPassword<V>["maskIcon"]>; 'valueChanged': JetElementCustomEvent<ojInputPassword<V>["value"]>; 'asyncValidatorsChanged': JetElementCustomEvent<ojInputPassword<V>["asyncValidators"]>; 'autocompleteChanged': JetElementCustomEvent<ojInputPassword<V>["autocomplete"]>; 'autofocusChanged': JetElementCustomEvent<ojInputPassword<V>["autofocus"]>; 'describedByChanged': JetElementCustomEvent<ojInputPassword<V>["describedBy"]>; 'disabledChanged': JetElementCustomEvent<ojInputPassword<V>["disabled"]>; 'displayOptionsChanged': JetElementCustomEvent<ojInputPassword<V>["displayOptions"]>; 'helpChanged': JetElementCustomEvent<ojInputPassword<V>["help"]>; 'helpHintsChanged': JetElementCustomEvent<ojInputPassword<V>["helpHints"]>; 'labelEdgeChanged': JetElementCustomEvent<ojInputPassword<V>["labelEdge"]>; 'labelHintChanged': JetElementCustomEvent<ojInputPassword<V>["labelHint"]>; 'labelledByChanged': JetElementCustomEvent<ojInputPassword<V>["labelledBy"]>; 'messagesCustomChanged': JetElementCustomEvent<ojInputPassword<V>["messagesCustom"]>; 'placeholderChanged': JetElementCustomEvent<ojInputPassword<V>["placeholder"]>; 'rawValueChanged': JetElementCustomEvent<ojInputPassword<V>["rawValue"]>; 'readonlyChanged': JetElementCustomEvent<ojInputPassword<V>["readonly"]>; 'requiredChanged': JetElementCustomEvent<ojInputPassword<V>["required"]>; 'userAssistanceDensityChanged': JetElementCustomEvent<ojInputPassword<V>["userAssistanceDensity"]>; 'validChanged': JetElementCustomEvent<ojInputPassword<V>["valid"]>; 'validatorsChanged': JetElementCustomEvent<ojInputPassword<V>["validators"]>; } export interface ojInputPasswordSettableProperties<V = string> extends inputBaseSettableProperties<V> { maskIcon: 'hidden' | 'visible'; value: V | null; translations: { accessibleHidePassword?: string; accessibleMaxLengthExceeded?: string; accessibleMaxLengthRemaining?: string; accessibleShowPassword?: string; regexp?: { messageDetail?: string; messageSummary?: string; }; required?: { hint?: string; messageDetail?: string; messageSummary?: string; }; }; } export interface ojInputPasswordSettablePropertiesLenient<V = string> extends Partial<ojInputPasswordSettableProperties<V>> { [key: string]: any; } export interface ojInputText<V = any> extends inputBase<V, ojInputTextSettableProperties<V>> { clearIcon: 'never' | 'always' | 'conditional'; converter: Promise<Converter<V>> | Converter<V> | null; length: { countBy?: 'codePoint' | 'codeUnit'; max: number | null; }; list: string; virtualKeyboard: 'auto' | 'email' | 'number' | 'search' | 'tel' | 'text' | 'url'; addEventListener<T extends keyof ojInputTextEventMap<V>>(type: T, listener: (this: HTMLElement, ev: ojInputTextEventMap<V>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojInputTextSettableProperties<V>>(property: T): ojInputText<V>[T]; getProperty(property: string): any; setProperty<T extends keyof ojInputTextSettableProperties<V>>(property: T, value: ojInputTextSettableProperties<V>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojInputTextSettableProperties<V>>): void; setProperties(properties: ojInputTextSettablePropertiesLenient<V>): void; } export namespace ojInputText { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type clearIconChanged<V = any> = JetElementCustomEvent<ojInputText<V>["clearIcon"]>; // tslint:disable-next-line interface-over-type-literal type converterChanged<V = any> = JetElementCustomEvent<ojInputText<V>["converter"]>; // tslint:disable-next-line interface-over-type-literal type lengthChanged<V = any> = JetElementCustomEvent<ojInputText<V>["length"]>; // tslint:disable-next-line interface-over-type-literal type listChanged<V = any> = JetElementCustomEvent<ojInputText<V>["list"]>; // tslint:disable-next-line interface-over-type-literal type virtualKeyboardChanged<V = any> = JetElementCustomEvent<ojInputText<V>["virtualKeyboard"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type asyncValidatorsChanged<V = any> = inputBase.asyncValidatorsChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autocompleteChanged<V = any> = inputBase.autocompleteChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autofocusChanged<V = any> = inputBase.autofocusChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type describedByChanged<V = any> = inputBase.describedByChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V = any> = inputBase.disabledChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged<V = any> = inputBase.displayOptionsChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V = any> = inputBase.helpChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V = any> = inputBase.helpHintsChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V = any> = inputBase.labelEdgeChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V = any> = inputBase.labelHintChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V = any> = inputBase.labelledByChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V = any> = inputBase.messagesCustomChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V = any> = inputBase.placeholderChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type rawValueChanged<V = any> = inputBase.rawValueChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V = any> = inputBase.readonlyChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V = any> = inputBase.requiredChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V = any> = inputBase.userAssistanceDensityChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validChanged<V = any> = inputBase.validChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validatorsChanged<V = any> = inputBase.validatorsChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V = any> = inputBase.valueChanged<V, ojInputTextSettableProperties<V>>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ojInputTextEventMap<V = any> extends inputBaseEventMap<V, ojInputTextSettableProperties<V>> { 'ojAnimateEnd': ojInputText.ojAnimateEnd; 'ojAnimateStart': ojInputText.ojAnimateStart; 'clearIconChanged': JetElementCustomEvent<ojInputText<V>["clearIcon"]>; 'converterChanged': JetElementCustomEvent<ojInputText<V>["converter"]>; 'lengthChanged': JetElementCustomEvent<ojInputText<V>["length"]>; 'listChanged': JetElementCustomEvent<ojInputText<V>["list"]>; 'virtualKeyboardChanged': JetElementCustomEvent<ojInputText<V>["virtualKeyboard"]>; 'asyncValidatorsChanged': JetElementCustomEvent<ojInputText<V>["asyncValidators"]>; 'autocompleteChanged': JetElementCustomEvent<ojInputText<V>["autocomplete"]>; 'autofocusChanged': JetElementCustomEvent<ojInputText<V>["autofocus"]>; 'describedByChanged': JetElementCustomEvent<ojInputText<V>["describedBy"]>; 'disabledChanged': JetElementCustomEvent<ojInputText<V>["disabled"]>; 'displayOptionsChanged': JetElementCustomEvent<ojInputText<V>["displayOptions"]>; 'helpChanged': JetElementCustomEvent<ojInputText<V>["help"]>; 'helpHintsChanged': JetElementCustomEvent<ojInputText<V>["helpHints"]>; 'labelEdgeChanged': JetElementCustomEvent<ojInputText<V>["labelEdge"]>; 'labelHintChanged': JetElementCustomEvent<ojInputText<V>["labelHint"]>; 'labelledByChanged': JetElementCustomEvent<ojInputText<V>["labelledBy"]>; 'messagesCustomChanged': JetElementCustomEvent<ojInputText<V>["messagesCustom"]>; 'placeholderChanged': JetElementCustomEvent<ojInputText<V>["placeholder"]>; 'rawValueChanged': JetElementCustomEvent<ojInputText<V>["rawValue"]>; 'readonlyChanged': JetElementCustomEvent<ojInputText<V>["readonly"]>; 'requiredChanged': JetElementCustomEvent<ojInputText<V>["required"]>; 'userAssistanceDensityChanged': JetElementCustomEvent<ojInputText<V>["userAssistanceDensity"]>; 'validChanged': JetElementCustomEvent<ojInputText<V>["valid"]>; 'validatorsChanged': JetElementCustomEvent<ojInputText<V>["validators"]>; 'valueChanged': JetElementCustomEvent<ojInputText<V>["value"]>; } export interface ojInputTextSettableProperties<V = any> extends inputBaseSettableProperties<V> { clearIcon: 'never' | 'always' | 'conditional'; converter: Promise<Converter<V>> | Converter<V> | null; length: { countBy?: 'codePoint' | 'codeUnit'; max: number | null; }; list: string; virtualKeyboard: 'auto' | 'email' | 'number' | 'search' | 'tel' | 'text' | 'url'; } export interface ojInputTextSettablePropertiesLenient<V = any> extends Partial<ojInputTextSettableProperties<V>> { [key: string]: any; } export interface ojTextArea<V = any> extends inputBase<V, ojTextAreaSettableProperties<V>> { converter: Promise<Converter<V>> | Converter<V> | null; length: { countBy?: 'codePoint' | 'codeUnit'; counter?: 'none' | 'remaining'; max: number | null; }; maxRows: number; resizeBehavior: 'both' | 'horizontal' | 'vertical' | 'none'; rows: number; addEventListener<T extends keyof ojTextAreaEventMap<V>>(type: T, listener: (this: HTMLElement, ev: ojTextAreaEventMap<V>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojTextAreaSettableProperties<V>>(property: T): ojTextArea<V>[T]; getProperty(property: string): any; setProperty<T extends keyof ojTextAreaSettableProperties<V>>(property: T, value: ojTextAreaSettableProperties<V>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTextAreaSettableProperties<V>>): void; setProperties(properties: ojTextAreaSettablePropertiesLenient<V>): void; } export namespace ojTextArea { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type converterChanged<V = any> = JetElementCustomEvent<ojTextArea<V>["converter"]>; // tslint:disable-next-line interface-over-type-literal type lengthChanged<V = any> = JetElementCustomEvent<ojTextArea<V>["length"]>; // tslint:disable-next-line interface-over-type-literal type maxRowsChanged<V = any> = JetElementCustomEvent<ojTextArea<V>["maxRows"]>; // tslint:disable-next-line interface-over-type-literal type resizeBehaviorChanged<V = any> = JetElementCustomEvent<ojTextArea<V>["resizeBehavior"]>; // tslint:disable-next-line interface-over-type-literal type rowsChanged<V = any> = JetElementCustomEvent<ojTextArea<V>["rows"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type asyncValidatorsChanged<V = any> = inputBase.asyncValidatorsChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autocompleteChanged<V = any> = inputBase.autocompleteChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autofocusChanged<V = any> = inputBase.autofocusChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type describedByChanged<V = any> = inputBase.describedByChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V = any> = inputBase.disabledChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged<V = any> = inputBase.displayOptionsChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V = any> = inputBase.helpChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V = any> = inputBase.helpHintsChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V = any> = inputBase.labelEdgeChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V = any> = inputBase.labelHintChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V = any> = inputBase.labelledByChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V = any> = inputBase.messagesCustomChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V = any> = inputBase.placeholderChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type rawValueChanged<V = any> = inputBase.rawValueChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V = any> = inputBase.readonlyChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V = any> = inputBase.requiredChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V = any> = inputBase.userAssistanceDensityChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validChanged<V = any> = inputBase.validChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validatorsChanged<V = any> = inputBase.validatorsChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V = any> = inputBase.valueChanged<V, ojTextAreaSettableProperties<V>>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ojTextAreaEventMap<V = any> extends inputBaseEventMap<V, ojTextAreaSettableProperties<V>> { 'ojAnimateEnd': ojTextArea.ojAnimateEnd; 'ojAnimateStart': ojTextArea.ojAnimateStart; 'converterChanged': JetElementCustomEvent<ojTextArea<V>["converter"]>; 'lengthChanged': JetElementCustomEvent<ojTextArea<V>["length"]>; 'maxRowsChanged': JetElementCustomEvent<ojTextArea<V>["maxRows"]>; 'resizeBehaviorChanged': JetElementCustomEvent<ojTextArea<V>["resizeBehavior"]>; 'rowsChanged': JetElementCustomEvent<ojTextArea<V>["rows"]>; 'asyncValidatorsChanged': JetElementCustomEvent<ojTextArea<V>["asyncValidators"]>; 'autocompleteChanged': JetElementCustomEvent<ojTextArea<V>["autocomplete"]>; 'autofocusChanged': JetElementCustomEvent<ojTextArea<V>["autofocus"]>; 'describedByChanged': JetElementCustomEvent<ojTextArea<V>["describedBy"]>; 'disabledChanged': JetElementCustomEvent<ojTextArea<V>["disabled"]>; 'displayOptionsChanged': JetElementCustomEvent<ojTextArea<V>["displayOptions"]>; 'helpChanged': JetElementCustomEvent<ojTextArea<V>["help"]>; 'helpHintsChanged': JetElementCustomEvent<ojTextArea<V>["helpHints"]>; 'labelEdgeChanged': JetElementCustomEvent<ojTextArea<V>["labelEdge"]>; 'labelHintChanged': JetElementCustomEvent<ojTextArea<V>["labelHint"]>; 'labelledByChanged': JetElementCustomEvent<ojTextArea<V>["labelledBy"]>; 'messagesCustomChanged': JetElementCustomEvent<ojTextArea<V>["messagesCustom"]>; 'placeholderChanged': JetElementCustomEvent<ojTextArea<V>["placeholder"]>; 'rawValueChanged': JetElementCustomEvent<ojTextArea<V>["rawValue"]>; 'readonlyChanged': JetElementCustomEvent<ojTextArea<V>["readonly"]>; 'requiredChanged': JetElementCustomEvent<ojTextArea<V>["required"]>; 'userAssistanceDensityChanged': JetElementCustomEvent<ojTextArea<V>["userAssistanceDensity"]>; 'validChanged': JetElementCustomEvent<ojTextArea<V>["valid"]>; 'validatorsChanged': JetElementCustomEvent<ojTextArea<V>["validators"]>; 'valueChanged': JetElementCustomEvent<ojTextArea<V>["value"]>; } export interface ojTextAreaSettableProperties<V = any> extends inputBaseSettableProperties<V> { converter: Promise<Converter<V>> | Converter<V> | null; length: { countBy?: 'codePoint' | 'codeUnit'; counter?: 'none' | 'remaining'; max: number | null; }; maxRows: number; resizeBehavior: 'both' | 'horizontal' | 'vertical' | 'none'; rows: number; } export interface ojTextAreaSettablePropertiesLenient<V = any> extends Partial<ojTextAreaSettableProperties<V>> { [key: string]: any; } export type InputPasswordElement<V = string> = ojInputPassword<V>; export type InputTextElement<V = any> = ojInputText<V>; export type TextAreaElement<V = any> = ojTextArea<V>; export namespace InputPasswordElement { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type maskIconChanged<V = string> = JetElementCustomEvent<ojInputPassword<V>["maskIcon"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V = string> = JetElementCustomEvent<ojInputPassword<V>["value"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type asyncValidatorsChanged<V = string> = inputBase.asyncValidatorsChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autocompleteChanged<V = string> = inputBase.autocompleteChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autofocusChanged<V = string> = inputBase.autofocusChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type describedByChanged<V = string> = inputBase.describedByChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V = string> = inputBase.disabledChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged<V = string> = inputBase.displayOptionsChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V = string> = inputBase.helpChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V = string> = inputBase.helpHintsChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V = string> = inputBase.labelEdgeChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V = string> = inputBase.labelHintChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V = string> = inputBase.labelledByChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V = string> = inputBase.messagesCustomChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V = string> = inputBase.placeholderChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type rawValueChanged<V = string> = inputBase.rawValueChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V = string> = inputBase.readonlyChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V = string> = inputBase.requiredChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V = string> = inputBase.userAssistanceDensityChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validChanged<V = string> = inputBase.validChanged<V, ojInputPasswordSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validatorsChanged<V = string> = inputBase.validatorsChanged<V, ojInputPasswordSettableProperties<V>>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export namespace InputTextElement { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type clearIconChanged<V = any> = JetElementCustomEvent<ojInputText<V>["clearIcon"]>; // tslint:disable-next-line interface-over-type-literal type converterChanged<V = any> = JetElementCustomEvent<ojInputText<V>["converter"]>; // tslint:disable-next-line interface-over-type-literal type lengthChanged<V = any> = JetElementCustomEvent<ojInputText<V>["length"]>; // tslint:disable-next-line interface-over-type-literal type listChanged<V = any> = JetElementCustomEvent<ojInputText<V>["list"]>; // tslint:disable-next-line interface-over-type-literal type virtualKeyboardChanged<V = any> = JetElementCustomEvent<ojInputText<V>["virtualKeyboard"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type asyncValidatorsChanged<V = any> = inputBase.asyncValidatorsChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autocompleteChanged<V = any> = inputBase.autocompleteChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autofocusChanged<V = any> = inputBase.autofocusChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type describedByChanged<V = any> = inputBase.describedByChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V = any> = inputBase.disabledChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged<V = any> = inputBase.displayOptionsChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V = any> = inputBase.helpChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V = any> = inputBase.helpHintsChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V = any> = inputBase.labelEdgeChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V = any> = inputBase.labelHintChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V = any> = inputBase.labelledByChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V = any> = inputBase.messagesCustomChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V = any> = inputBase.placeholderChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type rawValueChanged<V = any> = inputBase.rawValueChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V = any> = inputBase.readonlyChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V = any> = inputBase.requiredChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V = any> = inputBase.userAssistanceDensityChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validChanged<V = any> = inputBase.validChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validatorsChanged<V = any> = inputBase.validatorsChanged<V, ojInputTextSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V = any> = inputBase.valueChanged<V, ojInputTextSettableProperties<V>>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export namespace TextAreaElement { interface ojAnimateEnd extends CustomEvent<{ action: string; element: Element; [propName: string]: any; }> { } interface ojAnimateStart extends CustomEvent<{ action: string; element: Element; endCallback: (() => void); [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type converterChanged<V = any> = JetElementCustomEvent<ojTextArea<V>["converter"]>; // tslint:disable-next-line interface-over-type-literal type lengthChanged<V = any> = JetElementCustomEvent<ojTextArea<V>["length"]>; // tslint:disable-next-line interface-over-type-literal type maxRowsChanged<V = any> = JetElementCustomEvent<ojTextArea<V>["maxRows"]>; // tslint:disable-next-line interface-over-type-literal type resizeBehaviorChanged<V = any> = JetElementCustomEvent<ojTextArea<V>["resizeBehavior"]>; // tslint:disable-next-line interface-over-type-literal type rowsChanged<V = any> = JetElementCustomEvent<ojTextArea<V>["rows"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type asyncValidatorsChanged<V = any> = inputBase.asyncValidatorsChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autocompleteChanged<V = any> = inputBase.autocompleteChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type autofocusChanged<V = any> = inputBase.autofocusChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type describedByChanged<V = any> = inputBase.describedByChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<V = any> = inputBase.disabledChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type displayOptionsChanged<V = any> = inputBase.displayOptionsChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpChanged<V = any> = inputBase.helpChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type helpHintsChanged<V = any> = inputBase.helpHintsChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelEdgeChanged<V = any> = inputBase.labelEdgeChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelHintChanged<V = any> = inputBase.labelHintChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged<V = any> = inputBase.labelledByChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type messagesCustomChanged<V = any> = inputBase.messagesCustomChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type placeholderChanged<V = any> = inputBase.placeholderChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type rawValueChanged<V = any> = inputBase.rawValueChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type readonlyChanged<V = any> = inputBase.readonlyChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type requiredChanged<V = any> = inputBase.requiredChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type userAssistanceDensityChanged<V = any> = inputBase.userAssistanceDensityChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validChanged<V = any> = inputBase.validChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type validatorsChanged<V = any> = inputBase.validatorsChanged<V, ojTextAreaSettableProperties<V>>; // tslint:disable-next-line interface-over-type-literal type valueChanged<V = any> = inputBase.valueChanged<V, ojTextAreaSettableProperties<V>>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface InputPasswordIntrinsicProps extends Partial<Readonly<ojInputPasswordSettableProperties<any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAnimateEnd?: (value: ojInputPasswordEventMap<any>['ojAnimateEnd']) => void; onojAnimateStart?: (value: ojInputPasswordEventMap<any>['ojAnimateStart']) => void; onmaskIconChanged?: (value: ojInputPasswordEventMap<any>['maskIconChanged']) => void; onvalueChanged?: (value: ojInputPasswordEventMap<any>['valueChanged']) => void; onasyncValidatorsChanged?: (value: ojInputPasswordEventMap<any>['asyncValidatorsChanged']) => void; onautocompleteChanged?: (value: ojInputPasswordEventMap<any>['autocompleteChanged']) => void; onautofocusChanged?: (value: ojInputPasswordEventMap<any>['autofocusChanged']) => void; ondescribedByChanged?: (value: ojInputPasswordEventMap<any>['describedByChanged']) => void; ondisabledChanged?: (value: ojInputPasswordEventMap<any>['disabledChanged']) => void; ondisplayOptionsChanged?: (value: ojInputPasswordEventMap<any>['displayOptionsChanged']) => void; onhelpChanged?: (value: ojInputPasswordEventMap<any>['helpChanged']) => void; onhelpHintsChanged?: (value: ojInputPasswordEventMap<any>['helpHintsChanged']) => void; onlabelEdgeChanged?: (value: ojInputPasswordEventMap<any>['labelEdgeChanged']) => void; onlabelHintChanged?: (value: ojInputPasswordEventMap<any>['labelHintChanged']) => void; onlabelledByChanged?: (value: ojInputPasswordEventMap<any>['labelledByChanged']) => void; onmessagesCustomChanged?: (value: ojInputPasswordEventMap<any>['messagesCustomChanged']) => void; onplaceholderChanged?: (value: ojInputPasswordEventMap<any>['placeholderChanged']) => void; onrawValueChanged?: (value: ojInputPasswordEventMap<any>['rawValueChanged']) => void; onreadonlyChanged?: (value: ojInputPasswordEventMap<any>['readonlyChanged']) => void; onrequiredChanged?: (value: ojInputPasswordEventMap<any>['requiredChanged']) => void; onuserAssistanceDensityChanged?: (value: ojInputPasswordEventMap<any>['userAssistanceDensityChanged']) => void; onvalidChanged?: (value: ojInputPasswordEventMap<any>['validChanged']) => void; onvalidatorsChanged?: (value: ojInputPasswordEventMap<any>['validatorsChanged']) => void; children?: ComponentChildren; } export interface InputTextIntrinsicProps extends Partial<Readonly<ojInputTextSettableProperties<any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAnimateEnd?: (value: ojInputTextEventMap<any>['ojAnimateEnd']) => void; onojAnimateStart?: (value: ojInputTextEventMap<any>['ojAnimateStart']) => void; onclearIconChanged?: (value: ojInputTextEventMap<any>['clearIconChanged']) => void; onconverterChanged?: (value: ojInputTextEventMap<any>['converterChanged']) => void; onlengthChanged?: (value: ojInputTextEventMap<any>['lengthChanged']) => void; onlistChanged?: (value: ojInputTextEventMap<any>['listChanged']) => void; onvirtualKeyboardChanged?: (value: ojInputTextEventMap<any>['virtualKeyboardChanged']) => void; onasyncValidatorsChanged?: (value: ojInputTextEventMap<any>['asyncValidatorsChanged']) => void; onautocompleteChanged?: (value: ojInputTextEventMap<any>['autocompleteChanged']) => void; onautofocusChanged?: (value: ojInputTextEventMap<any>['autofocusChanged']) => void; ondescribedByChanged?: (value: ojInputTextEventMap<any>['describedByChanged']) => void; ondisabledChanged?: (value: ojInputTextEventMap<any>['disabledChanged']) => void; ondisplayOptionsChanged?: (value: ojInputTextEventMap<any>['displayOptionsChanged']) => void; onhelpChanged?: (value: ojInputTextEventMap<any>['helpChanged']) => void; onhelpHintsChanged?: (value: ojInputTextEventMap<any>['helpHintsChanged']) => void; onlabelEdgeChanged?: (value: ojInputTextEventMap<any>['labelEdgeChanged']) => void; onlabelHintChanged?: (value: ojInputTextEventMap<any>['labelHintChanged']) => void; onlabelledByChanged?: (value: ojInputTextEventMap<any>['labelledByChanged']) => void; onmessagesCustomChanged?: (value: ojInputTextEventMap<any>['messagesCustomChanged']) => void; onplaceholderChanged?: (value: ojInputTextEventMap<any>['placeholderChanged']) => void; onrawValueChanged?: (value: ojInputTextEventMap<any>['rawValueChanged']) => void; onreadonlyChanged?: (value: ojInputTextEventMap<any>['readonlyChanged']) => void; onrequiredChanged?: (value: ojInputTextEventMap<any>['requiredChanged']) => void; onuserAssistanceDensityChanged?: (value: ojInputTextEventMap<any>['userAssistanceDensityChanged']) => void; onvalidChanged?: (value: ojInputTextEventMap<any>['validChanged']) => void; onvalidatorsChanged?: (value: ojInputTextEventMap<any>['validatorsChanged']) => void; onvalueChanged?: (value: ojInputTextEventMap<any>['valueChanged']) => void; children?: ComponentChildren; } export interface TextAreaIntrinsicProps extends Partial<Readonly<ojTextAreaSettableProperties<any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAnimateEnd?: (value: ojTextAreaEventMap<any>['ojAnimateEnd']) => void; onojAnimateStart?: (value: ojTextAreaEventMap<any>['ojAnimateStart']) => void; onconverterChanged?: (value: ojTextAreaEventMap<any>['converterChanged']) => void; onlengthChanged?: (value: ojTextAreaEventMap<any>['lengthChanged']) => void; onmaxRowsChanged?: (value: ojTextAreaEventMap<any>['maxRowsChanged']) => void; onresizeBehaviorChanged?: (value: ojTextAreaEventMap<any>['resizeBehaviorChanged']) => void; onrowsChanged?: (value: ojTextAreaEventMap<any>['rowsChanged']) => void; onasyncValidatorsChanged?: (value: ojTextAreaEventMap<any>['asyncValidatorsChanged']) => void; onautocompleteChanged?: (value: ojTextAreaEventMap<any>['autocompleteChanged']) => void; onautofocusChanged?: (value: ojTextAreaEventMap<any>['autofocusChanged']) => void; ondescribedByChanged?: (value: ojTextAreaEventMap<any>['describedByChanged']) => void; ondisabledChanged?: (value: ojTextAreaEventMap<any>['disabledChanged']) => void; ondisplayOptionsChanged?: (value: ojTextAreaEventMap<any>['displayOptionsChanged']) => void; onhelpChanged?: (value: ojTextAreaEventMap<any>['helpChanged']) => void; onhelpHintsChanged?: (value: ojTextAreaEventMap<any>['helpHintsChanged']) => void; onlabelEdgeChanged?: (value: ojTextAreaEventMap<any>['labelEdgeChanged']) => void; onlabelHintChanged?: (value: ojTextAreaEventMap<any>['labelHintChanged']) => void; onlabelledByChanged?: (value: ojTextAreaEventMap<any>['labelledByChanged']) => void; onmessagesCustomChanged?: (value: ojTextAreaEventMap<any>['messagesCustomChanged']) => void; onplaceholderChanged?: (value: ojTextAreaEventMap<any>['placeholderChanged']) => void; onrawValueChanged?: (value: ojTextAreaEventMap<any>['rawValueChanged']) => void; onreadonlyChanged?: (value: ojTextAreaEventMap<any>['readonlyChanged']) => void; onrequiredChanged?: (value: ojTextAreaEventMap<any>['requiredChanged']) => void; onuserAssistanceDensityChanged?: (value: ojTextAreaEventMap<any>['userAssistanceDensityChanged']) => void; onvalidChanged?: (value: ojTextAreaEventMap<any>['validChanged']) => void; onvalidatorsChanged?: (value: ojTextAreaEventMap<any>['validatorsChanged']) => void; onvalueChanged?: (value: ojTextAreaEventMap<any>['valueChanged']) => void; children?: ComponentChildren; } declare global { namespace preact.JSX { interface IntrinsicElements { "oj-input-password": InputPasswordIntrinsicProps; "oj-input-text": InputTextIntrinsicProps; "oj-text-area": TextAreaIntrinsicProps; } } }
the_stack
import { App, aws_dynamodb, Stack } from "aws-cdk-lib"; import "jest"; import { Table, $util, AppsyncContext, reflect, $AWS, ITable, AnyTable, } from "../src"; import { appsyncTestCase } from "./util"; interface Item { id: string; name: number; } const app = new App({ autoSynth: false }); const stack = new Stack(app, "stack"); const fromTable = Table.fromTable<Item, "id">( new aws_dynamodb.Table(stack, "FromTable", { partitionKey: { name: "id", type: aws_dynamodb.AttributeType.STRING, }, }) ); const newTable = new Table<Item, "id">(stack, "NewTable", { partitionKey: { name: "id", type: aws_dynamodb.AttributeType.STRING, }, }); const fromTableSortKey = Table.fromTable<Item, "id", "name">( new aws_dynamodb.Table(stack, "FromTableSortKey", { partitionKey: { name: "id", type: aws_dynamodb.AttributeType.STRING, }, sortKey: { name: "name", type: aws_dynamodb.AttributeType.NUMBER, }, }) ); const newTableSortKey = new Table<Item, "id", "name">( stack, "NewTableSortKey", { partitionKey: { name: "id", type: aws_dynamodb.AttributeType.STRING, }, sortKey: { name: "name", type: aws_dynamodb.AttributeType.NUMBER, }, } ); /** * Enclose calls to $AWS.DynamoDB in a function so that they never run. * * The contents of this function are for type-level tests only. * * We use @ts-expect-error to validate that types are inferred properly. */ export function typeCheck() { let t1: Table<any, any, any> | undefined; let t2: Table<Item, "id"> | undefined; let t3: Table<Record<string, any>, string, string | undefined> | undefined; t1 = t2; t1 = t3; // type checks because Table<any, any, any> short circuits t2 = t1; // @ts-expect-error - Table<Record<string | number | symbol, any>, string | number | symbol, string | number | symbol | undefined> | undefined' is not assignable to type 'Table<Item, "id", undefined> | undefined t2 = t3; t3 = t1; t3 = t2; let t4: ITable<any, any, any> | undefined; let t5: ITable<Item, "id"> | undefined; let t6: AnyTable | undefined; t4 = t1; t4 = t2; t4 = t3; t4 = t5; t4 = t6; // type checks because Table<any, any, any> short circuits t5 = t2; // @ts-expect-error - Table<Record<string | number | symbol, any>, string | number | symbol, string | number | symbol | undefined> | undefined' is not assignable to type 'ITable<Item, "id", undefined> | undefined t5 = t3; // type checks because ITable<any, any, any> short circuits t5 = t4; // @ts-expect-error - 'AnyTable | undefined' is not assignable to type 'ITable<Item, "id", undefined> | undefined' t5 = t6; t6 = t1; t6 = t2; t6 = t3; t6 = t4; t6 = t5; // Test1: type checking should work for Table $AWS.DynamoDB.GetItem({ TableName: newTable, // @ts-expect-error - missing id prop Key: {}, }); $AWS.DynamoDB.PutItem({ TableName: newTable, Item: { id: { S: "", }, name: { N: `1`, }, // @ts-expect-error nonExistent: { S: "", }, }, }); $AWS.DynamoDB.DeleteItem({ TableName: newTable, // @ts-expect-error - missing id prop Key: {}, }); $AWS.DynamoDB.UpdateItem({ TableName: newTable, // @ts-expect-error - missing id prop Key: {}, UpdateExpression: "", }); // Test2: type checking should work for ITable $AWS.DynamoDB.GetItem({ TableName: fromTable, // @ts-expect-error - missing id prop Key: {}, }); $AWS.DynamoDB.PutItem({ TableName: fromTable, Item: { id: { S: "", }, name: { N: `1`, }, // @ts-expect-error nonExistent: { S: "", }, }, }); $AWS.DynamoDB.DeleteItem({ TableName: fromTable, // @ts-expect-error - missing id prop Key: {}, }); $AWS.DynamoDB.UpdateItem({ TableName: fromTable, // @ts-expect-error - missing id prop Key: {}, UpdateExpression: "", }); } /** * Enclose calls to $AWS.DynamoDB in a function so that they never run. * * The contents of this function are for type-level tests only. * * We use @ts-expect-error to validate that types are inferred properly. */ export function typeCheckSortKey() { let t1: Table<any, any, any> | undefined; let t2: Table<Item, "id", "name"> | undefined; let t3: Table<Record<string, any>, string, string | undefined> | undefined; t1 = t2; t1 = t3; // type checks because Table<any, any, any> short circuits t2 = t1; // @ts-expect-error - Table<Record<string | number | symbol, any>, string | number | symbol, string | number | symbol | undefined> | undefined' is not assignable to type 'Table<Item, "id", undefined> | undefined t2 = t3; t3 = t1; t3 = t2; let t4: ITable<any, any, any> | undefined; let t5: ITable<Item, "id", "name"> | undefined; let t6: AnyTable | undefined; t4 = t1; t4 = t2; t4 = t3; t4 = t5; t4 = t6; // type checks because Table<any, any, any> short circuits t5 = t2; // @ts-expect-error - Table<Record<string | number | symbol, any>, string | number | symbol, string | number | symbol | undefined> | undefined' is not assignable to type 'ITable<Item, "id", undefined> | undefined t5 = t3; // type checks because ITable<any, any, any> short circuits t5 = t4; // @ts-expect-error - 'AnyTable | undefined' is not assignable to type 'ITable<Item, "id", undefined> | undefined' t5 = t6; t6 = t1; t6 = t2; t6 = t3; t6 = t4; t6 = t5; // Test1: type checking should work for Table $AWS.DynamoDB.GetItem({ TableName: newTable, // @ts-expect-error - missing id prop Key: {}, }); $AWS.DynamoDB.PutItem({ TableName: newTable, Item: { id: { S: "", }, name: { N: `1`, }, // @ts-expect-error nonExistent: { S: "", }, }, }); $AWS.DynamoDB.DeleteItem({ TableName: newTable, // @ts-expect-error - missing id prop Key: {}, }); $AWS.DynamoDB.UpdateItem({ TableName: newTable, // @ts-expect-error - missing id prop Key: {}, UpdateExpression: "", }); // Test2: type checking should work for ITable $AWS.DynamoDB.GetItem({ TableName: fromTable, // @ts-expect-error - missing id prop Key: {}, }); $AWS.DynamoDB.PutItem({ TableName: fromTable, Item: { id: { S: "", }, name: { N: `1`, }, // @ts-expect-error nonExistent: { S: "", }, }, }); $AWS.DynamoDB.DeleteItem({ TableName: fromTable, // @ts-expect-error - missing id prop Key: {}, }); $AWS.DynamoDB.UpdateItem({ TableName: fromTable, // @ts-expect-error - missing id prop Key: {}, UpdateExpression: "", }); } test.each([fromTable, newTable])("get item", (table) => { appsyncTestCase( reflect((context: AppsyncContext<{ id: string }>): Item | undefined => { return table.getItem({ key: { id: { S: context.arguments.id, }, }, }); }) ); }); test.each([fromTableSortKey, newTableSortKey])("get item", (table) => { appsyncTestCase( reflect((context: AppsyncContext<{ id: string }>): Item | undefined => { return table.getItem({ key: { id: { S: context.arguments.id, }, name: { N: "1", }, }, }); }) ); }); test.each([fromTable, newTable])( "get item and set consistentRead:true", (table) => { appsyncTestCase( reflect((context: AppsyncContext<{ id: string }>): Item | undefined => { return table.getItem({ key: { id: { S: context.arguments.id, }, }, consistentRead: true, }); }) ); } ); test.each([fromTableSortKey, newTableSortKey])( "get item and set consistentRead:true", (table) => { appsyncTestCase( reflect((context: AppsyncContext<{ id: string }>): Item | undefined => { return table.getItem({ key: { id: { S: context.arguments.id, }, name: { N: "1", }, }, consistentRead: true, }); }) ); } ); test.each([fromTable, newTable])("put item", (table) => { appsyncTestCase( reflect( ( context: AppsyncContext<{ id: string; name: number }> ): Item | undefined => { return table.putItem({ key: { id: { S: context.arguments.id, }, }, attributeValues: { name: { N: `${context.arguments.name}`, }, }, condition: { expression: "#name = :val", expressionNames: { "#name": "name", }, expressionValues: { ":val": { S: context.arguments.id, }, }, }, }); } ) ); }); test.each([fromTableSortKey, newTableSortKey])("put item", (table) => { appsyncTestCase( reflect( ( context: AppsyncContext<{ id: string; name: number }> ): Item | undefined => { return table.putItem({ key: { id: { S: context.arguments.id, }, name: { N: "1", }, }, attributeValues: {}, condition: { expression: "#name = :val", expressionNames: { "#name": "name", }, expressionValues: { ":val": { S: context.arguments.id, }, }, }, }); } ) ); }); test.each([fromTable, newTable])("update item", (table) => { appsyncTestCase( reflect((context: AppsyncContext<{ id: string }>): Item | undefined => { return table.updateItem({ key: { id: { S: context.arguments.id, }, }, update: { expression: "#name = #name + 1", expressionNames: { "#name": "name", }, }, }); }) ); }); test.each([fromTableSortKey, newTableSortKey])("update item", (table) => { appsyncTestCase( reflect((context: AppsyncContext<{ id: string }>): Item | undefined => { return table.updateItem({ key: { id: { S: context.arguments.id, }, name: { N: "1", }, }, update: { expression: "#name = #name + 1", expressionNames: { "#name": "name", }, }, }); }) ); }); test.each([fromTable, newTable])("delete item", (table) => { appsyncTestCase( reflect((context: AppsyncContext<{ id: string }>): Item | undefined => { return table.deleteItem({ key: { id: { S: context.arguments.id, }, }, condition: { expression: "#name = #name + 1", expressionNames: { "#name": "name", }, }, }); }) ); }); test.each([fromTableSortKey, newTableSortKey])("delete item", (table) => { appsyncTestCase( reflect((context: AppsyncContext<{ id: string }>): Item | undefined => { return table.deleteItem({ key: { id: { S: context.arguments.id, }, name: { N: "1", }, }, condition: { expression: "#name = #name + 1", expressionNames: { "#name": "name", }, }, }); }) ); }); test.each([fromTable, newTable])("query", (table) => { appsyncTestCase( reflect((context: AppsyncContext<{ id: string; sort: number }>): Item[] => { return table.query({ query: { expression: "id = :id and #name = :val", expressionNames: { "#name": "name", }, expressionValues: { ":id": $util.dynamodb.toDynamoDB(context.arguments.id), ":val": $util.dynamodb.toDynamoDB(context.arguments.sort), }, }, }).items; }) ); }); test.each([fromTableSortKey, newTableSortKey])("query", (table) => { appsyncTestCase( reflect((context: AppsyncContext<{ id: string; sort: number }>): Item[] => { return table.query({ query: { expression: "id = :id and #name = :val", expressionNames: { "#name": "name", }, expressionValues: { ":id": $util.dynamodb.toDynamoDB(context.arguments.id), ":val": $util.dynamodb.toDynamoDB(context.arguments.sort), }, }, }).items; }) ); });
the_stack