text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
// Generated using the following tsjava options: // tsJavaModulePath: // tsJavaModule.ts // classpath: // target/hellojava-1.0.0.jar // classes: // com.redseal.hellojava.HelloJava // packages: // <none> /* tslint:disable:max-line-length class-name */ declare function require(name: string): any; require('source-map-support').install(); import _java = require('java'); import _ = require('lodash'); import BluePromise = require('bluebird'); import path = require('path'); _java.asyncOptions = { syncSuffix: '', asyncSuffix: 'A', promiseSuffix: 'P', promisify: BluePromise.promisify }; // JVM initialization callback which adds tsjava.classpath to the JVM classpath. function beforeJvm(): BluePromise<void> { var moduleJars: string[] = ['target/hellojava-1.0.0.jar']; moduleJars.forEach((jarPath: string) => { var fullJarPath: string = path.join(__dirname, '', jarPath); _java.classpath.push(fullJarPath); }); return BluePromise.resolve(); } _java.registerClientP(beforeJvm); export module Java { 'use strict'; interface StringDict { [index: string]: string; } export type NodeJavaAPI = typeof _java; export function getJava(): NodeJavaAPI { return _java; } export function ensureJvm(): Promise<void> { return _java.ensureJvm(); } // Return the fully qualified class path for a class name. // Returns undefined if the className is ambiguous or not present in the configured classes. export function fullyQualifiedName(className: string): string { var shortToLongMap: StringDict = { 'HelloJava': 'com.redseal.hellojava.HelloJava', 'Object': 'java.lang.Object', 'String': 'java.lang.String' }; return shortToLongMap[className]; } export function importClass(className: 'HelloJava'): Java.com.redseal.hellojava.HelloJava.Static; export function importClass(className: 'Object'): Java.java.lang.Object.Static; export function importClass(className: 'String'): Java.java.lang.String.Static; export function importClass(className: 'com.redseal.hellojava.HelloJava'): Java.com.redseal.hellojava.HelloJava.Static; export function importClass(className: 'java.lang.Object'): Java.java.lang.Object.Static; export function importClass(className: 'java.lang.String'): Java.java.lang.String.Static; export function importClass(className: string): any; export function importClass(className: string): any { var fullName: string = fullyQualifiedName(className) || className; return _java.import(fullName); } export function asInstanceOf(obj: any, className: 'HelloJava'): Java.com.redseal.hellojava.HelloJava; export function asInstanceOf(obj: any, className: 'Object'): Java.java.lang.Object; export function asInstanceOf(obj: any, className: 'String'): Java.java.lang.String; export function asInstanceOf(obj: any, className: 'com.redseal.hellojava.HelloJava'): Java.com.redseal.hellojava.HelloJava; export function asInstanceOf(obj: any, className: 'java.lang.Object'): Java.java.lang.Object; export function asInstanceOf(obj: any, className: 'java.lang.String'): Java.java.lang.String; export function asInstanceOf(obj: any, className: string): any; export function asInstanceOf(obj: any, className: string): any { var fullName: string = fullyQualifiedName(className) || className; if (_java.instanceOf(obj, fullName)) { return obj; } else { throw new Error('asInstanceOf fails, obj is not a ' + fullName); } } export interface Callback<T> { (err?: Error, result?: T): void; } // Returns true if javaObject is an instance of the named class, which may be a short className. // Returns false if javaObject is not an instance of the named class. // Throws an exception if the named class does not exist, or is an ambiguous short name. export function instanceOf(javaObject: any, className: string): boolean { var fullName: string = fullyQualifiedName(className) || className; return smellsLikeJavaObject(javaObject) && _java.instanceOf(javaObject, fullName); } export function newInstanceA(className: 'HelloJava', cb: Callback<Java.HelloJava>): void; export function newInstanceA(className: 'Object', cb: Callback<object_t>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', cb: Callback<string>): void; export function newInstanceA(className: 'com.redseal.hellojava.HelloJava', cb: Callback<Java.HelloJava>): void; export function newInstanceA(className: 'java.lang.Object', cb: Callback<object_t>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', cb: Callback<string>): void; export function newInstanceA(className: string, ...args: any[]): void; export function newInstanceA(className: string, ...args: any[]): any { var fullName: string = fullyQualifiedName(className) || className; args.unshift(fullName); return _java.newInstance.apply(_java, args); } export function newInstance(className: 'HelloJava'): Java.HelloJava; export function newInstance(className: 'Object'): object_t; export function newInstance(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: string_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: object_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: string_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: object_t): string; export function newInstance(className: 'String', arg0: object_t): string; export function newInstance(className: 'String', arg0: object_t): string; export function newInstance(className: 'String', arg0: string_t): string; export function newInstance(className: 'String', arg0: object_array_t): string; export function newInstance(className: 'String', arg0: object_array_t): string; export function newInstance(className: 'String'): string; export function newInstance(className: 'com.redseal.hellojava.HelloJava'): Java.HelloJava; export function newInstance(className: 'java.lang.Object'): object_t; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: string_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: string_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_t): string; export function newInstance(className: 'java.lang.String', arg0: string_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t): string; export function newInstance(className: 'java.lang.String'): string; export function newInstance(className: string, ...args: any[]): any; export function newInstance(className: string, ...args: any[]): any { var fullName: string = fullyQualifiedName(className) || className; args.unshift(fullName); return _java.newInstanceSync.apply(_java, args); } export function newInstanceP(className: 'HelloJava'): Promise<Java.HelloJava>; export function newInstanceP(className: 'Object'): Promise<object_t>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: string_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: object_t, arg2: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: string_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: string_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t): Promise<string>; export function newInstanceP(className: 'String'): Promise<string>; export function newInstanceP(className: 'com.redseal.hellojava.HelloJava'): Promise<Java.HelloJava>; export function newInstanceP(className: 'java.lang.Object'): Promise<object_t>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: string_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, arg2: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: string_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: string_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t): Promise<string>; export function newInstanceP(className: 'java.lang.String'): Promise<string>; export function newInstanceP(className: string, ...args: any[]): Promise<any>; export function newInstanceP(className: string, ...args: any[]): Promise<any> { var fullName: string = fullyQualifiedName(className) || className; args.unshift(fullName); return _java.newInstanceP.apply(_java, args); } export function newArray(className: 'HelloJava', arg: Java.HelloJava[]): array_t<com.redseal.hellojava.HelloJava>; export function newArray(className: 'Object', arg: object_t[]): array_t<java.lang.Object>; export function newArray(className: 'String', arg: string_t[]): array_t<java.lang.String>; export function newArray(className: 'com.redseal.hellojava.HelloJava', arg: Java.HelloJava[]): array_t<com.redseal.hellojava.HelloJava>; export function newArray(className: 'java.lang.Object', arg: object_t[]): array_t<java.lang.Object>; export function newArray(className: 'java.lang.String', arg: string_t[]): array_t<java.lang.String>; export function newArray<T>(className: string, arg: any[]): array_t<T>; export function newArray<T>(className: string, arg: any[]): array_t<T> { var fullName: string = fullyQualifiedName(className) || className; return _java.newArray(fullName, arg); } // export module Java { // Node-java has special handling for methods that return long or java.lang.Long, // returning a Javascript Number but with an additional property longValue. export interface longValue_t extends Number { longValue: string; } // Node-java can automatically coerce a javascript string into a java.lang.String. // This special type alias allows to declare that possiblity to Typescript. export type string_t = string | Java.java.lang.String; // Java methods that take java.lang.Object parameters implicitly will take a java.lang.String. // But string_t is not sufficient for this case, we need object_t. export type object_t = Java.java.lang.Object | string | boolean | number | longValue_t; // Java methods that take long or java.lang.Long parameters may take javascript numbers, // longValue_t (see above) or java.lang.Long. // This special type alias allows to declare that possiblity to Typescript. export type long_t = number | longValue_t ; // Handling of other primitive numeric types is simpler, as there is no loss of precision. export type boolean_t = boolean ; export type short_t = number ; export type integer_t = number ; export type double_t = number ; export type float_t = number ; export type number_t = number ; export interface array_t<T> extends Java.java.lang.Object { // This is an opaque type for a java array_t T[]; // Use Java.newArray<T>(className, [...]) to create wherever a Java method expects a T[], // most notably for vararg parameteters. __dummy: T; } export type object_array_t = array_t<Java.java.lang.Object> | object_t[]; export import HelloJava = com.redseal.hellojava.HelloJava; export import Object = java.lang.Object; export import String = java.lang.String; export module com.redseal.hellojava { export interface HelloJava extends Java.java.lang.Object { // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<object_t>): void; equals(arg0: object_t): object_t; equalsP(arg0: object_t): Promise<object_t>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<object_t>): void; getClass(): object_t; getClassP(): Promise<object_t>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<object_t>): void; hashCode(): object_t; hashCodeP(): Promise<object_t>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: object_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: object_t): void; waitP(arg0: object_t, arg1: object_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module HelloJava { export interface Static { class: Java.Object; new (): com.redseal.hellojava.HelloJava; // public static java.lang.String com.redseal.hellojava.HelloJava.sayHello() sayHelloA( cb: Callback<string>): void; sayHello(): string; sayHelloP(): Promise<string>; } } } export module java.lang { export interface Object { // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<object_t>): void; equals(arg0: object_t): object_t; equalsP(arg0: object_t): Promise<object_t>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<object_t>): void; getClass(): object_t; getClassP(): Promise<object_t>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<object_t>): void; hashCode(): object_t; hashCodeP(): Promise<object_t>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: object_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: object_t): void; waitP(arg0: object_t, arg1: object_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Object { export interface Static { class: Java.Object; new (): java.lang.Object; } } } export module java.lang { export interface String extends Java.java.lang.Object { // public char java.lang.String.charAt(int) charAtA(arg0: object_t, cb: Callback<object_t>): void; charAt(arg0: object_t): object_t; charAtP(arg0: object_t): Promise<object_t>; // public default java.util.stream.IntStream java.lang.CharSequence.chars() charsA( cb: Callback<object_t>): void; chars(): object_t; charsP(): Promise<object_t>; // public int java.lang.String.codePointAt(int) codePointAtA(arg0: object_t, cb: Callback<object_t>): void; codePointAt(arg0: object_t): object_t; codePointAtP(arg0: object_t): Promise<object_t>; // public int java.lang.String.codePointBefore(int) codePointBeforeA(arg0: object_t, cb: Callback<object_t>): void; codePointBefore(arg0: object_t): object_t; codePointBeforeP(arg0: object_t): Promise<object_t>; // public int java.lang.String.codePointCount(int,int) codePointCountA(arg0: object_t, arg1: object_t, cb: Callback<object_t>): void; codePointCount(arg0: object_t, arg1: object_t): object_t; codePointCountP(arg0: object_t, arg1: object_t): Promise<object_t>; // public default java.util.stream.IntStream java.lang.CharSequence.codePoints() codePointsA( cb: Callback<object_t>): void; codePoints(): object_t; codePointsP(): Promise<object_t>; // public int java.lang.String.compareTo(java.lang.String) compareToA(arg0: string_t, cb: Callback<object_t>): void; compareTo(arg0: string_t): object_t; compareToP(arg0: string_t): Promise<object_t>; // public int java.lang.String.compareTo(java.lang.Object) compareToA(arg0: object_t, cb: Callback<object_t>): void; compareTo(arg0: object_t): object_t; compareToP(arg0: object_t): Promise<object_t>; // public int java.lang.String.compareToIgnoreCase(java.lang.String) compareToIgnoreCaseA(arg0: string_t, cb: Callback<object_t>): void; compareToIgnoreCase(arg0: string_t): object_t; compareToIgnoreCaseP(arg0: string_t): Promise<object_t>; // public java.lang.String java.lang.String.concat(java.lang.String) concatA(arg0: string_t, cb: Callback<string>): void; concat(arg0: string_t): string; concatP(arg0: string_t): Promise<string>; // public boolean java.lang.String.contains(java.lang.CharSequence) containsA(arg0: object_t, cb: Callback<object_t>): void; contains(arg0: object_t): object_t; containsP(arg0: object_t): Promise<object_t>; // public boolean java.lang.String.contentEquals(java.lang.StringBuffer) contentEqualsA(arg0: object_t, cb: Callback<object_t>): void; contentEquals(arg0: object_t): object_t; contentEqualsP(arg0: object_t): Promise<object_t>; // public boolean java.lang.String.contentEquals(java.lang.CharSequence) contentEqualsA(arg0: object_t, cb: Callback<object_t>): void; contentEquals(arg0: object_t): object_t; contentEqualsP(arg0: object_t): Promise<object_t>; // public boolean java.lang.String.endsWith(java.lang.String) endsWithA(arg0: string_t, cb: Callback<object_t>): void; endsWith(arg0: string_t): object_t; endsWithP(arg0: string_t): Promise<object_t>; // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<object_t>): void; equals(arg0: object_t): object_t; equalsP(arg0: object_t): Promise<object_t>; // public boolean java.lang.String.equalsIgnoreCase(java.lang.String) equalsIgnoreCaseA(arg0: string_t, cb: Callback<object_t>): void; equalsIgnoreCase(arg0: string_t): object_t; equalsIgnoreCaseP(arg0: string_t): Promise<object_t>; // public void java.lang.String.getBytes(int,int,byte[],int) getBytesA(arg0: object_t, arg1: object_t, arg2: object_array_t, arg3: object_t, cb: Callback<void>): void; getBytes(arg0: object_t, arg1: object_t, arg2: object_array_t, arg3: object_t): void; getBytesP(arg0: object_t, arg1: object_t, arg2: object_array_t, arg3: object_t): Promise<void>; // public byte[] java.lang.String.getBytes(java.nio.charset.Charset) getBytesA(arg0: object_t, cb: Callback<object_t[]>): void; getBytes(arg0: object_t): object_t[]; getBytesP(arg0: object_t): Promise<object_t[]>; // public byte[] java.lang.String.getBytes(java.lang.String) throws java.io.UnsupportedEncodingException getBytesA(arg0: string_t, cb: Callback<object_t[]>): void; getBytes(arg0: string_t): object_t[]; getBytesP(arg0: string_t): Promise<object_t[]>; // public byte[] java.lang.String.getBytes() getBytesA( cb: Callback<object_t[]>): void; getBytes(): object_t[]; getBytesP(): Promise<object_t[]>; // public void java.lang.String.getChars(int,int,char[],int) getCharsA(arg0: object_t, arg1: object_t, arg2: object_array_t, arg3: object_t, cb: Callback<void>): void; getChars(arg0: object_t, arg1: object_t, arg2: object_array_t, arg3: object_t): void; getCharsP(arg0: object_t, arg1: object_t, arg2: object_array_t, arg3: object_t): Promise<void>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<object_t>): void; getClass(): object_t; getClassP(): Promise<object_t>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<object_t>): void; hashCode(): object_t; hashCodeP(): Promise<object_t>; // public int java.lang.String.indexOf(java.lang.String,int) indexOfA(arg0: string_t, arg1: object_t, cb: Callback<object_t>): void; indexOf(arg0: string_t, arg1: object_t): object_t; indexOfP(arg0: string_t, arg1: object_t): Promise<object_t>; // public int java.lang.String.indexOf(int,int) indexOfA(arg0: object_t, arg1: object_t, cb: Callback<object_t>): void; indexOf(arg0: object_t, arg1: object_t): object_t; indexOfP(arg0: object_t, arg1: object_t): Promise<object_t>; // public int java.lang.String.indexOf(java.lang.String) indexOfA(arg0: string_t, cb: Callback<object_t>): void; indexOf(arg0: string_t): object_t; indexOfP(arg0: string_t): Promise<object_t>; // public int java.lang.String.indexOf(int) indexOfA(arg0: object_t, cb: Callback<object_t>): void; indexOf(arg0: object_t): object_t; indexOfP(arg0: object_t): Promise<object_t>; // public native java.lang.String java.lang.String.intern() internA( cb: Callback<string>): void; intern(): string; internP(): Promise<string>; // public boolean java.lang.String.isEmpty() isEmptyA( cb: Callback<object_t>): void; isEmpty(): object_t; isEmptyP(): Promise<object_t>; // public int java.lang.String.lastIndexOf(java.lang.String,int) lastIndexOfA(arg0: string_t, arg1: object_t, cb: Callback<object_t>): void; lastIndexOf(arg0: string_t, arg1: object_t): object_t; lastIndexOfP(arg0: string_t, arg1: object_t): Promise<object_t>; // public int java.lang.String.lastIndexOf(int,int) lastIndexOfA(arg0: object_t, arg1: object_t, cb: Callback<object_t>): void; lastIndexOf(arg0: object_t, arg1: object_t): object_t; lastIndexOfP(arg0: object_t, arg1: object_t): Promise<object_t>; // public int java.lang.String.lastIndexOf(java.lang.String) lastIndexOfA(arg0: string_t, cb: Callback<object_t>): void; lastIndexOf(arg0: string_t): object_t; lastIndexOfP(arg0: string_t): Promise<object_t>; // public int java.lang.String.lastIndexOf(int) lastIndexOfA(arg0: object_t, cb: Callback<object_t>): void; lastIndexOf(arg0: object_t): object_t; lastIndexOfP(arg0: object_t): Promise<object_t>; // public int java.lang.String.length() lengthA( cb: Callback<object_t>): void; length(): object_t; lengthP(): Promise<object_t>; // public boolean java.lang.String.matches(java.lang.String) matchesA(arg0: string_t, cb: Callback<object_t>): void; matches(arg0: string_t): object_t; matchesP(arg0: string_t): Promise<object_t>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public int java.lang.String.offsetByCodePoints(int,int) offsetByCodePointsA(arg0: object_t, arg1: object_t, cb: Callback<object_t>): void; offsetByCodePoints(arg0: object_t, arg1: object_t): object_t; offsetByCodePointsP(arg0: object_t, arg1: object_t): Promise<object_t>; // public boolean java.lang.String.regionMatches(boolean,int,java.lang.String,int,int) regionMatchesA(arg0: object_t, arg1: object_t, arg2: string_t, arg3: object_t, arg4: object_t, cb: Callback<object_t>): void; regionMatches(arg0: object_t, arg1: object_t, arg2: string_t, arg3: object_t, arg4: object_t): object_t; regionMatchesP(arg0: object_t, arg1: object_t, arg2: string_t, arg3: object_t, arg4: object_t): Promise<object_t>; // public boolean java.lang.String.regionMatches(int,java.lang.String,int,int) regionMatchesA(arg0: object_t, arg1: string_t, arg2: object_t, arg3: object_t, cb: Callback<object_t>): void; regionMatches(arg0: object_t, arg1: string_t, arg2: object_t, arg3: object_t): object_t; regionMatchesP(arg0: object_t, arg1: string_t, arg2: object_t, arg3: object_t): Promise<object_t>; // public java.lang.String java.lang.String.replace(java.lang.CharSequence,java.lang.CharSequence) replaceA(arg0: object_t, arg1: object_t, cb: Callback<string>): void; replace(arg0: object_t, arg1: object_t): string; replaceP(arg0: object_t, arg1: object_t): Promise<string>; // public java.lang.String java.lang.String.replace(char,char) replaceA(arg0: object_t, arg1: object_t, cb: Callback<string>): void; replace(arg0: object_t, arg1: object_t): string; replaceP(arg0: object_t, arg1: object_t): Promise<string>; // public java.lang.String java.lang.String.replaceAll(java.lang.String,java.lang.String) replaceAllA(arg0: string_t, arg1: string_t, cb: Callback<string>): void; replaceAll(arg0: string_t, arg1: string_t): string; replaceAllP(arg0: string_t, arg1: string_t): Promise<string>; // public java.lang.String java.lang.String.replaceFirst(java.lang.String,java.lang.String) replaceFirstA(arg0: string_t, arg1: string_t, cb: Callback<string>): void; replaceFirst(arg0: string_t, arg1: string_t): string; replaceFirstP(arg0: string_t, arg1: string_t): Promise<string>; // public java.lang.String[] java.lang.String.split(java.lang.String,int) splitA(arg0: string_t, arg1: object_t, cb: Callback<string[]>): void; split(arg0: string_t, arg1: object_t): string[]; splitP(arg0: string_t, arg1: object_t): Promise<string[]>; // public java.lang.String[] java.lang.String.split(java.lang.String) splitA(arg0: string_t, cb: Callback<string[]>): void; split(arg0: string_t): string[]; splitP(arg0: string_t): Promise<string[]>; // public boolean java.lang.String.startsWith(java.lang.String,int) startsWithA(arg0: string_t, arg1: object_t, cb: Callback<object_t>): void; startsWith(arg0: string_t, arg1: object_t): object_t; startsWithP(arg0: string_t, arg1: object_t): Promise<object_t>; // public boolean java.lang.String.startsWith(java.lang.String) startsWithA(arg0: string_t, cb: Callback<object_t>): void; startsWith(arg0: string_t): object_t; startsWithP(arg0: string_t): Promise<object_t>; // public java.lang.CharSequence java.lang.String.subSequence(int,int) subSequenceA(arg0: object_t, arg1: object_t, cb: Callback<object_t>): void; subSequence(arg0: object_t, arg1: object_t): object_t; subSequenceP(arg0: object_t, arg1: object_t): Promise<object_t>; // public java.lang.String java.lang.String.substring(int,int) substringA(arg0: object_t, arg1: object_t, cb: Callback<string>): void; substring(arg0: object_t, arg1: object_t): string; substringP(arg0: object_t, arg1: object_t): Promise<string>; // public java.lang.String java.lang.String.substring(int) substringA(arg0: object_t, cb: Callback<string>): void; substring(arg0: object_t): string; substringP(arg0: object_t): Promise<string>; // public char[] java.lang.String.toCharArray() toCharArrayA( cb: Callback<object_t[]>): void; toCharArray(): object_t[]; toCharArrayP(): Promise<object_t[]>; // public java.lang.String java.lang.String.toLowerCase(java.util.Locale) toLowerCaseA(arg0: object_t, cb: Callback<string>): void; toLowerCase(arg0: object_t): string; toLowerCaseP(arg0: object_t): Promise<string>; // public java.lang.String java.lang.String.toLowerCase() toLowerCaseA( cb: Callback<string>): void; toLowerCase(): string; toLowerCaseP(): Promise<string>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public java.lang.String java.lang.String.toUpperCase(java.util.Locale) toUpperCaseA(arg0: object_t, cb: Callback<string>): void; toUpperCase(arg0: object_t): string; toUpperCaseP(arg0: object_t): Promise<string>; // public java.lang.String java.lang.String.toUpperCase() toUpperCaseA( cb: Callback<string>): void; toUpperCase(): string; toUpperCaseP(): Promise<string>; // public java.lang.String java.lang.String.trim() trimA( cb: Callback<string>): void; trim(): string; trimP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: object_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: object_t): void; waitP(arg0: object_t, arg1: object_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module String { export interface Static { CASE_INSENSITIVE_ORDER: object_t; class: Java.Object; new (arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t): java.lang.String; new (arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: string_t): java.lang.String; new (arg0: object_array_t, arg1: object_t, arg2: object_t, arg3: object_t): java.lang.String; new (arg0: object_array_t, arg1: object_t, arg2: object_t): java.lang.String; new (arg0: object_array_t, arg1: object_t, arg2: object_t): java.lang.String; new (arg0: object_array_t, arg1: object_t, arg2: object_t): java.lang.String; new (arg0: object_array_t, arg1: object_t): java.lang.String; new (arg0: object_array_t, arg1: string_t): java.lang.String; new (arg0: object_array_t, arg1: object_t): java.lang.String; new (arg0: object_t): java.lang.String; new (arg0: object_t): java.lang.String; new (arg0: string_t): java.lang.String; new (arg0: object_array_t): java.lang.String; new (arg0: object_array_t): java.lang.String; new (): java.lang.String; // public static java.lang.String java.lang.String.copyValueOf(char[],int,int) copyValueOfA(arg0: object_array_t, arg1: object_t, arg2: object_t, cb: Callback<string>): void; copyValueOf(arg0: object_array_t, arg1: object_t, arg2: object_t): string; copyValueOfP(arg0: object_array_t, arg1: object_t, arg2: object_t): Promise<string>; // public static java.lang.String java.lang.String.copyValueOf(char[]) copyValueOfA(arg0: object_array_t, cb: Callback<string>): void; copyValueOf(arg0: object_array_t): string; copyValueOfP(arg0: object_array_t): Promise<string>; // public static java.lang.String java.lang.String.format(java.util.Locale,java.lang.String,java.lang.Object...) formatA(arg0: object_t, arg1: string_t, arg2: object_array_t, cb: Callback<string>): void; format(arg0: object_t, arg1: string_t, ...arg2: object_t[]): string; format(arg0: object_t, arg1: string_t, arg2: object_array_t): string; formatP(arg0: object_t, arg1: string_t, ...arg2: object_t[]): Promise<string>; formatP(arg0: object_t, arg1: string_t, arg2: object_array_t): Promise<string>; // public static java.lang.String java.lang.String.format(java.lang.String,java.lang.Object...) formatA(arg0: string_t, arg1: object_array_t, cb: Callback<string>): void; format(arg0: string_t, ...arg1: object_t[]): string; format(arg0: string_t, arg1: object_array_t): string; formatP(arg0: string_t, ...arg1: object_t[]): Promise<string>; formatP(arg0: string_t, arg1: object_array_t): Promise<string>; // public static java.lang.String java.lang.String.join(java.lang.CharSequence,java.lang.CharSequence...) joinA(arg0: object_t, arg1: object_array_t, cb: Callback<string>): void; join(arg0: object_t, ...arg1: object_t[]): string; join(arg0: object_t, arg1: object_array_t): string; joinP(arg0: object_t, ...arg1: object_t[]): Promise<string>; joinP(arg0: object_t, arg1: object_array_t): Promise<string>; // public static java.lang.String java.lang.String.join(java.lang.CharSequence,java.lang.Iterable<? extends java.lang.CharSequence>) joinA(arg0: object_t, arg1: object_t, cb: Callback<string>): void; join(arg0: object_t, arg1: object_t): string; joinP(arg0: object_t, arg1: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(char[],int,int) valueOfA(arg0: object_array_t, arg1: object_t, arg2: object_t, cb: Callback<string>): void; valueOf(arg0: object_array_t, arg1: object_t, arg2: object_t): string; valueOfP(arg0: object_array_t, arg1: object_t, arg2: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(java.lang.Object) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(char[]) valueOfA(arg0: object_array_t, cb: Callback<string>): void; valueOf(arg0: object_array_t): string; valueOfP(arg0: object_array_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(boolean) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(long) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(int) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(float) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(double) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(char) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; } } } // #### `function smellsLikeJavaObject(e: any)` // Returns true if the obj 'smells' like a Java object. // This is a light-weight test that will return false when `e` is clearly not a Java object, // but it may have false positives. To be certain, use `isJavaObject(e)` or `instanceOf(e, classname)` instead. function smellsLikeJavaObject(e: any): boolean { return _.isObject(e) && !_.isArray(e) ; } // #### `function isJavaObject(e: any)` // Returns true if the obj is a Java object. // Useful for determining the runtime type of object_t returned by many java methods. export function isJavaObject(e: any): boolean { return smellsLikeJavaObject(e) && _java.instanceOf(e, 'java.lang.Object'); } } // module Java
the_stack
import * as extensionFunctions from './extensionFunctions'; import * as path from 'path'; import { ViewColumn, WebviewPanel, Disposable, Uri, workspace, window, ExtensionContext } from 'vscode'; import { DIDACT_DEFAULT_URL } from './utils'; import { DEFAULT_TITLE_VALUE, didactManager, VIEW_TYPE } from './didactManager'; import * as commandHandler from './commandHandler'; export class DidactPanel { // public for testing purposes public _panel: WebviewPanel | undefined; private _disposables: Disposable[] = []; private currentHtml : string | undefined = undefined; private didactUriPath : Uri | undefined = undefined; private defaultTitle = DEFAULT_TITLE_VALUE; private isAsciiDoc = false; private _disposed = false; public visible = false; public constructor(uri?: Uri ) { this.didactUriPath = uri; didactManager.add(this); } public initWebviewPanel(viewColumn: ViewColumn, inpath?: Uri | undefined): DidactPanel | undefined { const extPath = didactManager.getExtensionPath(); if (!extPath) { console.error(`Error: Extension context not set on Didact manager`); return undefined; } // Otherwise, create a new panel. const localResourceRoots = [Uri.file(path.resolve(extPath, 'media'))]; if (inpath) { const dirName = path.dirname(inpath.fsPath); localResourceRoots.push(Uri.file(dirName)); } const localIconPath = Uri.file(path.resolve(extPath, 'icon/logo.svg')); const iconDirPath = path.dirname(localIconPath.fsPath); localResourceRoots.push(Uri.file(iconDirPath)); const panel = window.createWebviewPanel( VIEW_TYPE, this.defaultTitle, viewColumn, { // Enable javascript in the webview enableScripts: true, // And restrict the webview to only loading content from known directories localResourceRoots: localResourceRoots, // persist the state retainContextWhenHidden: true } ); panel.iconPath = localIconPath; return this.attachWebviewPanel(panel); } public attachWebviewPanel(webviewPanel: WebviewPanel): DidactPanel { this._panel = webviewPanel; this.setVisible(webviewPanel.active); this._panel.onDidDispose(() => { this.dispose(); }, this, this._disposables); return this; } private setVisible(flag: boolean) { didactManager.resetVisibility(); this.visible = flag; } public static revive(context: ExtensionContext, webviewPanel: WebviewPanel, oldBody? : string, oldUri? : string): DidactPanel { didactManager.setContext(context); let panel : DidactPanel; if (oldUri) { const toUri = Uri.parse(oldUri); panel = new DidactPanel(toUri); } else { panel = new DidactPanel(); } panel.attachWebviewPanel(webviewPanel); panel.handleEvents(); panel.configure(); if (oldBody) { panel.setHtml(oldBody); } return panel; } public handleEvents() : void { this._panel?.webview.onDidReceiveMessage( async message => { console.log(message); switch (message.command) { case 'update': if (message.text) { this.currentHtml = message.text; } return; case 'link': if (message.text) { try { await commandHandler.processInputs(message.text, didactManager.getExtensionPath()); } catch (error) { window.showErrorMessage(`Didact was unable to call commands: ${message.text}: ${error}`); } } return; } }, null, this._disposables ); this._panel?.onDidChangeViewState( async (e) => { this.setVisible(e.webviewPanel.active); await this.sendSetStateMessage(); }); } public async sendSetStateMessage() : Promise<void> { if (!this._panel || this._disposed) { return; } const sendCommand = `"command": "setState"`; let sendUri = undefined; if (this.didactUriPath) { const encodedUri = encodeURI(this.didactUriPath.toString()); sendUri = `"oldUri" : "${encodedUri}"`; } let jsonMsg = `{ ${sendCommand} }`; if (sendUri) { jsonMsg = `{ ${sendCommand}, ${sendUri} }`; } this._panel.webview.postMessage(jsonMsg); } public async refreshPanel() : Promise<void> { this.configure(true); } async configure(flag = false): Promise<void> { this._update(flag); await this.sendSetStateMessage(); } public setHtml(html : string) : void { if (this._panel) { this._panel.webview.html = html; } } public getCurrentHTML() : string | undefined { return this._panel?.webview.html; } public getCurrentTitle() : string | undefined { return this._panel?.title; } public getDidactUriPath(): Uri | undefined { return this.didactUriPath; } public setIsAsciiDoc(flag : boolean): void { this.isAsciiDoc = flag; } // public for testing purposes public getDidactDefaultTitle() : string | undefined { return this.defaultTitle; } public setDidactUriPath(inpath : Uri | undefined): void { this.didactUriPath = inpath; if (inpath) { const tempFilename = path.basename(inpath.fsPath); this.defaultTitle = tempFilename; } this._update(true); } private async _update(flag: boolean) { if (flag) { // reset based on vscode link const content = await extensionFunctions.getWebviewContent(); if (content) { this.currentHtml = this.wrapDidactContent(content); } } if (this.currentHtml) { if (this._panel && this._panel.webview) { this._panel.webview.html = this.currentHtml; const firstHeading : string | undefined = this.getFirstHeadingText(); if (firstHeading && firstHeading.trim().length > 0) { this.defaultTitle = firstHeading; } this._panel.title = this.defaultTitle; } } await this.sendSetStateMessage(); } wrapDidactContent(didactHtml: string | undefined) : string | undefined { if (!didactHtml || this._disposed) { return; } const nonce = this.getNonce(); // Base uri to support images const didactUri : Uri = this.didactUriPath as Uri; let uriBaseHref = undefined; if (didactUri && this._panel) { try { const didactUriPath = path.dirname(didactUri.fsPath); const uriBase = this._panel.webview.asWebviewUri(Uri.file(didactUriPath)).toString(); uriBaseHref = `<base href="${uriBase}${uriBase.endsWith('/') ? '' : '/'}"/>`; } catch (error) { console.error(error); } } const extPath = didactManager.getExtensionPath(); if (!extPath) { console.error(`Error: Extension context not set on Didact manager`); return undefined; } // Local path to main script run in the webview const scriptPathOnDisk = Uri.file( path.resolve(extPath, 'media', 'main.js') ); // And the uri we use to load this script in the webview const scriptUri = scriptPathOnDisk.with({ scheme: 'vscode-resource' }); // the cssUri is our path to the stylesheet included in the security policy const cssPathOnDisk = Uri.file( path.resolve(extPath, 'media', 'webviewslim.css') ); const cssUri = cssPathOnDisk.with({ scheme: 'vscode-resource' }); // this css holds our overrides for both asciidoc and markdown html const cssUriHtml = `<link rel="stylesheet" href="${cssUri}"/>`; // process the stylesheet details for asciidoc or markdown-based didact files const stylesheetHtml = this.produceStylesheetHTML(cssUriHtml); let cspSrc = undefined; if (this._panel) { cspSrc = this._panel.webview.cspSource; } else { console.error(`Error: Content Security Policy not set on webview`); return undefined; } let metaHeader = `<meta charset="UTF-8"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' data: https: http: blob: ${cspSrc}; media-src vscode-resource: https: data:; script-src 'nonce-${nonce}' https:; style-src 'unsafe-inline' ${this._panel.webview.cspSource} https: data:; font-src ${this._panel.webview.cspSource} https: data:; object-src 'none';"/>`; if (uriBaseHref) { metaHeader += `\n${uriBaseHref}\n`; } return `<!DOCTYPE html> <html lang="en"> <head> ${metaHeader} <title>Didact Tutorial</title>` + stylesheetHtml + `<script defer="true" src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script> </head> <body class="content"> <div class="tutorialContent">` + didactHtml + `</div> <script nonce="${nonce}" src="${scriptUri}"/> </body> </html>`; } produceStylesheetHTML(cssUriHtml : string) : string { let stylesheetHtml = ''; if (this.isAsciiDoc) { // use asciidoctor-default.css with import from // https://cdn.jsdelivr.net/gh/asciidoctor/asciidoctor@v2.0.10/data/stylesheets/asciidoctor-default.css const adUriHtml = `<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/asciidoctor/asciidoctor@v2.0.10/data/stylesheets/asciidoctor-default.css"/>`; stylesheetHtml = `${adUriHtml}\n ${cssUriHtml}\n`; } else { // use bulma.min.css as the default stylesheet for markdown from https://bulma.io/ const bulmaCssHtml = `<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.8.0/css/bulma.min.css"/>`; stylesheetHtml = `${bulmaCssHtml}\n ${cssUriHtml}\n`; } return stylesheetHtml; } getNonce() : string { let text = ''; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < 32; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } public async dispose(): Promise<void> { if (this._disposed) { return; } this._disposed = true; didactManager.remove(this); // Clean up our resources if (this._panel) { this._panel.dispose(); } while (this._disposables.length) { const x = this._disposables.pop(); if (x) { x.dispose(); } } } getFirstHeadingText() : string | undefined { const h1 = extensionFunctions.collectElements('h1', this._panel?.webview.html); if (h1 && h1.length > 0 && h1[0].innerText) { return h1[0].innerText; } const h2 = extensionFunctions.collectElements('h2', this._panel?.webview.html); if (h2 && h2.length > 0 && h2[0].innerText) { return h2[0].innerText; } return undefined; } getColumn() : ViewColumn | undefined { if (this._panel) { return this._panel.viewColumn; } return undefined; } public async postMessage(message: string): Promise<void> { if (!this._panel) { return; } const jsonMsg:string = "{ \"command\": \"sendMessage\", \"data\": \"" + message + "\"}"; this._panel.webview.postMessage(jsonMsg); } public async postRequirementsResponseMessage(requirementName: string, result: boolean): Promise<void> { if (!this._panel) { return; } const jsonMsg:string = "{ \"command\": \"requirementCheck\", \"requirementName\": \"" + requirementName + "\", \"result\": \"" + result + "\"}"; this._panel.webview.postMessage(jsonMsg); await this.sendSetStateMessage(); } async postNamedSimpleMessage(msg: string): Promise<void> { if (!this._panel) { return; } const jsonMsg = `{ "command" : "${msg}"}`; this._panel.webview.postMessage(jsonMsg); } public async postTestAllRequirementsMessage(): Promise<void> { this.postNamedSimpleMessage("allRequirementCheck"); } public async postCollectAllRequirementsMessage(): Promise<void> { this.postNamedSimpleMessage("returnRequirements"); } public async postCollectAllCommandIdsMessage(): Promise<void> { this.postNamedSimpleMessage("returnCommands"); } public hardReset(): void { const configuredUri : string | undefined = workspace.getConfiguration().get(DIDACT_DEFAULT_URL); if (configuredUri) { const defaultUri = Uri.parse(configuredUri); didactManager.active()?.setDidactUriPath(defaultUri); } didactManager.active()?._update(true); } public async sendScrollToHeadingMessage(tag : string, headingText: string) : Promise<void> { if (!this._panel || this._disposed) { return; } const jsonMsg = `{ "command": "scrollToHeading", "tag" : "${tag}", "headingText" : "${headingText}" }`; await this._panel.webview.postMessage(jsonMsg); } }
the_stack
/// <reference path="../geom/Point.ts" /> namespace egret { export interface DisplayObject { addEventListener<Z>(type: "touchMove" | "touchBegin" | "touchEnd" | "touchCancel" | "touchTap" | "touchReleaseOutside" | "touchRollOut"| "touchRollOver" , listener: (this: Z, e: TouchEvent) => void, thisObject: Z, useCapture?: boolean, priority?: number); addEventListener(type: string, listener: Function, thisObject: any, useCapture?: boolean, priority?: number); } let localPoint: Point = new Point(); /** * The TouchEvent class lets you handle events on devices that detect user contact with the device (such as a finger * on a touch screen).When a user interacts with a device such as a mobile phone or tablet with a touch screen, the * user typically touches the screen with his or her fingers or a pointing device. You can develop applications that * respond to basic touch events (such as a single finger tap) with the TouchEvent class. Create event listeners using * the event types defined in this class. * Note: When objects are nested on the display list, touch events target the deepest possible nested object that is * visible in the display list. This object is called the target node. To have a target node's ancestor (an object * containing the target node in the display list) receive notification of a touch event, use EventDispatcher.addEventListener() * on the ancestor node with the type parameter set to the specific touch event you want to detect. * * @version Egret 2.4 * @platform Web,Native * @includeExample egret/events/TouchEvent.ts * @language en_US */ /** * 使用 TouchEvent 类,您可以处理设备上那些检测用户与设备之间的接触的事件。 * 当用户与带有触摸屏的移动电话或平板电脑等设备交互时,用户通常使用手指或指针设备接触屏幕。可使用 TouchEvent * 类开发响应基本触摸事件(如单个手指点击)的应用程序。使用此类中定义的事件类型创建事件侦听器。 * 注意:当对象嵌套在显示列表中时,触摸事件的目标将是显示列表中可见的最深的可能嵌套对象。 * 此对象称为目标节点。要使目标节点的祖代(祖代是一个包含显示列表中所有目标节点的对象,从舞台到目标节点的父节点均包括在内) * 接收触摸事件的通知,请对祖代节点使用 EventDispatcher.on() 并将 type 参数设置为要检测的特定触摸事件。 * * @version Egret 2.4 * @platform Web,Native * @includeExample egret/events/TouchEvent.ts * @language zh_CN */ export class TouchEvent extends Event { /** * Dispatched when the user touches the device, and is continuously dispatched until the point of contact is removed. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 当用户触碰设备时进行调度,而且会连续调度,直到接触点被删除。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static TOUCH_MOVE: "touchMove" = "touchMove"; /** * Dispatched when the user first contacts a touch-enabled device (such as touches a finger to a mobile phone or tablet with a touch screen). * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 当用户第一次触摸启用触摸的设备时(例如,用手指触摸配有触摸屏的移动电话或平板电脑)调度。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static TOUCH_BEGIN: "touchBegin" = "touchBegin"; /** * Dispatched when the user removes contact with a touch-enabled device (such as lifts a finger off a mobile phone * or tablet with a touch screen). * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 当用户移除与启用触摸的设备的接触时(例如,将手指从配有触摸屏的移动电话或平板电脑上抬起)调度。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static TOUCH_END: "touchEnd" = "touchEnd"; /** * Dispatched when an event of some kind occurred that canceled the touch. * Such as the eui.Scroller will dispatch 'TOUCH_CANCEL' when it start move, the 'TOUCH_END' and 'TOUCH_TAP' will not be triggered. * @version Egret 3.0.1 * @platform Web,Native * @language en_US */ /** * 由于某个事件取消了触摸时触发。比如 eui.Scroller 在开始滚动后会触发 'TOUCH_CANCEL' 事件,不再触发后续的 'TOUCH_END' 和 'TOUCH_TAP' 事件 * @version Egret 3.0.1 * @platform Web,Native * @language zh_CN */ public static TOUCH_CANCEL: "touchCancel" = "touchCancel"; /** * Dispatched when the user lifts the point of contact over the same DisplayObject instance on which the contact * was initiated on a touch-enabled device. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 当用户在触摸设备上与开始触摸的同一 DisplayObject 实例上抬起接触点时调度。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static TOUCH_TAP: "touchTap" = "touchTap"; /** * Dispatched when the user lifts the point of contact over the different DisplayObject instance on which the contact * was initiated on a touch-enabled device (such as presses and releases a finger from a single point over a display * object on a mobile phone or tablet with a touch screen). * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 当用户在触摸设备上与开始触摸的不同 DisplayObject 实例上抬起接触点时调度。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static TOUCH_RELEASE_OUTSIDE: "touchReleaseOutside" = "touchReleaseOutside"; /** * Creates an Event object that contains information about touch events. * @param type The type of the event, accessible as Event.type. * @param bubbles Determines whether the Event object participates in the bubbling stage of the event flow. The default value is false. * @param cancelable Determines whether the Event object can be canceled. The default values is false. * @param stageX The horizontal coordinate at which the event occurred in global Stage coordinates. * @param stageY The vertical coordinate at which the event occurred in global Stage coordinates. * @param touchPointID A unique identification number assigned to the touch point. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 创建一个 TouchEvent 对象,其中包含有关Touch事件的信息 * @param type 事件的类型,可以作为 Event.type 访问。 * @param bubbles 确定 Event 对象是否参与事件流的冒泡阶段。默认值为 false。 * @param cancelable 确定是否可以取消 Event 对象。默认值为 false。 * @param stageX 事件发生点在全局舞台坐标系中的水平坐标 * @param stageY 事件发生点在全局舞台坐标系中的垂直坐标 * @param touchPointID 分配给触摸点的唯一标识号 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public constructor(type: string, bubbles?: boolean, cancelable?: boolean, stageX?: number, stageY?: number, touchPointID?: number) { super(type, bubbles, cancelable); this.$initTo(stageX, stageY, touchPointID); } /** * @private */ $initTo(stageX: number, stageY: number, touchPointID: number): void { this.touchPointID = +touchPointID || 0; this.$stageX = +stageX || 0; this.$stageY = +stageY || 0; } /** * @private */ $stageX: number; /** * The horizontal coordinate at which the event occurred in global Stage coordinates. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 事件发生点在全局舞台坐标中的水平坐标。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get stageX(): number { return this.$stageX; } /** * @private */ $stageY: number; /** * The vertical coordinate at which the event occurred in global Stage coordinates. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 事件发生点在全局舞台坐标中的垂直坐标。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get stageY(): number { return this.$stageY; } private _localX: number; /** * The horizontal coordinate at which the event occurred relative to the display object. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 事件发生点相对于所属显示对象的水平坐标。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get localX(): number { if (this.targetChanged) { this.getLocalXY(); } return this._localX; } private _localY: number; /** * The vertical coordinate at which the event occurred relative to the display object. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 事件发生点相对于所属显示对象的垂直坐标。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public get localY(): number { if (this.targetChanged) { this.getLocalXY(); } return this._localY; } private targetChanged: boolean = true; /** * @private */ private getLocalXY(): void { this.targetChanged = false; let m = (<DisplayObject>this.$target).$getInvertedConcatenatedMatrix(); m.transformPoint(this.$stageX, this.$stageY, localPoint); this._localX = localPoint.x; this._localY = localPoint.y; } $setTarget(target: any): boolean { this.$target = target; this.targetChanged = !!target; return true; } /** * A unique identification number assigned to the touch point. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 分配给触摸点的唯一标识号 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public touchPointID: number; /** * Instructs Egret runtime to render after processing of this event completes, if the display list has been modified. * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 如果已修改显示列表,调用此方法将会忽略帧频限制,在此事件处理完成后立即重绘屏幕。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public updateAfterEvent(): void { sys.$requestRenderingFlag = true; } /** * Whether the touch is pressed (true) or not pressed (false). * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 表示触摸已按下 (true) 还是未按下 (false)。 * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public touchDown: boolean = false; /** * uses a specified target to dispatchEvent an event. Using this method can reduce the number of * reallocate event objects, which allows you to get better code execution performance. * @param target the event target * @param type The type of the event, accessible as Event.type. * @param bubbles Determines whether the Event object participates in the bubbling stage of the event flow. The default value is false. * @param cancelable Determines whether the Event object can be canceled. The default values is false. * @param stageX The horizontal coordinate at which the event occurred in global Stage coordinates. * @param stageY The vertical coordinate at which the event occurred in global Stage coordinates. * @param touchPointID A unique identification number (as an int) assigned to the touch point. * * @see egret.Event.create() * @see egret.Event.release() * * @version Egret 2.4 * @platform Web,Native * @language en_US */ /** * 使用指定的EventDispatcher对象来抛出Event事件对象。抛出的对象将会缓存在对象池上,供下次循环复用。 * @param target 派发事件目标 * @param type 事件的类型,可以作为 Event.type 访问。 * @param bubbles 确定 Event 对象是否参与事件流的冒泡阶段。默认值为 false。 * @param cancelable 确定是否可以取消 Event 对象。默认值为 false。 * @param stageX 事件发生点在全局舞台坐标系中的水平坐标 * @param stageY 事件发生点在全局舞台坐标系中的垂直坐标 * @param touchPointID 分配给触摸点的唯一标识号 * * @see egret.Event.create() * @see egret.Event.release() * * @version Egret 2.4 * @platform Web,Native * @language zh_CN */ public static dispatchTouchEvent(target: IEventDispatcher, type: string, bubbles?: boolean, cancelable?: boolean, stageX?: number, stageY?: number, touchPointID?: number, touchDown: boolean = false): boolean { if (!bubbles && !target.hasEventListener(type)) { return true; } let event: TouchEvent = Event.create(TouchEvent, type, bubbles, cancelable); event.$initTo(stageX, stageY, touchPointID); event.touchDown = touchDown; let result = target.dispatchEvent(event); Event.release(event); return result; } } }
the_stack
/// <reference path='accountsPlugin.ts'/> module HawkularAccounts { export class OrganizationMembershipController { public static $inject = ['$log', '$rootScope', '$scope', '$routeParams', '$modal', 'HawkularAccount', 'NotificationsService']; // backend data related to this controller public memberships: Array<IOrganizationMembership>; public joinRequests: Array<IJoinRequest>; public organization: IOrganization; public pending: Array<IInvitation>; public role: IRole; public possibleRoles: Array<Role>; // state control, for easier UI consumption public loading: boolean; public loadingJoinRequests: boolean; public foundOrganization: boolean; public isAllowedToInvite: boolean = false; public isAllowedToListPending: boolean = false; public isAllowedToTransferOrganization: boolean = false; public isAllowedToChangeRoleOfMembers: boolean = false; public isAllowedToApproveMember: boolean = false; public isOrganization: boolean = false; public membershipsToUpdate: { [id: string]: PersistenceState; } = {}; public joinRequestsToUpdate: { [id: string]: PersistenceState; } = {}; constructor(private $log: ng.ILogService, private $rootScope: any, private $scope: any, private $routeParams: any, private $modal: any, private HawkularAccount: any, private NotificationsService: INotificationsService) { this.foundOrganization = false; this.prepareListeners(); this.loadData(); if (this.$rootScope.currentPersona) { this.isOrganization = this.$rootScope.currentPersona.id !== this.$rootScope.userDetails.id; } } public prepareListeners(): void { let organizationId = this.$routeParams.organizationId; this.$scope.$on('OrganizationLoaded', () => { this.loadMemberships(organizationId); this.loadJoinRequests(organizationId); }); this.$scope.$on('PermissionToListPendingLoaded', () => { if (this.isAllowedToListPending) { this.loadPendingInvitations(organizationId); } }); this.$scope.$on('PermissionToTransferOrganizationLoaded', () => { if (this.isAllowedToTransferOrganization) { this.possibleRoles.push(new Role('Owner')); } }); this.$scope.$on('OwnershipChanged', () => { this.loadPossibleRoles(); }); this.$scope.$on('JoinRequestApproved', () => { this.loadMemberships(organizationId); }); this.$rootScope.$on('SwitchedPersona', (event: any, persona: IPersona) => { this.isOrganization = persona.id !== this.$rootScope.userDetails.id; }); } public loadData(): void { this.loading = true; this.loadingJoinRequests = true; let organizationId = this.$routeParams.organizationId; this.loadOrganization(organizationId); this.loadPermissionToInvite(organizationId); this.loadPermissionToListPending(organizationId); this.loadPermissionToChangeRoleOfMembers(organizationId); this.loadPermissionToApproveMember(organizationId); this.loadPossibleRoles(); } public loadPossibleRoles(): void { let organizationId = this.$routeParams.organizationId; this.possibleRoles = [ new Role('Monitor'), new Role('Operator'), new Role('Maintainer'), new Role('Deployer'), new Role('Administrator'), new Role('Auditor'), new Role('SuperUser') ]; this.loadPermissionToTransferOrganization(organizationId); } public loadOrganization(organizationId: string): void { this.organization = this.HawkularAccount.Organization.get({ id: organizationId }, () => { this.foundOrganization = true; this.$scope.$broadcast('OrganizationLoaded'); }, (error: IErrorPayload) => { this.$log.warn(`Error while loading the organization: ${error.data.message}`); this.loading = false; } ); } public loadMemberships(organizationId: string): void { this.memberships = this.HawkularAccount.OrganizationMembership.query({ organizationId: organizationId }, () => { this.loading = false; this.$log.debug(`Finished loading members. Size: ${this.memberships.length}`); }, (error: IErrorPayload) => { this.NotificationsService.error('List of memberships could NOT be retrieved.'); this.$log.warn(`List of memberships could NOT be retrieved: ${error.data.message}`); this.loading = false; } ); } public loadPendingInvitations(organizationId: string): void { this.pending = this.HawkularAccount.OrganizationInvitation.query({ organizationId: organizationId }, () => { this.$log.debug(`Finished loading pending invitations. Size: ${this.pending.length}`); }, (error: IErrorPayload) => { this.$log.debug(`Error while trying to load the pending invitations: ${error.data.message}`); } ); } public loadPermissionToInvite(organizationId: string): void { const operationName: string = 'organization-invite'; this.loadPermission(organizationId, operationName, (response: IPermissionResponse) => { this.isAllowedToInvite = response.permitted; this.$log.debug(`Finished checking if we can invite other users. Response: ${response.permitted}`); }, (error: IErrorPayload) => { this.$log.debug(`Error checking if we can invite other users. Response: ${error.data.message}`); } ); } public loadPermissionToListPending(organizationId: string): void { const operationName: string = 'organization-list-invitations'; this.loadPermission(organizationId, operationName, (response: IPermissionResponse) => { this.isAllowedToListPending = response.permitted; this.$scope.$broadcast('PermissionToListPendingLoaded'); this.$log.debug(`Finished checking if we can list the pending invitations. Response: ${response.permitted}`); }, (error: IErrorPayload) => { this.$log.debug(`Error checking if we can list the pending invitations. Response: ${error.data.message}`); } ); } public loadPermissionToApproveMember(organizationId: string): void { const operationName: string = 'organization-invite'; this.loadPermission(organizationId, operationName, (response: IPermissionResponse) => { this.isAllowedToApproveMember = response.permitted; this.$scope.$broadcast('PermissionToListPendingLoaded'); this.$log.debug(`Finished checking if we can approve join requests. Response: ${response.permitted}`); }, (error: IErrorPayload) => { this.$log.debug(`Error checking if we can approve join requests. Response: ${error.data.message}`); } ); } public loadPermissionToTransferOrganization(organizationId: string): void { const operationName: string = 'organization-transfer'; this.loadPermission(organizationId, operationName, (response: IPermissionResponse) => { this.isAllowedToTransferOrganization = response.permitted; this.$scope.$broadcast('PermissionToTransferOrganizationLoaded'); this.$log.debug(`Finished checking if we can transfer this organization. Response: ${response.permitted}`); }, (error: IErrorPayload) => { this.$log.debug(`Error checking if we can transfer this organization. Response: ${error.data.message}`); } ); } public loadPermissionToChangeRoleOfMembers(organizationId: string): void { const operationName: string = 'organization-change-role-of-members'; this.loadPermission(organizationId, operationName, (response: IPermissionResponse) => { this.isAllowedToChangeRoleOfMembers = response.permitted; this.$log.debug(`Finished checking if we can change the role of members. Response: ${response.permitted}`); }, (error: IErrorPayload) => { this.$log.debug(`Error checking if we can change the role of members. Response: ${error.data.message}`); } ); } public loadPermission( resourceId: string, operationName: string, successCallback: (response: IPermissionResponse) => void, errorCallback: (error: IErrorPayload) => void ): void { return this.HawkularAccount.Permission.get( { resourceId: resourceId, operation: operationName }, successCallback, errorCallback ); } public loadJoinRequests(organizationId) { this.joinRequests = this.HawkularAccount.OrganizationJoinRequest.query({ organizationId: organizationId }, () => { this.loadingJoinRequests = false; }, (error: IErrorPayload) => { this.$log.debug(`Error loading the join requests for this organization. Response: ${error.data.message}`); }); } public showInviteModal(): void { let createFormModal = this.$modal.open({ controller: 'HawkularAccounts.OrganizationInviteModalController as inviteModal', templateUrl: 'plugins/accounts/html/organization-invite.html' }); createFormModal.result.then((emails: Array<string>) => { emails.forEach((email) => { let invitation: IInvitation = new Invitation(email, new Role('Monitor')); this.pending.unshift(invitation); }); }); } public changeRole(membership: IOrganizationMembership): void { if (membership.role === null) { return; } if (membership.role.name === 'Owner') { this.transferOwnership(membership); return; } this.membershipsToUpdate[membership.id] = PersistenceState.PERSISTING; membership.$update(null, (response: ISuccessPayload) => { this.membershipsToUpdate[membership.id] = PersistenceState.SUCCESS; // just for a moment, until we re-evaluate if the user still has the permission this.isAllowedToChangeRoleOfMembers = false; this.loadPermissionToChangeRoleOfMembers(this.organization.id); }, (error: IErrorPayload) => { this.membershipsToUpdate[membership.id] = PersistenceState.ERROR; this.$log.debug(`Error changing role for membership. Response: ${error.data.message}`); }); } public transferOwnership(membership: IOrganizationMembership): void { if (!this.isAllowedToTransferOrganization) { this.NotificationsService.error('Error: You don\'t have the permissions to transfer this organization.'); return; } let transferOrgModal = this.$modal.open({ controller: 'HawkularAccounts.OrganizationTransferModalController as transferModal', templateUrl: 'plugins/accounts/html/organization-transfer-modal.html', resolve: { organization: () => this.organization, transferTo: () => membership.member } }); transferOrgModal.result.then(() => { this.organization.owner = membership.member; this.membershipsToUpdate[membership.id] = PersistenceState.PERSISTING; this.organization.$update(null, (response: IOrganization) => { this.$scope.$broadcast('OwnershipChanged'); this.membershipsToUpdate[membership.id] = PersistenceState.SUCCESS; this.organization = response; // now, we refresh the memberships we have, to make sure we have the most up to date IDs this.memberships = []; this.loading = true; this.loadMemberships(this.organization.id); }, (error: IErrorPayload) => { this.membershipsToUpdate[membership.id] = PersistenceState.ERROR; this.$log.debug(`Error changing role for membership. Response: ${error.data.message}`); }); }, () => { // the modal was dismissed, get the original data for this membership membership.$get(); }); } public approveRequest(joinRequest: IJoinRequest): void { joinRequest.decision = 'ACCEPT'; this.updateJoinRequest(joinRequest, (response: IJoinRequest) => { this.joinRequestsToUpdate[joinRequest.id] = PersistenceState.SUCCESS; this.NotificationsService.success('Join request successfully approved.'); this.joinRequests.splice(this.joinRequests.indexOf(joinRequest), 1); this.$scope.$broadcast('JoinRequestApproved'); }, (error: IErrorPayload) => { this.joinRequestsToUpdate[joinRequest.id] = PersistenceState.ERROR; this.NotificationsService.error('An error occurred while trying to accept the join request.'); this.$log.error(`Error while trying to accept join request: ${error.data.message}`); }); } public rejectRequest(joinRequest: IJoinRequest): void { joinRequest.decision = 'REJECT'; this.updateJoinRequest(joinRequest, (response: IJoinRequest) => { this.joinRequestsToUpdate[joinRequest.id] = PersistenceState.SUCCESS; this.NotificationsService.success('Join request successfully rejected.'); this.joinRequests.splice(this.joinRequests.indexOf(joinRequest), 1); }, (error: IErrorPayload) => { this.joinRequestsToUpdate[joinRequest.id] = PersistenceState.ERROR; this.NotificationsService.error('An error occurred while trying to reject the join request.'); this.$log.error(`Error while trying to reject join request: ${error.data.message}`); }); } public updateJoinRequest(joinRequest: IJoinRequest, successCallback: (response: IJoinRequest) => void, errorCallback: (error: IErrorPayload) => void): void { joinRequest.joinRequestId = joinRequest.id; this.joinRequestsToUpdate[joinRequest.id] = PersistenceState.PERSISTING; joinRequest.$update({ organizationId: this.organization.id }, successCallback, errorCallback); } } export class OrganizationInviteModalController { public static $inject = ['$log', '$routeParams', '$modalInstance', 'HawkularAccount', 'NotificationsService']; public invitation: IInvitationRequest; constructor(private $log: ng.ILogService, private $routeParams: any, private $modalInstance: any, private HawkularAccount: any, private NotificationsService: INotificationsService) { this.invitation = new HawkularAccount.OrganizationInvitation({ organizationId: $routeParams.organizationId }); } public cancel(): void { this.$modalInstance.dismiss('cancel'); } public invite(): void { this.invitation.$save(() => { this.NotificationsService.success('Invitation successfully sent.'); this.$modalInstance.close( this.invitation.emails .split(/[,\s]/) .filter((entry: string) => { return entry && entry.length > 0; } ) ); }, (error: IErrorPayload) => { this.NotificationsService.error('An error occurred while trying to send the invitations.'); this.$log.debug(`Error while trying to send invitations: ${error.data.message}`); this.$modalInstance.close('error'); }); } } export class OrganizationTransferModalController { public static $inject = ['$log', '$routeParams', '$modalInstance', 'organization', 'transferTo']; constructor(private $log: ng.ILogService, private $routeParams: any, private $modalInstance: any, private organization: IOrganization, private transferTo: IPersona) { this.$log.debug('Organization received: '); this.$log.debug(organization); } public cancel(): void { this.$modalInstance.dismiss('cancel'); } public transfer(): void { this.$modalInstance.close('transfer'); } } _module.controller('HawkularAccounts.OrganizationMembershipController', OrganizationMembershipController); _module.controller('HawkularAccounts.OrganizationInviteModalController', OrganizationInviteModalController); _module.controller('HawkularAccounts.OrganizationTransferModalController', OrganizationTransferModalController); }
the_stack
import { Observable } from 'rxjs'; import { HOTP, HOTPGenerateValidatedData } from '../../src'; import { Validator } from '../../src/lib/schemas/validator'; describe('- Unit hotp.verify.test.ts file', () => { /** * Test if HOTP.verify() function returns an Observable */ test('- `HOTP.verify()` must return an `Observable`', (done) => { expect(HOTP.verify(undefined, undefined)).toBeInstanceOf(Observable); done(); }); /** * Test if HOTP.verify() function returns an error if token isn't set */ test('- `HOTP.verify()` must return an error if key isn\'t set', (done) => { HOTP.verify(undefined, undefined) .subscribe({ error: error => { expect(error.message).toBe('data must have required property \'token\''); done(); } }); }); /** * Test if HOTP.verify() function returns an error if token isn't a string */ test('- `HOTP.verify()` must return an error if token isn\'t a string', (done) => { HOTP.verify(null, 'A') .subscribe({ error: error => { expect(error.message).toBe('data/token must be string'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if token has wrong value */ test('- `HOTP.verify()` must return an error if token has wrong value', (done) => { HOTP.verify('', 'A') .subscribe({ error: error => { expect(error.message).toBe('data/token must match pattern "^[0-9]{1,11}$"'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if key isn't set */ test('- `HOTP.verify()` must return an error if key isn\'t set', (done) => { HOTP.verify('123456', undefined) .subscribe({ error: error => { expect(error.message).toBe('data must have required property \'key\''); done(); } }); }); /** * Test if HOTP.verify() function returns an error if key isn't a string */ test('- `HOTP.verify()` must return an error if key isn\'t a string', (done) => { HOTP.verify('123456', null) .subscribe({ error: error => { expect(error.message).toBe('data/key must be string'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if key is an empty string */ test('- `HOTP.verify()` must return an error if key is an empty string', (done) => { HOTP.verify('123456', '') .subscribe({ error: error => { expect(error.message).toBe('data/key must NOT have fewer than 1 characters'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if key_format is wrong */ test('- `HOTP.verify()` must return an error if key_format is wrong', (done) => { HOTP.verify('123456', 'AA', { key_format: null }) .subscribe({ error: error => { expect(error.message).toBe('data/key_format must be equal to one of the allowed values'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if key has a wrong hex value */ test('- `HOTP.verify()` must return an error if key has a wrong hex value', (done) => { HOTP.verify('123456', 'A', { key_format: 'hex' }) .subscribe({ error: error => { expect(error.message).toBe('data/key must match pattern "^[A-Fa-f0-9]{2,}$"'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if window isn't a number */ test('- `HOTP.verify()` must return an error if window isn\'t a number', (done) => { HOTP.verify('123456', 'secret key', { window: null }) .subscribe({ error: error => { expect(error.message).toBe('data/window must be number'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if window value is less than 0 */ test('- `HOTP.verify()` must return an error if window value is less than 0', (done) => { HOTP.verify('123456', 'secret key', { window: -1 }) .subscribe({ error: error => { expect(error.message).toBe('data/window must be >= 0'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if counter isn't a number */ test('- `HOTP.verify()` must return an error if counter isn\'t a number', (done) => { HOTP.verify('123456', 'secret key', { counter: null }) .subscribe({ error: error => { expect(error.message).toBe('data/counter must be number'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if counter value is less than 0 */ test('- `HOTP.verify()` must return an error if counter value is less than 0', (done) => { HOTP.verify('123456', 'secret key', { counter: -1 }) .subscribe({ error: error => { expect(error.message).toBe('data/counter must be >= 0'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if counter_format is wrong */ test('- `HOTP.verify()` must return an error if counter_format is wrong', (done) => { HOTP.verify('123456', 'secret key', { counter_format: null }) .subscribe({ error: error => { expect(error.message).toBe('data/counter_format must be equal to one of the allowed values'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if counter_format is wrong */ test('- `HOTP.verify()` must return an error if counter has a wrong hex value', (done) => { HOTP.verify('123456', 'secret key', { counter: '00000000000000000', counter_format: 'hex' }) .subscribe({ error: error => { expect(error.message).toBe('data/counter must match pattern "^[A-Fa-f0-9]{1,16}$"'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if add_checksum isn't a boolean */ test('- `HOTP.verify()` must return an error if add_checksum isn\'t a boolean', (done) => { HOTP.verify('123456', 'secret key', { add_checksum: null }) .subscribe({ error: error => { expect(error.message).toBe('data/add_checksum must be boolean'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if truncation_offset isn't a number */ test('- `HOTP.verify()` must return an error if truncation_offset isn\'t a number', (done) => { HOTP.verify('123456', 'secret key', { truncation_offset: null }) .subscribe({ error: error => { expect(error.message).toBe('data/truncation_offset must be number'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if truncation_offset value is less than -1 */ test('- `HOTP.verify()` must return an error if truncation_offset value is less than -1', (done) => { HOTP.verify('123456', 'secret key', { truncation_offset: -2 }) .subscribe({ error: error => { expect(error.message).toBe('data/truncation_offset must be >= -1'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if truncation_offset value is greater than 15 */ test('- `HOTP.verify()` must return an error if truncation_offset value is greater than 15', (done) => { HOTP.verify('123456', 'secret key', { truncation_offset: 16 }) .subscribe({ error: error => { expect(error.message).toBe('data/truncation_offset must be <= 15'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if algorithm is wrong */ test('- `HOTP.verify()` must return an error if algorithm is wrong', (done) => { HOTP.verify('123456', 'secret key', { algorithm: null }) .subscribe({ error: error => { expect(error.message).toBe('data/algorithm must be equal to one of the allowed values'); done(); } }); }); /** * Test if HOTP.verify() function returns an error if previous_otp_allowed isn't a boolean */ test('- `HOTP.verify()` must return an error if previous_otp_allowed isn\'t a boolean', (done) => { HOTP.verify('123456', 'secret key', { previous_otp_allowed: null }) .subscribe({ error: error => { expect(error.message).toBe('data/previous_otp_allowed must be boolean'); done(); } }); }); /** * Test if Validator.validateDataWithSchemaReference() function returns all default values */ test('- `Validator.validateDataWithSchemaReference()` must return all default values', (done) => { Validator.validateDataWithSchemaReference('/rx-otp/schemas/hotp-verify.json', { token: '123456', key: 'secret key' }) .subscribe((_: HOTPGenerateValidatedData) => { expect(_).toEqual({ token: '123456', key: 'secret key', key_format: 'str', window: 50, counter: 0, counter_format: 'int', add_checksum: false, truncation_offset: -1, algorithm: 'SHA512', previous_otp_allowed: false }); done(); } ); }); /** * Test if Validator.validateDataWithSchemaReference() function returns updated values */ test('- `Validator.validateDataWithSchemaReference()` must return updated values', (done) => { Validator.validateDataWithSchemaReference('/rx-otp/schemas/hotp-verify.json', { token: '123456', key: '00000000', key_format: 'hex', window: 5, counter: 1, algorithm: 'SHA256', previous_otp_allowed: true }) .subscribe((_: HOTPGenerateValidatedData) => { expect(_).toEqual({ token: '123456', key: '00000000', key_format: 'hex', window: 5, counter: 1, counter_format: 'int', add_checksum: false, truncation_offset: -1, algorithm: 'SHA256', previous_otp_allowed: true }); done(); } ); }); }) ;
the_stack
import * as assert from 'assert'; import * as protoLoader from '@grpc/proto-loader'; import * as grpc from '../src'; import { ProtoGrpcType } from '../src/generated/channelz' import { ChannelzClient } from '../src/generated/grpc/channelz/v1/Channelz'; import { Channel__Output } from '../src/generated/grpc/channelz/v1/Channel'; import { Server__Output } from '../src/generated/grpc/channelz/v1/Server'; import { ServiceClient, ServiceClientConstructor } from '../src/make-client'; import { loadProtoFile } from './common'; const loadedChannelzProto = protoLoader.loadSync('channelz.proto', { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true, includeDirs: [ `${__dirname}/../../proto` ] }); const channelzGrpcObject = grpc.loadPackageDefinition(loadedChannelzProto) as unknown as ProtoGrpcType; const TestServiceClient = loadProtoFile(`${__dirname}/fixtures/test_service.proto`).TestService as ServiceClientConstructor; const testServiceImpl: grpc.UntypedServiceImplementation = { unary(call: grpc.ServerUnaryCall<any, any>, callback: grpc.sendUnaryData<any>) { if (call.request.error) { setTimeout(() => { callback({ code: grpc.status.INVALID_ARGUMENT, details: call.request.message }); }, call.request.errorAfter) } else { callback(null, {count: 1}); } } } describe('Channelz', () => { let channelzServer: grpc.Server; let channelzClient: ChannelzClient; let testServer: grpc.Server; let testClient: ServiceClient; before((done) => { channelzServer = new grpc.Server(); channelzServer.addService(grpc.getChannelzServiceDefinition(), grpc.getChannelzHandlers()); channelzServer.bindAsync('localhost:0', grpc.ServerCredentials.createInsecure(), (error, port) => { if (error) { done(error); return; } channelzServer.start(); channelzClient = new channelzGrpcObject.grpc.channelz.v1.Channelz(`localhost:${port}`, grpc.credentials.createInsecure()); done(); }); }); after(() => { channelzClient.close(); channelzServer.forceShutdown(); }); beforeEach((done) => { testServer = new grpc.Server(); testServer.addService(TestServiceClient.service, testServiceImpl); testServer.bindAsync('localhost:0', grpc.ServerCredentials.createInsecure(), (error, port) => { if (error) { done(error); return; } testServer.start(); testClient = new TestServiceClient(`localhost:${port}`, grpc.credentials.createInsecure()); done(); }); }); afterEach(() => { testClient.close(); testServer.forceShutdown(); }); it('should see a newly created channel', (done) => { // Test that the specific test client channel info can be retrieved channelzClient.GetChannel({channel_id: testClient.getChannel().getChannelzRef().id}, (error, result) => { assert.ifError(error); assert(result); assert(result.channel); assert(result.channel.ref); assert.strictEqual(+result.channel.ref.channel_id, testClient.getChannel().getChannelzRef().id); // Test that the channel is in the list of top channels channelzClient.getTopChannels({start_channel_id: testClient.getChannel().getChannelzRef().id, max_results:1}, (error, result) => { assert.ifError(error); assert(result); assert.strictEqual(result.channel.length, 1); assert(result.channel[0].ref); assert.strictEqual(+result.channel[0].ref.channel_id, testClient.getChannel().getChannelzRef().id); done(); }); }); }); it('should see a newly created server', (done) => { // Test that the specific test server info can be retrieved channelzClient.getServer({server_id: testServer.getChannelzRef().id}, (error, result) => { assert.ifError(error); assert(result); assert(result.server); assert(result.server.ref); assert.strictEqual(+result.server.ref.server_id, testServer.getChannelzRef().id); // Test that the server is in the list of servers channelzClient.getServers({start_server_id: testServer.getChannelzRef().id, max_results: 1}, (error, result) => { assert.ifError(error); assert(result); assert.strictEqual(result.server.length, 1); assert(result.server[0].ref); assert.strictEqual(+result.server[0].ref.server_id, testServer.getChannelzRef().id); done(); }); }); }); it('should count successful calls', (done) => { testClient.unary({}, (error: grpc.ServiceError, value: unknown) => { assert.ifError(error); // Channel data tests channelzClient.GetChannel({channel_id: testClient.getChannel().getChannelzRef().id}, (error, channelResult) => { assert.ifError(error); assert(channelResult); assert(channelResult.channel); assert(channelResult.channel.ref); assert(channelResult.channel.data); assert.strictEqual(+channelResult.channel.data.calls_started, 1); assert.strictEqual(+channelResult.channel.data.calls_succeeded, 1); assert.strictEqual(+channelResult.channel.data.calls_failed, 0); assert.strictEqual(channelResult.channel.subchannel_ref.length, 1); channelzClient.getSubchannel({subchannel_id: channelResult.channel.subchannel_ref[0].subchannel_id}, (error, subchannelResult) => { assert.ifError(error); assert(subchannelResult); assert(subchannelResult.subchannel); assert(subchannelResult.subchannel.ref); assert(subchannelResult.subchannel.data); assert.strictEqual(subchannelResult.subchannel.ref.subchannel_id, channelResult.channel!.subchannel_ref[0].subchannel_id); assert.strictEqual(+subchannelResult.subchannel.data.calls_started, 1); assert.strictEqual(+subchannelResult.subchannel.data.calls_succeeded, 1); assert.strictEqual(+subchannelResult.subchannel.data.calls_failed, 0); assert.strictEqual(subchannelResult.subchannel.socket_ref.length, 1); channelzClient.getSocket({socket_id: subchannelResult.subchannel.socket_ref[0].socket_id}, (error, socketResult) => { assert.ifError(error); assert(socketResult); assert(socketResult.socket); assert(socketResult.socket.ref); assert(socketResult.socket.data); assert.strictEqual(socketResult.socket.ref.socket_id, subchannelResult.subchannel!.socket_ref[0].socket_id); assert.strictEqual(+socketResult.socket.data.streams_started, 1); assert.strictEqual(+socketResult.socket.data.streams_succeeded, 1); assert.strictEqual(+socketResult.socket.data.streams_failed, 0); assert.strictEqual(+socketResult.socket.data.messages_received, 1); assert.strictEqual(+socketResult.socket.data.messages_sent, 1); // Server data tests channelzClient.getServer({server_id: testServer.getChannelzRef().id}, (error, serverResult) => { assert.ifError(error); assert(serverResult); assert(serverResult.server); assert(serverResult.server.ref); assert(serverResult.server.data); assert.strictEqual(+serverResult.server.ref.server_id, testServer.getChannelzRef().id); assert.strictEqual(+serverResult.server.data.calls_started, 1); assert.strictEqual(+serverResult.server.data.calls_succeeded, 1); assert.strictEqual(+serverResult.server.data.calls_failed, 0); channelzClient.getServerSockets({server_id: testServer.getChannelzRef().id}, (error, socketsResult) => { assert.ifError(error); assert(socketsResult); assert.strictEqual(socketsResult.socket_ref.length, 1); channelzClient.getSocket({socket_id: socketsResult.socket_ref[0].socket_id}, (error, serverSocketResult) => { assert.ifError(error); assert(serverSocketResult); assert(serverSocketResult.socket); assert(serverSocketResult.socket.ref); assert(serverSocketResult.socket.data); assert.strictEqual(serverSocketResult.socket.ref.socket_id, socketsResult.socket_ref[0].socket_id); assert.strictEqual(+serverSocketResult.socket.data.streams_started, 1); assert.strictEqual(+serverSocketResult.socket.data.streams_succeeded, 1); assert.strictEqual(+serverSocketResult.socket.data.streams_failed, 0); assert.strictEqual(+serverSocketResult.socket.data.messages_received, 1); assert.strictEqual(+serverSocketResult.socket.data.messages_sent, 1); done(); }); }); }); }); }); }); }); }); it('should count failed calls', (done) => { testClient.unary({error: true}, (error: grpc.ServiceError, value: unknown) => { assert(error); // Channel data tests channelzClient.GetChannel({channel_id: testClient.getChannel().getChannelzRef().id}, (error, channelResult) => { assert.ifError(error); assert(channelResult); assert(channelResult.channel); assert(channelResult.channel.ref); assert(channelResult.channel.data); assert.strictEqual(+channelResult.channel.data.calls_started, 1); assert.strictEqual(+channelResult.channel.data.calls_succeeded, 0); assert.strictEqual(+channelResult.channel.data.calls_failed, 1); assert.strictEqual(channelResult.channel.subchannel_ref.length, 1); channelzClient.getSubchannel({subchannel_id: channelResult.channel.subchannel_ref[0].subchannel_id}, (error, subchannelResult) => { assert.ifError(error); assert(subchannelResult); assert(subchannelResult.subchannel); assert(subchannelResult.subchannel.ref); assert(subchannelResult.subchannel.data); assert.strictEqual(subchannelResult.subchannel.ref.subchannel_id, channelResult.channel!.subchannel_ref[0].subchannel_id); assert.strictEqual(+subchannelResult.subchannel.data.calls_started, 1); assert.strictEqual(+subchannelResult.subchannel.data.calls_succeeded, 0); assert.strictEqual(+subchannelResult.subchannel.data.calls_failed, 1); assert.strictEqual(subchannelResult.subchannel.socket_ref.length, 1); channelzClient.getSocket({socket_id: subchannelResult.subchannel.socket_ref[0].socket_id}, (error, socketResult) => { assert.ifError(error); assert(socketResult); assert(socketResult.socket); assert(socketResult.socket.ref); assert(socketResult.socket.data); assert.strictEqual(socketResult.socket.ref.socket_id, subchannelResult.subchannel!.socket_ref[0].socket_id); assert.strictEqual(+socketResult.socket.data.streams_started, 1); assert.strictEqual(+socketResult.socket.data.streams_succeeded, 1); assert.strictEqual(+socketResult.socket.data.streams_failed, 0); assert.strictEqual(+socketResult.socket.data.messages_received, 0); assert.strictEqual(+socketResult.socket.data.messages_sent, 1); // Server data tests channelzClient.getServer({server_id: testServer.getChannelzRef().id}, (error, serverResult) => { assert.ifError(error); assert(serverResult); assert(serverResult.server); assert(serverResult.server.ref); assert(serverResult.server.data); assert.strictEqual(+serverResult.server.ref.server_id, testServer.getChannelzRef().id); assert.strictEqual(+serverResult.server.data.calls_started, 1); assert.strictEqual(+serverResult.server.data.calls_succeeded, 0); assert.strictEqual(+serverResult.server.data.calls_failed, 1); channelzClient.getServerSockets({server_id: testServer.getChannelzRef().id}, (error, socketsResult) => { assert.ifError(error); assert(socketsResult); assert.strictEqual(socketsResult.socket_ref.length, 1); channelzClient.getSocket({socket_id: socketsResult.socket_ref[0].socket_id}, (error, serverSocketResult) => { assert.ifError(error); assert(serverSocketResult); assert(serverSocketResult.socket); assert(serverSocketResult.socket.ref); assert(serverSocketResult.socket.data); assert.strictEqual(serverSocketResult.socket.ref.socket_id, socketsResult.socket_ref[0].socket_id); assert.strictEqual(+serverSocketResult.socket.data.streams_started, 1); assert.strictEqual(+serverSocketResult.socket.data.streams_succeeded, 0); assert.strictEqual(+serverSocketResult.socket.data.streams_failed, 1); assert.strictEqual(+serverSocketResult.socket.data.messages_received, 1); assert.strictEqual(+serverSocketResult.socket.data.messages_sent, 0); done(); }); }); }); }); }); }); }); }); });
the_stack
import * as angular from 'angular'; import { ButtonTypeEnum } from './buttonTypeEnum'; describe('buttonDirective: <uif-button />', () => { /** * before each test load all required modules */ beforeEach(() => { angular.mock.module('officeuifabric.core'); angular.mock.module('officeuifabric.components.icon'); angular.mock.module('officeuifabric.components.button'); }); /** * tests for the description directive used in the button */ describe('buttonDescriptionDirective: <uif-button-description />', () => { let element: JQuery; let scope: angular.IScope; beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => { let html: string = '<uif-button-description>Lorem Ipsum</uif-button>'; scope = $rootScope; element = $compile(html)(scope); // jqLite object element = jQuery(element[0]); // jQuery object scope.$digest(); })); it('should create correct HTML', () => { // expected rendered HTML: // <span class="ms-Button-description">Some description goes here of the button</span> // verify expected HTML tag expect(element.prop('tagName')).toEqual('SPAN'); }); it('should set correct Office UI Fabric CSS class', () => { // expected rendered HTML: // <span class="ms-Button-description">Some description goes here of the button</span> // check expected CSS classes expect(element).toHaveClass('ms-Button-description'); }); // the value specified should render within the body of the rendered element it('should be able to set the description', () => { // expected rendered HTML: // <span class="ms-Button-description">Lorem Ipsum</span> // check value of the element expect(element[0].tagName).toBe('SPAN'); expect(element[0].innerText).toBe('Lorem Ipsum'); }); }); /** * tests when the button should be rendered as a <button> tag */ describe('rendered as <button>', () => { let element: JQuery; let scope: angular.IScope; beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => { let html: string = '<uif-button>Lorem Ipsum</uif-button>'; scope = $rootScope; element = $compile(html)(scope); // jqLite object element = jQuery(element[0]); // jQuery object scope.$digest(); })); it('should create correct HTML', () => { // expected rendered HTML: // <button class="ms-Button"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> // verify expected HTML tag expect(element.prop('tagName')).toEqual('BUTTON'); // check child let spanElement: JQuery = element.find('span'); expect(spanElement.prop('tagName')).toEqual('SPAN'); }); it('should set correct Office UI Fabric CSS class', () => { // expected rendered HTML: // <button class="ms-Button"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> // verify button CSS expect(element[0]).toHaveClass('ms-Button'); // verify inner span CSS let spanElement: JQuery = element.find('span'); expect(spanElement[0]).toHaveClass('ms-Button-label'); }); // should not throw an error when null button type enum passed in it('should not log error on null button types', inject(($log: angular.ILogService, $compile: Function) => { // create button with no attributes let html: string = '<uif-button>Lorem Ipsum</uif-button>'; $compile(html)(scope); scope.$digest(); // verify no errors logged expect($log.error.logs.length).toBe(0); })); // should not throw an error when valid button type enum passed in it('should not log error on valid button types', inject(($log: angular.ILogService, $compile: Function) => { let html: string = ''; // create buttons for each enum option Object.keys(ButtonTypeEnum) .forEach((buttonType: string) => { html = '<uif-button uif-type="' + buttonType + '">Lorem Ipsum</uif-button>'; $compile(html)(scope); scope.$digest(); // verify no errors logged expect($log.error.logs.length).toBe(0); }); })); // should log an error when invalid button type passed specified it('should log error on invalid button types', inject(($log: angular.ILogService, $compile: Function) => { // check no error when no type specified let html: string = '<uif-button uif-type="INVALID">Lorem Ipsum</uif-button>'; $compile(html)(scope); scope.$digest(); // verify error logged expect($log.error.logs.length).toBe(1); })); // the value specified should render within the body of the rendered element it('should be able to set the label', () => { // expected rendered HTML: // <button class="ms-Button"> // <span class="ms-Button-label">Lorem Ipsum</span> // </button> // check value of the span let spanElement: JQuery = element.find('span'); expect(spanElement[0].innerText).toBe('Lorem Ipsum'); }); // the rendered element should render enabled by default it('should be able to set enabled', () => { // expected rendered HTML: // <button class="ms-Button"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> // verify no disabled class present expect(element).not.toHaveClass('is-disabled'); expect(element.attr('disabled')).toBe(undefined, 'button should not be disabled'); }); // if set to disabled, this should render on the button rendered element it('should be able to set disabled', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button is-disabled" disabled="disabled"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> let html: string = '<uif-button disabled="disabled">Lorem Ipsum</uif-button>'; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object scope.$digest(); // verify no disabled class present expect(buttonElement[0]).toHaveClass('is-disabled'); expect(buttonElement.attr('disabled')).toBe('disabled', 'button should be disabled'); })); it('should call preventDefault in disabled state', inject(($compile: Function) => { let html: string = '<uif-button disabled="disabled">Lorem Upsum</uif-button>'; let buttonElement: JQuery = $compile(html)(scope); buttonElement = jQuery(buttonElement[0]); scope.$digest(); // button calls event.preventDefault on click let e: Event = $.Event('click'); buttonElement.trigger('e'); expect(e.preventDefault).toBeTruthy(); })); it('should be able to be toggled between enabled and disabled', inject(($compile: Function) => { let currentScope: any = scope.$new(); currentScope.btnDisabled = true; let html: string = '<uif-button ng-disabled="btnDisabled">Lorem Upsum</uif-button>'; let buttonElement: JQuery = $compile(html)(currentScope); buttonElement = jQuery(buttonElement[0]); scope.$digest(); expect(buttonElement).toHaveClass('is-disabled'); expect(buttonElement.attr('disabled')).toBe('disabled', 'button should be disabled'); currentScope.btnDisabled = false; currentScope.$digest(); expect(element).not.toHaveClass('is-disabled'); expect(element.attr('disabled')).toBe(undefined, 'button should not be disabled'); })); /** * action (default) button tests */ describe('action (default) button', () => { // the rendered button should not have any button type decorator classes it('should not have any button decorator classes', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> let html: string = '<uif-button>Lorem Ipsum</uif-button>'; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify no decorator classes rendered by the directive expect(buttonElement).not.toHaveClass('ms-Button--primary'); expect(buttonElement).not.toHaveClass('ms-Button--command'); expect(buttonElement).not.toHaveClass('ms-Button--compound'); expect(buttonElement).not.toHaveClass('ms-Button--hero'); })); // the icon specified should not be rendered (action doesn't support icon) it('should not be able to set an icon', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> let html: string = `<uif-button> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify no wrapper was created expect(buttonElement.find('span.ms-Button-icon').length).toBe(0); // verify no icon was added expect(buttonElement.find('uif-icon').length).toBe(0); })); }); // describe('action (default) button') describe('primary button', () => { // ensure that the button has the correct CSS class for the button type it('should include correct CSS class', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--primary"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> let html: string = '<uif-button uif-type="primary">Lorem Ipsum</uif-button>'; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify correct decorator class expect(buttonElement).toHaveClass('ms-Button--primary'); })); // the icon specified should not be rendered (primary doesn't support icon) it('should not be able to set an icon', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--primary"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> let html: string = `<uif-button uif-type="primary"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify no wrapper was created expect(buttonElement.find('span.ms-Button-icon').length).toBe(0); // verify no icon was added expect(buttonElement.find('uif-icon').length).toBe(0); })); // the icon specified should not be rendered (primary doesn't support icon) it('should log error when icon specified', inject(($log: angular.ILogService, $compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--primary"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> let html: string = `<uif-button uif-type="primary"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; $compile(html)(scope); scope.$digest(); // verify error logged expect($log.error.logs.length).toBe(1); })); }); // describe('primary button') /** * command button tests */ describe('command button', () => { // ensure that the button has the correct CSS class for the button type it('should include correct CSS class', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--command"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> let html: string = '<uif-button uif-type="command">Lorem Ipsum</uif-button>'; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify no icon was rendered by the directive expect(buttonElement).toHaveClass('ms-Button--command'); })); // the icon specified should render within the body of the rendered element it('should be able to set an icon', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--command"> // <span class="ms-Button-icon"><i class="ms-Icon ms-Icon--plus"></i></span> // <span class="ms-Button-label">+ Button as &lt;button&gt;</span> // </button> // >>> REALLY should render // <button class="ms-Button ms-Button--command"> // <span class="ms-Button-icon"><uif-icon uif-type="plus"></uif-icon></span> // <span class="ms-Button-label">Hero Button</span> // </button> let html: string = `<uif-button uif-type="command"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify class on inner label expect(buttonElement.children('span.ms-Button-label').length).toBe(1); // verify icon was rendered by the directive expect(buttonElement.children('span.ms-Button-icon').length).toBe(1); })); it('should not log error when icon specified', inject(($log: angular.ILogService, $compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--command"> // <span class="ms-Button-icon"><uif-icon uif-type="plus"></uif-icon></span> // <span class="ms-Button-label">Hero Button</span> // </button> let html: string = `<uif-button uif-type="command"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; $compile(html)(scope); scope.$digest(); // verify error logged expect($log.error.logs.length).toBe(0); })); }); // describe('command button') /** * compound button tests */ describe('compound button', () => { // ensure that the button has the correct CSS class for the button type it('should include correct CSS class (label only)', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--compound"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> let html: string = '<uif-button uif-type="compound">Lorem Ipsum</uif-button>'; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify class on button element expect(buttonElement).toHaveClass('ms-Button--compound'); // verify class on inner label expect(buttonElement.children('span.ms-Button-label').length).toBe(1); })); it('should include correct CSS class (label & description only)', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--compound"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // <span class="ms-Button-description">Button description</span> // </button> let html: string = `<uif-button uif-type="compound"> Lorem Ipsum <uif-button-description>Button Description</uif-button-description> </uif-button>`; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify class on button element expect(buttonElement).toHaveClass('ms-Button--compound'); // verify class on inner label expect(buttonElement.children('span.ms-Button-label').length).toBe(1); // verify class on inner description expect(buttonElement.children('span.ms-Button-description').length).toBe(1); })); // the icon specified should not be rendered (compound doesn't support icon) it('should not be able to set an icon', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--compound"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // <span class="ms-Button-description">Some description goes here of the button</span> // </button> let html: string = `<uif-button uif-type="compound"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify no icon was rendered by the directive expect(buttonElement.children('span.ms-Button-icon').length).toBe(0); expect(buttonElement.find('uif-icon').length).toBe(0); })); }); // describe('compound button') /** * hero button tests */ describe('hero button', () => { // ensure that the button has the correct CSS class for the button type it('should include correct CSS class', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--hero"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </button> let html: string = '<uif-button uif-type="hero">Lorem Ipsum</uif-button>'; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify no icon was rendered by the directive expect(buttonElement).toHaveClass('ms-Button--hero'); })); // the icon specified should render within the body of the rendered element it('should be able to set an icon', inject(($compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--hero"> // <span class="ms-Button-icon"><i class="ms-Icon ms-Icon--plus"></i></span> // <span class="ms-Button-label">Hero Button</span> // </button> // >>> REALLY should render // <button class="ms-Button ms-Button--hero"> // <span class="ms-Button-icon"><uif-icon uif-type="plus"></uif-icon></span> // <span class="ms-Button-label">Hero Button</span> // </button> let html: string = `<uif-button uif-type="hero"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; let buttonElement: JQuery = $compile(html)(scope); // jqLite object buttonElement = jQuery(buttonElement[0]); // jQuery object // verify class on inner label expect(buttonElement.children('span.ms-Button-label').length).toBe(1); // verify icon was rendered by the directive expect(buttonElement.children('span.ms-Button-icon').length).toBe(1); })); }); // describe('hero button') }); // describe('rendered as <button>') /** * tests when the button should be rendered as an <a> tag */ describe('rendered as <a>', () => { let element: JQuery; let scope: angular.IScope; beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => { let html: string = '<uif-button ng-href="http://ngOfficeUiFabric.com">Lorem Ipsum</uif-button>'; scope = $rootScope; // element = jqLite object element = $compile(html)(scope); // element = jQuery object element = jQuery(element[0]); scope.$digest(); })); it('should create HTML <a> tag', () => { // expected rendered HTML: // <a class="ms-Button"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </a> // verify expected HTML tag expect(element.prop('tagName')).toEqual('A'); // check child let spanElement: JQuery = element.find('span'); expect(spanElement.prop('tagName')).toEqual('SPAN'); }); it('should set correct Office UI Fabric CSS class', () => { // expected rendered HTML: // <a class="ms-Button"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </a> // verify button CSS expect(element[0]).toHaveClass('ms-Button'); // check child let spanElement: JQuery = element.find('span'); expect(spanElement.prop('tagName')).toEqual('SPAN'); }); // should not throw an error when valid button type enum passed in it('should not log error on null button types', inject(($log: angular.ILogService, $compile: Function) => { // check no error when no type specified let html: string = '<uif-button ng-href="http://ngOfficeUiFabric.com">Lorem Ipsum</uif-button>'; $compile(html)(scope); scope.$digest(); expect($log.error.logs.length).toBe(0); })); // should not throw an error when valid button type enum passed in it('should not log error on valid button types', inject(($log: angular.ILogService, $compile: Function) => { let html: string = ''; // for all enum options... // check no error when no type specified Object.keys(ButtonTypeEnum) .forEach((buttonType: string) => { html = '<uif-button uif-type="' + buttonType + '" ng-href="http://ngOfficeUiFabric.com">Lorem Ipsum</uif-button>'; $compile(html)(scope); scope.$digest(); // verify no errors logged expect($log.error.logs.length).toBe(0); }); })); // should throw an error when invalid button type passed in it('should log error on invalid button types', inject(($log: angular.ILogService, $compile: Function) => { // check no error when no type specified let html: string = '<uif-button uif-type="INVALID" ng-href="http://ngOfficeUiFabric.com">Lorem Ipsum</uif-button>'; $compile(html)(scope); scope.$digest(); // verify error logged expect($log.error.logs.length).toBe(1); })); // the value specified should render within the body of the rendered element it('should be able to set the label', () => { // expected rendered HTML: // <a class="ms-Button"> // <span class="ms-Button-label">Button as &lt;a&gt;</span> // </a> // check value of the span let spanElement: JQuery = element.find('span'); expect(spanElement[0].innerText).toBe('Lorem Ipsum'); }); // the rendered element should render enabled by default it('should be able to set enabled', () => { // expected rendered HTML: // <a class="ms-Button"> // <span class="ms-Button-label">Button as &lt;a&gt;</span> // </a> // verify no disabled class present expect(element).not.toHaveClass('is-disabled'); }); // if set to disabled, this should render on the button rendered element it('should be able to set disabled', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button is-disabled"> // <span class="ms-Button-label">Button as &lt;a&gt;</span> // </a> let html: string = '<uif-button disabled="disabled" ng-href="http://ngOfficeUiFabric.com">Lorem Ipsum</uif-button>'; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object scope.$digest(); // verify disabled class present expect(linkElement[0]).toHaveClass('is-disabled'); })); it('should call preventDefault in disabled state', inject(($compile: Function) => { let html: string = '<uif-button disabled="disabled" ng-href="http://ngOfficeUiFabric.com">Lorem Ipsum</uif-button>'; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object scope.$digest(); // link calls event.preventDefault on click let e: Event = $.Event('click'); linkElement.trigger('e'); expect(e.preventDefault).toBeTruthy(); })); it('should be able to be toggled between enabled and disabled', inject(($compile: Function) => { let currentScope: any = scope.$new(); currentScope.btnDisabled = true; let html: string = '<uif-button ng-disabled="btnDisabled" ng-href="http://ngOfficeUiFabric.com">Lorem Upsum</uif-button>'; let buttonElement: JQuery = $compile(html)(currentScope); buttonElement = jQuery(buttonElement[0]); scope.$digest(); expect(buttonElement).toHaveClass('is-disabled'); currentScope.btnDisabled = false; currentScope.$digest(); expect(element).not.toHaveClass('is-disabled'); })); /** * action (default) button tests */ describe('action (default) button', () => { // the rendered button should not have any button type decorator classes it('should not have any button decorator classes', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </a> let html: string = '<uif-button ng-href="http://ngOfficeUiFabric.com">Lorem Ipsum</uif-button>'; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify no decorator classes rendered by the directive expect(linkElement).not.toHaveClass('ms-Button--primary'); expect(linkElement).not.toHaveClass('ms-Button--command'); expect(linkElement).not.toHaveClass('ms-Button--compound'); expect(linkElement).not.toHaveClass('ms-Button--hero'); })); // the icon specified should not be rendered (action doesn't support icon) it('should not be able to set an icon', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button"> // <span class="ms-Button-label">Button as &lt;a&gt;</span> // </a> let html: string = `<uif-button ng-href="http://ngOfficeUiFabric.com"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify no wrapper was created expect(linkElement.find('span.ms-Button-icon').length).toBe(0); // verify no icon was added expect(linkElement.find('uif-icon').length).toBe(0); })); }); // describe('action (default) button') /** * primary button tests */ describe('primary button', () => { // ensure that the button has the correct CSS class for the button type it('should include correct CSS class', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button ms-Button--primary"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </a> let html: string = '<uif-button uif-type="primary" ng-href="http://ngOfficeUiFabric.com">Lorem Ipsum</uif-button>'; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify correct decorator class expect(linkElement).toHaveClass('ms-Button--primary'); })); // the icon specified should not be rendered (primary doesn't support icon) it('should not be able to set an icon', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button ms-Button--primary"> // <span class="ms-Button-label">Button as &lt;a&gt;</span> // </a> let html: string = `<uif-button uif-type="primary" ng-href="http://ngOfficeUiFabric.com">' <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify no wrapper was created expect(linkElement.find('span.ms-Button-icon').length).toBe(0); // verify no icon was added expect(linkElement.find('uif-icon').length).toBe(0); })); // the icon specified should not be rendered (primary doesn't support icon) it('should log error when icon specified', inject(($log: angular.ILogService, $compile: Function) => { // expected rendered HTML: // <a class="ms-Button ms-Button--primary"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </a> let html: string = `<uif-button uif-type="primary" ng-href="http://ngOfficeUiFabric.com"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; $compile(html)(scope); scope.$digest(); // verify error logged expect($log.error.logs.length).toBe(1); })); }); // describe('primary button') describe('command button', () => { // ensure that the button has the correct CSS class for the button type it('should include correct CSS class', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button ms-Button--command"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </a> let html: string = '<uif-button uif-type="command">Lorem Ipsum</uif-button>'; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify no icon was rendered by the directive expect(linkElement).toHaveClass('ms-Button--command'); })); // the icon specified should render within the body of the rendered element it('should be able to set an icon', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button ms-Button--command"> // <span class="ms-Button-icon"><i class="ms-Icon ms-Icon--plus"></i></span> // <span class="ms-Button-label">+ Button as &lt;a&gt;</span> // </a> // >>> REALLY should render // <a class="ms-Button ms-Button--command"> // <span class="ms-Button-icon"><uif-icon uif-type="plus"></uif-icon></span> // <span class="ms-Button-label">+ Button as &lt;a&gt;</span> // </a> let html: string = `<uif-button uif-type="command" ng-href="http://ngOfficeUiFabric.com"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify class on inner label expect(linkElement.children('span.ms-Button-label').length).toBe(1); // verify icon was rendered by the directive expect(linkElement.children('span.ms-Button-icon').length).toBe(1); })); it('should not log error when icon specified', inject(($log: angular.ILogService, $compile: Function) => { // expected rendered HTML: // <button class="ms-Button ms-Button--command"> // <span class="ms-Button-icon"><uif-icon uif-type="plus"></uif-icon></span> // <span class="ms-Button-label">Hero Button</span> // </button> let html: string = `<uif-button uif-type="command" ng-href="http://ngOfficeUiFabric.com"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; $compile(html)(scope); scope.$digest(); // verify error logged expect($log.error.logs.length).toBe(0); })); }); // describe('command button') /** * compound button tests */ describe('compound button', () => { // ensure that the button has the correct CSS class for the button type it('should include correct CSS class (label only)', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button ms-Button--compound"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </a> let html: string = `<uif-button uif-type="compound" ng-href="http://ngOfficeUiFabric.com"> Lorem Ipsum </uif-button>`; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify no icon was rendered by the directive expect(linkElement).toHaveClass('ms-Button--compound'); // verify class on inner label expect(linkElement.children('span.ms-Button-label').length).toBe(1); })); it('should include correct CSS class (label & description only)', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button ms-Button--compound"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // <span class="ms-Button-description">Button description</span> // </a> let html: string = `<uif-button uif-type="compound" ng-href="http://ngOfficeUiFabric.com"> Lorem Ipsum <uif-button-description>Button Description</uif-button-description> </uif-button>`; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify class on button element expect(linkElement).toHaveClass('ms-Button--compound'); // verify class on inner label expect(linkElement.children('span.ms-Button-label').length).toBe(1); // verify class on inner description expect(linkElement.children('span.ms-Button-description').length).toBe(1); })); // the icon specified should not be rendered (compound doesn't support icon) it('should not be able to set an icon', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button ms-Button--compound"> // <span class="ms-Button-label">Button as &lt;a&gt;</span> // <span class="ms-Button-description">Some description goes here of the button</span> // </a> let html: string = `<uif-button ng-href="http://ngOfficeUiFabric.com"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify no icon was rendered by the directive expect(linkElement.children('span.ms-Button-icon').length).toBe(0); expect(linkElement.find('uif-icon').length).toBe(0); })); }); // describe('compound button') /** * hero button tests */ describe('hero button', () => { // ensure that the button has the correct CSS class for the button type it('should include correct CSS class', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button ms-Button--hero"> // <span class="ms-Button-label">Button as &lt;button&gt;</span> // </a> let html: string = `<uif-button uif-type="hero" ng-href="http://ngOfficeUiFabric.com"> Lorem Ipsum </uif-button>`; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify no icon was rendered by the directive expect(linkElement).toHaveClass('ms-Button--hero'); })); // the icon specified should render within the body of the rendered element it('should be able to set an icon', inject(($compile: Function) => { // expected rendered HTML: // <a class="ms-Button ms-Button--hero"> // <span class="ms-Button-icon"><i class="ms-Icon ms-Icon--plus"></i></span> // <span class="ms-Button-label">Hero Button</span> // </a> // >>> REALLY should render // <a class="ms-Button ms-Button--hero"> // <span class="ms-Button-icon"><uif-icon uif-type="plus"></uif-icon></span> // <span class="ms-Button-label">Hero Button</span> // </a> let html: string = `<uif-button uif-type="hero" ng-href="http://ngOfficeUiFabric.com"> <uif-icon uif-type="plus"></uif-icon>Lorem Ipsum </uif-button>`; let linkElement: JQuery = $compile(html)(scope); // jqLite object linkElement = jQuery(linkElement[0]); // jQuery object // verify class on inner label expect(linkElement.children('span.ms-Button-label').length).toBe(1); // verify icon was rendered by the directive expect(linkElement.children('span.ms-Button-icon').length).toBe(1); })); }); // describe('hero button') }); // describe('rendered as <a>') });
the_stack
import { Client, ClientConfig } from "pg"; import { parse } from "pg-connection-string"; import dotenv from "dotenv"; import { Action, MatchType, Options } from "./types/index"; import { SchemaQueryResult, TypeQueryResult, EntityQueryResult, ColumnQueryResult, IndexQueryResult, ConstraintQueryResult, ActionLetter, MatchTypeLetter, QueryResults, FunctionQueryResult, TriggerQueryResult, } from "./types/query-result"; import { executeSqlFile, getConnectedPgClient, getQueryVersionFor, getEnvValues, arrify } from "./util/helper"; import Db from "./pg-structure/db"; import Schema from "./pg-structure/schema"; import Domain from "./pg-structure/type/domain"; import EnumType from "./pg-structure/type/enum-type"; import BaseType from "./pg-structure/type/base-type"; import CompositeType from "./pg-structure/type/composite-type"; import Table from "./pg-structure/entity/table"; import View from "./pg-structure/entity/view"; import MaterializedView from "./pg-structure/entity/materialized-view"; import Sequence from "./pg-structure/entity/sequence"; import Entity from "./pg-structure/base/entity"; import Column from "./pg-structure/column"; import Index from "./pg-structure"; import PrimaryKey from "./pg-structure/constraint/primary-key"; import UniqueConstraint from "./pg-structure/constraint/unique-constraint"; import CheckConstraint from "./pg-structure/constraint/check-constraint"; import ExclusionConstraint from "./pg-structure/constraint/exclusion-constraint"; import ForeignKey from "./pg-structure/constraint/foreign-key"; import RangeType from "./pg-structure/type/range-type"; import NormalFunction from "./pg-structure/function/normal-function"; import Procedure from "./pg-structure/function/procedure"; import AggregateFunction from "./pg-structure/function/aggregate-function"; import WindowFunction from "./pg-structure/function/window-function"; import PseudoType from "./pg-structure/type/pseudo-type"; import Trigger from "./pg-structure/trigger"; import getRelationNameFunctions from "./util/naming-function"; dotenv.config(); /** * Returns database name. * * @ignore * @param pgClientOrConfig is input to get database name from. * @returns database name. */ /* istanbul ignore next */ function getDatabaseName(pgClientOrConfig: Client | ClientConfig | string): string { if (!pgClientOrConfig || pgClientOrConfig instanceof Client) { return "database"; } return (typeof pgClientOrConfig === "string" ? parse(pgClientOrConfig).database : pgClientOrConfig.database) || "database"; } /** * Returns list of schemes in database. If no patterns are given returns all schemas except system schemas. * Patterns are feeded to `LIKE` operator of SQL, so `%` and `_` may be used. * * @ignore * @param client is pg client. * @param include is pattern to be used in SQL query `LIKE` part. * @param exclude is pattern to be used in SQL query `NOT LIKE` part. * @param system is whether to include system schemas in result. * @returns array of objects describing schemas. */ async function getSchemas( client: Client, { include = [], exclude = [], system = false }: { include?: string[]; exclude?: string[]; system?: boolean } ): Promise<SchemaQueryResult[]> { const where: string[] = ["NOT pg_is_other_temp_schema(oid)", "nspname <> 'pg_toast'"]; const whereInclude: string[] = []; const parameters: string[] = []; const includedPatterns = include.concat(system && include.length > 0 ? ["information_schema", "pg_%"] : []); const excludedPatterns = exclude.concat(system ? [] : ["information_schema", "pg_%"]); includedPatterns.forEach((pattern, i) => { whereInclude.push(`nspname LIKE $${i + 1}`); // nspname LIKE $1 parameters.push(pattern); }); if (whereInclude.length > 0) where.push(`(${whereInclude.join(" OR ")})`); excludedPatterns.forEach((pattern, i) => { where.push(`nspname NOT LIKE $${i + include.length + 1}`); // nspname NOT LIKE $2 parameters.push(pattern); }); const whereQuery = `WHERE ${where.join(" AND ")}`; const sql = `SELECT oid, nspname AS name, obj_description(oid, 'pg_namespace') AS comment FROM pg_namespace ${whereQuery} ORDER BY nspname`; const result = await client.query(sql, parameters); return result.rows; } /** * Returns list of system schames required by pg-structure. * Patterns are feeded to `LIKE` operator of SQL, so `%` and `_` may be used. * * @ignore * @param client is pg client. * @returns array of objects describing schemas. */ async function getSystemSchemas(client: Client): Promise<SchemaQueryResult[]> { const sql = `SELECT oid, nspname AS name, obj_description(oid, 'pg_namespace') AS comment FROM pg_namespace WHERE nspname IN ('pg_catalog') ORDER BY nspname`; return (await client.query(sql)).rows; } /** * Adds system schemas required by pg-structure. * * @ignore * @param db is Db object. */ function addSystemSchemas(db: Db, rows: SchemaQueryResult[]): void { rows.forEach((row) => db.systemSchemas.push(new Schema({ ...row, db }))); } /** * Adds schema instances to database. * * @ignore * @param db is Db object. */ function addSchemas(db: Db, rows: SchemaQueryResult[]): void { rows.forEach((row) => db.schemas.push(new Schema({ ...row, db }))); } const builtinTypeAliases: Record<string, Record<string, string | boolean>> = { int2: { name: "smallint" }, int4: { name: "integer", shortName: "int" }, int8: { name: "bigint" }, numeric: { internalName: "decimal", hasPrecision: true, hasScale: true }, float4: { name: "real" }, float8: { name: "double precision" }, varchar: { name: "character varying", hasLength: true }, char: { name: "character", hasLength: true }, timestamp: { name: "timestamp without time zone", hasPrecision: true }, timestamptz: { name: "timestamp with time zone", hasPrecision: true }, time: { name: "time without time zone", hasPrecision: true }, timetz: { name: "time with time zone", hasPrecision: true }, interval: { hasPrecision: true }, bool: { name: "boolean" }, bit: { hasLength: true }, varbit: { name: "bit varying", hasLength: true }, }; /** * Adds types to database. * * @ignore * @param db is DB object * @param rows are query result of types to be added. */ function addTypes(db: Db, rows: TypeQueryResult[]): void { const typeKinds = { d: Domain, e: EnumType, b: BaseType, c: CompositeType, r: RangeType, p: PseudoType }; // https://www.postgresql.org/docs/9.5/catalog-pg-type.html rows.forEach((row) => { const schema = db.systemSchemas.getMaybe(row.schemaOid, { key: "oid" }) || db.schemas.get(row.schemaOid, { key: "oid" }); const builtinTypeData = builtinTypeAliases[row.name] ? { internalName: row.name, ...builtinTypeAliases[row.name] } : {}; const kind = row.kind as keyof typeof typeKinds; const type = new typeKinds[kind]({ ...row, ...builtinTypeData, schema, sqlType: row.sqlType as string }); // Only domain type has `sqlType` and it's required. schema.typesIncludingEntities.push(type); }); } /** * Adds entities to database. * * @ignore * @param db is DB object * @param rows are query result of entities to be added. */ function addEntities(db: Db, rows: EntityQueryResult[]): void { rows.forEach((row) => { const schema = db.schemas.get(row.schemaOid, { key: "oid" }) as Schema; /* istanbul ignore else */ if (row.kind === "r" || row.kind === "p") schema.tables.push(new Table({ ...row, schema })); else if (row.kind === "v") schema.views.push(new View({ ...row, schema })); else if (row.kind === "m") schema.materializedViews.push(new MaterializedView({ ...row, schema })); else if (row.kind === "S") schema.sequences.push(new Sequence({ ...row, schema })); }); } /** * Adds columns to database. * * @ignore * @param db is DB object * @param rows are query result of columns to be added. */ function addColumns(db: Db, rows: ColumnQueryResult[]): void { rows.forEach((row) => { const parent = (row.parentKind === "c" ? db.typesIncludingEntities.get(row.parentOid as any, { key: "classOid" }) : db.entities.get(row.parentOid as any, { key: "oid" })) as CompositeType | Entity; parent.columns.push(new Column({ parent, ...row })); }); } /** * Adds indexes to database. * * @ignore * @param db is DB object * @param rows are query result of indexes to be added. */ function addIndexes(db: Db, rows: IndexQueryResult[]): void { rows.forEach((row) => { const parent = db.entities.get(row.tableOid, { key: "oid" }) as Table | MaterializedView; const index = new Index({ ...row, parent }); const indexExpressions = [...row.indexExpressions]; // Non column reference index expressions. row.columnPositions.forEach((position) => { // If position is 0, then it's an index attribute that is not simple column references. It is an expression which is stored in indexExpressions. const columnOrExpression = (position > 0 ? parent.columns.find((c: Column) => c.attributeNumber === position) : indexExpressions.shift()) as string | Column; index.columnsAndExpressions.push(columnOrExpression); }); parent.indexes.push(index); }); } /** * Add functions to database. * * @ignore * @param db is DB object. * @param rows are query result of functions to be added. */ function addFunctions(db: Db, rows: FunctionQueryResult[]): void { rows.forEach((row) => { const schema = db.schemas.get(row.schemaOid, { key: "oid" }) as Schema; /* istanbul ignore else */ if (row.kind === "f") schema.normalFunctions.push(new NormalFunction({ ...row, schema })); else if (row.kind === "p") schema.procedures.push(new Procedure({ ...row, schema })); else if (row.kind === "a") schema.aggregateFunctions.push(new AggregateFunction({ ...row, schema })); else if (row.kind === "w") schema.windowFunctions.push(new WindowFunction({ ...row, schema })); }); } /** * * @ignore * @param db is DB object. * @param rows are query result of triggers to be added. */ function addTriggers(db: Db, rows: TriggerQueryResult[]): void { rows.forEach((row) => { const entity = db.entities.get(row.entityOid, { key: "oid" }) as Table | View; const func = db.functions.get(row.functionOid, { key: "oid" }); entity.triggers.push(new Trigger({ ...row, function: func, parent: entity })); }); } /** * Adds constraints to database. * * @ignore * @param db is DB object * @param rows are query result of constraints to be added. */ function addConstraints(db: Db, rows: ConstraintQueryResult[]): void { const actionLetterMap: { [key in ActionLetter]: Action } = { a: Action.NoAction, r: Action.Restrict, c: Action.Cascade, n: Action.SetNull, d: Action.SetDefault, }; const matchTypeLetterMap: { [key in MatchTypeLetter]: MatchType } = { f: MatchType.Full, p: MatchType.Partial, s: MatchType.Simple, }; rows.forEach((row) => { const table = db.tables.getMaybe(row.tableOid, { key: "oid" }); const index = db.indexes.getMaybe(row.indexOid, { key: "oid" }) as Index; const domain = db.typesIncludingEntities.getMaybe(row.typeOid, { key: "oid" }) as Domain | undefined; /* istanbul ignore else */ if (table) { /* istanbul ignore else */ if (row.kind === "p") table.constraints.push(new PrimaryKey({ ...row, index, table })); else if (row.kind === "u") table.constraints.push(new UniqueConstraint({ ...row, index, table })); else if (row.kind === "x") table.constraints.push(new ExclusionConstraint({ ...row, index, table })); else if (row.kind === "c") table.constraints.push(new CheckConstraint({ ...row, table, expression: row.checkConstraintExpression })); else if (row.kind === "f") { const foreignKey = new ForeignKey({ ...row, table, index, columns: row.constrainedColumnPositions.map((pos) => table.columns.get(pos, { key: "attributeNumber" })) as Column[], onUpdate: actionLetterMap[row.onUpdate], onDelete: actionLetterMap[row.onDelete], matchType: matchTypeLetterMap[row.matchType], }); table.constraints.push(foreignKey); foreignKey.referencedTable.foreignKeysToThis.push(foreignKey); } } else if (domain) { /* istanbul ignore else */ if (row.kind === "c") { domain.checkConstraints.push(new CheckConstraint({ ...row, domain, expression: row.checkConstraintExpression })); } } }); } /** * Returns results of SQL queries of meta data. * * @ignore */ async function getQueryResultsFromDb( serverVersion: string, client: Client, includeSchemasArray?: string[], excludeSchemasArray?: string[], includeSystemSchemas?: boolean ): Promise<QueryResults> { const schemaRows = await getSchemas(client, { include: includeSchemasArray, exclude: excludeSchemasArray, system: includeSystemSchemas }); const systemSchemaRows = await getSystemSchemas(client); const schemaOids = schemaRows.map((schema) => schema.oid); const schemaOidsIncludingSystem = schemaOids.concat(systemSchemaRows.map((schema) => schema.oid)); const queryVersions = await getQueryVersionFor(serverVersion); return Promise.all([ schemaRows, systemSchemaRows, executeSqlFile(queryVersions, "type", client, schemaOidsIncludingSystem), executeSqlFile(queryVersions, "entity", client, schemaOids), executeSqlFile(queryVersions, "column", client, schemaOids), executeSqlFile(queryVersions, "index", client, schemaOids), executeSqlFile(queryVersions, "constraint", client, schemaOids), executeSqlFile(queryVersions, "function", client, schemaOids), executeSqlFile(queryVersions, "trigger", client, schemaOids), ]); } /** * Adds database objects to database. * * @ignore * @param db is DB object * @param queryResults are query results to get object details from. */ function addObjects(db: Db, queryResults: QueryResults): void { addSchemas(db, queryResults[0]); addSystemSchemas(db, queryResults[1]); addTypes(db, queryResults[2]); addEntities(db, queryResults[3]); addColumns(db, queryResults[4]); addIndexes(db, queryResults[5]); addConstraints(db, queryResults[6]); addFunctions(db, queryResults[7]); addTriggers(db, queryResults[8]); } /** * Checks whether given object are options for the `pgStructure` function. * * @param input is the input to check. * @returns whether given input are options for the `pgStructure` function. */ function isOptions(input?: Client | ClientConfig | string | Options): input is Options { if (input === undefined) return false; const optionsAvailable: Required<{ [K in keyof Options]: true }> = { envPrefix: true, name: true, commentDataToken: true, includeSchemas: true, excludeSchemas: true, includeSystemSchemas: true, foreignKeyAliasSeparator: true, foreignKeyAliasTargetFirst: true, relationNameFunctions: true, keepConnection: true, }; return Object.keys(input).some((key) => Object.prototype.hasOwnProperty.call(optionsAvailable, key)); } /** * Reverse engineers a PostgreSQL database and creates [[Db]] instance which represents given database's structure. * There are several options such as to include or exclude schemas, provide custom names to relations. Please refer to [[Options]] * for detailed explanations. * * **IMPORTANT:** Please note that if included schemas contain references to a non-included schema, this function throws exception. * (e.g. a foreign key to another schema or a type in another schema which is not included) * * @param client is either a [node-postgres client](https://node-postgres.com/api/client) or a configuration object or a connection string to create a [node-postgres client](https://node-postgres.com/api/client). * @param options are preferences to modify reverse engineering process. * @returns [[Db]] object which represents given database's structure. * * @example * const db = await pgStructure({ database: "db", user: "u", password: "pass" }, { includeSchemas: ["public"] }); */ export async function pgStructure(client?: Client | ClientConfig | string, options?: Options): Promise<Db>; /** * Reads configuration details from environment variables to create [node-postgres client](https://node-postgres.com/api/client). * Keys are upper case environment variables prefixed with `options.envPrefix` (default is `DB`). * * |Environment Varibale|[ClientConfig](https://node-postgres.com/api/client) Key| * |---|---| * |DB_DATABASE|database| * |DB_USER|user| * |DB_PASSWORD|password| * |...|...| * * @param options are preferences to modify reverse engineering process. * @returns [[Db]] object which represents given database's structure. * * @example * const db = await pgStructure({ includeSchemas: ["public"] }); * * @example * const db = await pgStructure(); // Read connection details from environmet variables. */ export async function pgStructure(options?: Options): Promise<Db>; export async function pgStructure(clientOrOptions?: Client | ClientConfig | string | Options, maybeOptions: Options = {}): Promise<Db> { const [maybePgClientOrConfig, options] = isOptions(clientOrOptions) ? [undefined, clientOrOptions] : [clientOrOptions, maybeOptions]; const pgClientOrConfig = maybePgClientOrConfig ?? getEnvValues(options.envPrefix ?? "DB"); const { client, shouldCloseConnection } = await getConnectedPgClient(pgClientOrConfig); const serverVersion = (await client.query("SHOW server_version")).rows[0].server_version; const queryResults = await getQueryResultsFromDb( serverVersion, client, arrify(options.includeSchemas), arrify(options.excludeSchemas), options.includeSystemSchemas ); const db = new Db( { name: options.name || getDatabaseName(pgClientOrConfig), serverVersion }, { commentDataToken: options.commentDataToken ?? "pg-structure", relationNameFunctions: options.relationNameFunctions ?? "short", foreignKeyAliasSeparator: options.foreignKeyAliasSeparator ?? ",", foreignKeyAliasTargetFirst: options.foreignKeyAliasTargetFirst ?? false, }, queryResults, getRelationNameFunctions(options.relationNameFunctions ?? "short") ); addObjects(db, queryResults); if (!options.keepConnection && shouldCloseConnection) client.end(); // If a connected client is provided, do not close connection. return db; } /** * Deserializes given data to create [[Db]] object. Please note that custom relation name functions are not serialized. * To serialize, provide functions as a module and use them with `{ relationNameFunctions: "my-module" }`. * * @param serializedData is serialized data of the `Db` object. * @returns [[Db]] object for given serialized data. * @example * import pgStructure, { deserialize } from "pg-structure"; * const db = await pgStructure({ database: "db", user: "u", password: "pass" }); * const serialized = db.serialize(); * const otherDb = deserialize(serialized); */ export function deserialize(serializedData: string): Db { const data = JSON.parse(serializedData); const db = new Db( { name: data.name, serverVersion: data.serverVersion }, data.config, data.queryResults, getRelationNameFunctions(data.config.relationNameFunctions) ); addObjects(db, data.queryResults); return db; }
the_stack
import { platform } from 'os'; import { chdir } from 'process'; import { debug, error, setFailed, warning, info } from '@actions/core'; import { exec } from '@actions/exec'; import { context } from '@actions/github'; import * as glob from '@actions/glob'; import { downloadToFile, getOptionalString, verifyChecksum, verifySignature, } from './utils'; import type { ExecOptions } from '@actions/exec/lib/interfaces'; const DOWNLOAD_URL = `https://codeclimate.com/downloads/test-reporter/test-reporter-latest-${platform()}-amd64`; const EXECUTABLE = './cc-reporter'; export const CODECLIMATE_GPG_PUBLIC_KEY_ID = '9BD9E2DD46DA965A537E5B0A5CBF320243B6FD85' as const; const CODECLIMATE_GPG_PUBLIC_KEY_URL = `https://keys.openpgp.org/vks/v1/by-fingerprint/${CODECLIMATE_GPG_PUBLIC_KEY_ID}` as const; const DEFAULT_COVERAGE_COMMAND = ''; const DEFAULT_WORKING_DIRECTORY = ''; const DEFAULT_CODECLIMATE_DEBUG = 'false'; const DEFAULT_COVERAGE_LOCATIONS = ''; const DEFAULT_VERIFY_DOWNLOAD = 'true'; function prepareEnv() { const env = process.env as { [key: string]: string }; if (process.env.GITHUB_SHA !== undefined) env.GIT_COMMIT_SHA = process.env.GITHUB_SHA; if (process.env.GITHUB_REF !== undefined) env.GIT_BRANCH = process.env.GITHUB_REF; if (env.GIT_BRANCH) env.GIT_BRANCH = env.GIT_BRANCH.replace(/^refs\/heads\//, ''); // Remove 'refs/heads/' prefix (See https://github.com/paambaati/codeclimate-action/issues/42) if (process.env.GITHUB_EVENT_NAME === 'pull_request') { env.GIT_BRANCH = process.env.GITHUB_HEAD_REF || env.GIT_BRANCH; // Report correct branch for PRs (See https://github.com/paambaati/codeclimate-action/issues/86) env.GIT_COMMIT_SHA = context.payload.pull_request?.['head']?.['sha']; // Report correct SHA for the head branch (See https://github.com/paambaati/codeclimate-action/issues/140) } return env; } async function getLocationLines( coverageLocationPatternsParam: string ): Promise<Array<string>> { const coverageLocationPatternsLines = coverageLocationPatternsParam .split(/\r?\n/) .filter((pat) => pat) .map((pat) => pat.trim()); const patternsAndFormats = coverageLocationPatternsLines.map((line) => { const lineParts = line.split(':'); const format = lineParts.slice(-1)[0]; const pattern = lineParts.slice(0, -1)[0]; return { format, pattern }; }); const pathsWithFormat = await Promise.all( patternsAndFormats.map(async ({ format, pattern }) => { const globber = await glob.create(pattern); const paths = await globber.glob(); const pathsWithFormat = paths.map( (singlePath) => `${singlePath}:${format}` ); return pathsWithFormat; }) ); const coverageLocationLines = ([] as Array<string>).concat( ...pathsWithFormat ); return coverageLocationLines; } export function run( downloadUrl: string = DOWNLOAD_URL, executable: string = EXECUTABLE, coverageCommand: string = DEFAULT_COVERAGE_COMMAND, workingDirectory: string = DEFAULT_WORKING_DIRECTORY, codeClimateDebug: string = DEFAULT_CODECLIMATE_DEBUG, coverageLocationsParam: string = DEFAULT_COVERAGE_LOCATIONS, coveragePrefix?: string, verifyDownload: string = DEFAULT_VERIFY_DOWNLOAD ): Promise<void> { return new Promise(async (resolve, reject) => { if (platform() === 'win32') { return reject(new Error('CC Reporter is not supported on Windows!')); } let lastExitCode = 1; if (workingDirectory) { debug(`Changing working directory to ${workingDirectory}`); try { chdir(workingDirectory); lastExitCode = 0; debug('✅ Changing working directory completed...'); } catch (err) { error((err as Error).message); setFailed('🚨 Changing working directory failed!'); return reject(err); } } try { debug(`ℹ️ Downloading CC Reporter from ${downloadUrl} ...`); await downloadToFile(downloadUrl, executable); debug('✅ CC Reporter downloaded...'); } catch (err) { error((err as Error).message); setFailed('🚨 CC Reporter download failed!'); warning(`Could not download ${downloadUrl}`); warning( `Please check if your platform is supported — see https://docs.codeclimate.com/docs/configuring-test-coverage#section-locations-of-pre-built-binaries` ); return reject(err); } if (verifyDownload === 'true') { const checksumUrl = `${downloadUrl}.sha256`; const checksumFilePath = `${executable}.sha256`; const signatureUrl = `${downloadUrl}.sha256.sig`; const signatureFilePath = `${executable}.sha256.sig`; const ccPublicKeyFilePath = 'public-key.asc'; try { debug(`ℹ️ Verifying CC Reporter checksum...`); await downloadToFile(checksumUrl, checksumFilePath); const checksumVerified = await verifyChecksum( executable, checksumFilePath, 'sha256' ); if (!checksumVerified) throw new Error('CC Reporter checksum does not match!'); debug('✅ CC Reported checksum verification completed...'); } catch (err) { error((err as Error).message); setFailed('🚨 CC Reporter checksum verfication failed!'); return reject(err); } try { debug(`ℹ️ Verifying CC Reporter GPG signature...`); await downloadToFile(signatureUrl, signatureFilePath); await downloadToFile( CODECLIMATE_GPG_PUBLIC_KEY_URL, ccPublicKeyFilePath ); const signatureVerified = await verifySignature( checksumFilePath, signatureFilePath, ccPublicKeyFilePath ); if (!signatureVerified) throw new Error('CC Reporter GPG signature is invalid!'); debug('✅ CC Reported GPG signature verification completed...'); } catch (err) { error((err as Error).message); setFailed('🚨 CC Reporter GPG signature verfication failed!'); return reject(err); } } const execOpts: ExecOptions = { env: prepareEnv(), }; try { lastExitCode = await exec(executable, ['before-build'], execOpts); if (lastExitCode !== 0) { throw new Error( `Coverage after-build exited with code ${lastExitCode}` ); } debug('✅ CC Reporter before-build checkin completed...'); } catch (err) { error((err as Error).message); setFailed('🚨 CC Reporter before-build checkin failed!'); return reject(err); } if (coverageCommand) { try { lastExitCode = await exec(coverageCommand, undefined, execOpts); if (lastExitCode !== 0) { throw new Error(`Coverage run exited with code ${lastExitCode}`); } debug('✅ Coverage run completed...'); } catch (err) { error((err as Error).message); setFailed('🚨 Coverage run failed!'); return reject(err); } } else { info( `ℹ️ 'coverageCommand' not set, so skipping building coverage report!` ); } const coverageLocations = await getLocationLines(coverageLocationsParam); if (coverageLocations.length > 0) { debug( `Parsing ${ coverageLocations.length } coverage location(s) — ${coverageLocations} (${typeof coverageLocations})` ); // Run format-coverage on each location. const parts: Array<string> = []; for (const i in coverageLocations) { const [location, type] = coverageLocations[i].split(':'); if (!type) { const err = new Error(`Invalid formatter type ${type}`); debug( `⚠️ Could not find coverage formatter type! Found ${ coverageLocations[i] } (${typeof coverageLocations[i]})` ); error(err.message); setFailed( '🚨 Coverage formatter type not set! Each coverage location should be of the format <file_path>:<coverage_format>' ); return reject(err); } const commands = [ 'format-coverage', location, '-t', type, '-o', `codeclimate.${i}.json`, ]; if (codeClimateDebug === 'true') commands.push('--debug'); if (coveragePrefix) { commands.push('--prefix', coveragePrefix); } parts.push(`codeclimate.${i}.json`); try { lastExitCode = await exec(executable, commands, execOpts); if (lastExitCode !== 0) { throw new Error( `Coverage formatter exited with code ${lastExitCode}` ); } } catch (err) { error((err as Error).message); setFailed('🚨 CC Reporter coverage formatting failed!'); return reject(err); } } // Run sum coverage. const sumCommands = [ 'sum-coverage', ...parts, '-p', `${coverageLocations.length}`, '-o', `coverage.total.json`, ]; if (codeClimateDebug === 'true') sumCommands.push('--debug'); try { lastExitCode = await exec(executable, sumCommands, execOpts); if (lastExitCode !== 0) { throw new Error( `Coverage sum process exited with code ${lastExitCode}` ); } } catch (err) { error((err as Error).message); setFailed('🚨 CC Reporter coverage sum failed!'); return reject(err); } // Upload to Code Climate. const uploadCommands = ['upload-coverage', '-i', `coverage.total.json`]; if (codeClimateDebug === 'true') uploadCommands.push('--debug'); try { lastExitCode = await exec(executable, uploadCommands, execOpts); if (lastExitCode !== 0) { throw new Error(`Coverage upload exited with code ${lastExitCode}`); } debug('✅ CC Reporter upload coverage completed!'); return resolve(); } catch (err) { error((err as Error).message); setFailed('🚨 CC Reporter coverage upload failed!'); return reject(err); } } try { const commands = ['after-build', '--exit-code', lastExitCode.toString()]; if (codeClimateDebug === 'true') commands.push('--debug'); if (coveragePrefix) { commands.push('--prefix', coveragePrefix); } lastExitCode = await exec(executable, commands, execOpts); if (lastExitCode !== 0) { throw new Error( `Coverage after-build exited with code ${lastExitCode}` ); } debug('✅ CC Reporter after-build checkin completed!'); return resolve(); } catch (err) { error((err as Error).message); setFailed('🚨 CC Reporter after-build checkin failed!'); return reject(err); } }); } if (require.main === module) { const coverageCommand = getOptionalString( 'coverageCommand', DEFAULT_COVERAGE_COMMAND ); const workingDirectory = getOptionalString( 'workingDirectory', DEFAULT_WORKING_DIRECTORY ); const codeClimateDebug = getOptionalString( 'debug', DEFAULT_CODECLIMATE_DEBUG ); const coverageLocations = getOptionalString( 'coverageLocations', DEFAULT_COVERAGE_LOCATIONS ); const coveragePrefix = getOptionalString('prefix'); const verifyDownload = getOptionalString( 'verifyDownload', DEFAULT_VERIFY_DOWNLOAD ); run( DOWNLOAD_URL, EXECUTABLE, coverageCommand, workingDirectory, codeClimateDebug, coverageLocations, coveragePrefix, verifyDownload ); }
the_stack
declare module 'twit' { import {IncomingMessage} from 'http'; import {EventEmitter} from 'events'; namespace Twit { export type StreamEndpoint = 'statuses/filter' | 'statuses/sample' | 'statuses/firehose' | 'user' | 'site'; export namespace Twitter { export type ResultType = 'mixed' | 'popular' | 'recent'; // See https://dev.twitter.com/overview/api/tweets#obj-contributors export interface Contributors { id: number; id_str: number; screen_name: string; } // See https://dev.twitter.com/overview/api/entities export interface HashtagEntity { indices: [number, number]; text: string; } export interface Size { h: number; w: number; resize: 'crop' | 'fit'; } export interface Sizes { large: Size; medium: Size; small: Size; thumb: Size; } export interface VideoVariant { bitrate?: number; content_type: string; url: string; } export interface VideoInfo { aspect_ratio: [number, number]; duration_millis?: number; variants: VideoVariant[]; } export interface MediaEntity { display_url: string; expanded_url: string; id: number; id_str: string; indices: [number, number]; media_url: string; media_url_https: string; sizes: Sizes; source_status_id?: number; source_status_id_str?: string; type: string; url: string; video_info?: VideoInfo; } export interface UrlEntity { display_url: string; expanded_url: string; indices: [number, number] | null; url: string; } export interface UserMentionEntity { id: number; id_str: string; indices: [number, number]; name: string; screen_name: string; } export interface SymbolEntity { indices: [number, number]; text: string; } export interface Entities { hashtags?: HashtagEntity[]; media?: MediaEntity[]; symbols?: SymbolEntity[]; urls?: UrlEntity[]; user_mentions?: UserMentionEntity[]; } export interface UserEntities { description?: Entities; url?: Entities; } // See https://dev.twitter.com/overview/api/users export interface User { contributors_enabled: boolean; created_at: string; default_profile: boolean; default_profile_image: boolean; description: string; entities: UserEntities; favourites_count: number; follow_request_sent?: boolean; followers_count: number; following?: boolean; friends_count: number; geo_enabled?: boolean; id: number; id_str: string; is_translator?: boolean; lang: string; listed_count: number; location: string; name: string; notifications?: boolean; profile_background_color: string; profile_background_image_url: string; profile_background_image_url_https: string; profile_background_tile: boolean; profile_banner_url?: string; profile_image_url: string; profile_image_url_https: string; profile_link_color: string; profile_sidebar_border_color: string; profile_sidebar_fill_color: string; profile_text_color: string; profile_use_background_image: boolean; protected: boolean; screen_name: string; show_all_inline_media?: boolean; status?: Status; statuses_count: number; time_zone?: string; url: string; utc_offset?: number; verified: boolean; withheld_in_countries?: string; withheld_scope?: string; } // See https://dev.twitter.com/overview/api/places export interface PlaceAttribute { 'app:id': string; iso3: string; locality: string; phone: string; postal_code: string; region: string; street_address: string; twitter: string; url: string; } export interface Place { attributes: PlaceAttribute; bounding_box: GeoJSON.Polygon; contained_within: Place[]; country: string; country_code: string; full_name: string; geometry: GeoJSON.Point; id: string; name: string; place_type: string; url: string; } // See https://dev.twitter.com/overview/api/tweets export interface Status { id: number; id_str: string; annotations?: Object; contributors?: Contributors[]; coordinates?: GeoJSON.Point; current_user_retweet?: { id: number; id_str: number; }; created_at: string; entities: Entities; extended_entities: Entities; favorite_count: number; favorited: boolean; filter_level: 'none' | 'low' | 'medium'; geo?: Object; in_reply_to_screen_name?: string; in_reply_to_status_id?: number; in_reply_to_status_id_str?: string; in_reply_to_user_id?: number; in_reply_to_user_id_str?: string; is_quote_status: boolean; lang?: string; place?: Place; possibly_sensitive?: boolean; quoted_status?: Status; quoted_status_id?: number; quoted_status_id_str?: string; retweet_count: number; retweeted: boolean; retweeted_status?: Status; scopes?: Object; source?: string; text: string; truncated: boolean; user: User; withheld_copyright?: boolean; withheld_in_countries?: string[]; withheld_scope?: string; } interface DirectMessage { created_at: string; entities: Entities; id: number; id_str: string; recipient: User; recipient_id: number; recipient_screen_name: string; sender: User; sender_id: number; sender_screen_name: string; text: string; } export interface Metadata { completed_in?: number; count?: number; max_id?: number; max_id_str?: string; next_results?: string; query?: string; refresh_url?: string; since_id?: number; since_id_str?: string; } export interface SearchResponse { search_metadata: Metadata; statuses: Status[]; } export interface Error { code: number; message: string; } export interface StreamingDeleteStatus { id: number; id_str: string; user_id: number; user_id_str: string; } export interface StreamingDeleteEvent { delete: { status: StreamingDeleteStatus; timestamp: string; }; } export interface StreamingFriendsEvent { friends: number[] | string[]; } export interface StreamingLimitEvent { limit: { track: number; }; } export interface StreamingDisconnectEvent { disconnect: { code: number; reason: string; stream_name: string; }; } export interface StreamingWarningEvent { warning: { code: string; message: string; percent_full: number; }; } export interface StreamEvent { created_at: string; event: string; source?: User; target?: User; target_object?: any; } export interface StreamTargetEvent { created_at: string; event: string; source: User; target: User; target_object?: any; } } interface MediaParam { file_path: string; } interface Params { // search/tweets q?: string; geocode?: string; lang?: string; locale?: string; result_type?: Twitter.ResultType; count?: number; results_per_page?: number; until?: string; since_id?: string; max_id?: string; include_entities?: boolean; // Other params from various endpoints media_id?: string; media_ids?: string[]; alt_text?: { text?: string }; media_data?: Buffer | string; screen_name?: string; id?: string; slug?: string; status?: string; } export interface PromiseResponse { data: any; responde: IncomingMessage; } export interface ConfigKeys { consumer_key: string; consumer_secret: string; access_token?: string; access_token_secret?: string; } export interface Options extends ConfigKeys { app_only_auth?: boolean; timeout_ms?: number; trusted_cert_fingerprints?: string[]; } export interface ApiError extends Error { allErrors: Twitter.Error[]; code: number; statusCode: number; twitterReply: IncomingMessage; } export type Callback = (err: ApiError, result: any, response: IncomingMessage) => void; export class Stream extends EventEmitter { start(): void; stop(): void; on(event: 'blocked', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'connect', cb: (request: any) => void): this; on(event: 'connected', cb: (response: IncomingMessage) => void): this; on(event: 'delete', cb: (e: Twitter.StreamingDeleteEvent) => void): this; on(event: 'direct_message', cb: (msg: any) => void): this; on(event: 'disconnect', cb: (d: Twitter.StreamingDisconnectEvent) => void): this; on(event: 'error', cb: (e: Twit.ApiError) => void): this; on(event: 'favorite', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'favorited_retweet', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'follow', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'friends', cb: (friend_ids: Twitter.StreamingFriendsEvent) => void): this; on(event: 'limit', cb: (l: Twitter.StreamingLimitEvent) => void): this; on(event: 'list_created', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'list_destroyed', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'list_member_added', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'list_member_removed', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'list_updated', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'list_user_subscribed', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'list_user_unsubscribed', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'message', cb: (msg: any) => void): this; on(event: 'mute', cb: (e: Twitter.StreamTargetEvent) => void): this; on(event: 'quoted_tweet', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'reconnect', cb: (request: any, response: IncomingMessage, connectInterval: number) => void): this; on(event: 'retweeted_retweet', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'scrub_geo', cb: (msg: any) => void): this; on(event: 'status_withheld', cb: (msg: any) => void): this; on(event: 'tweet', cb: (tw: Twitter.Status) => void): this; on(event: 'unblocked', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'unfavorite', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'unfollow', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'unknown_user_event', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'unmute', cb: (e: Twitter.StreamTargetEvent) => void): this; on(event: 'user_event', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'user_update', cb: (e: Twitter.StreamEvent) => void): this; on(event: 'user_withheld', cb: (msg: any) => void): this; on(event: 'warning', cb: (warning: Twitter.StreamingWarningEvent) => void): this; on(event: string, cb: Function): this; } } class Twit { // See https://github.com/ttezel/twit#var-t--new-twitconfig constructor(config: Twit.Options); // See https://github.com/ttezel/twit#tgetpath-params-callback get(path: string, callback: Twit.Callback): void; get(path: string, params: Twit.Params, callback: Twit.Callback): void; get(path: string, params?: Twit.Params): Promise<Twit.PromiseResponse>; // See https://github.com/ttezel/twit#tpostpath-params-callback post(path: string, callback: Twit.Callback): void; post(path: string, params: Twit.Params, callback: Twit.Callback): void; post(path: string, params?: Twit.Params): Promise<Twit.PromiseResponse>; // See https://github.com/ttezel/twit#tpostmediachunkedparams-callback postMediaChunked(media: Twit.MediaParam, callback: Twit.Callback): void; // See https://github.com/ttezel/twit#tgetauth getAuth(): Twit.Options; // See https://github.com/ttezel/twit#tsetauthtokens setAuth(tokens: Twit.ConfigKeys): void; // See https://github.com/ttezel/twit#tstreampath-params stream(path: Twit.StreamEndpoint, params?: Twit.Params): Twit.Stream; } export = Twit; }
the_stack
import {runIfMain} from "../../deps/mocha.ts"; import {expect} from "../../deps/chai.ts"; import {Connection, PromiseUtils} from "../../../src/index.ts"; import {AuroraDataApiDriver} from "../../../src/driver/aurora-data-api/AuroraDataApiDriver.ts"; // TODO(uki00a) uncomment this when CockroachDriver is implemented. // import {CockroachDriver} from "../../../src/driver/cockroachdb/CockroachDriver.ts"; import {MysqlDriver} from "../../../src/driver/mysql/MysqlDriver.ts"; import {OracleDriver} from "../../../src/driver/oracle/OracleDriver.ts"; // TODO(uki00a) uncomment this when PostgresDriver is implemented. // import {PostgresDriver} from "../../../src/driver/postgres/PostgresDriver.ts"; import {SapDriver} from "../../../src/driver/sap/SapDriver.ts"; import {AbstractSqliteDriver} from "../../../src/driver/sqlite-abstract/AbstractSqliteDriver.ts"; import {SqlServerDriver} from "../../../src/driver/sqlserver/SqlServerDriver.ts"; import {closeTestingConnections, createTestingConnections, reloadTestingDatabases} from "../../utils/test-utils.ts"; import {Post} from "./entity/Post.ts"; import {Album} from "./entity/Album.ts"; import {Category} from "./entity/Category.ts"; import {Faculty} from "./entity/Faculty.ts"; import {Photo} from "./entity/Photo.ts"; import {Question} from "./entity/Question.ts"; import {Student} from "./entity/Student.ts"; import {Teacher} from "./entity/Teacher.ts"; import {PostVersion} from "./entity/PostVersion.ts"; describe("schema builder > change column", () => { let connections: Connection[]; before(async () => { connections = await createTestingConnections({ entities: [Post, Album, Category, Faculty, Photo, PostVersion, Question, Student, Teacher], schemaCreate: true, dropSchema: true, }); }); beforeEach(() => reloadTestingDatabases(connections)); after(() => closeTestingConnections(connections)); it("should correctly change column name", () => PromiseUtils.runInSequence(connections, async connection => { const postMetadata = connection.getMetadata(Post); const nameColumn = postMetadata.findColumnWithPropertyName("name")!; nameColumn.propertyName = "title"; nameColumn.build(connection); await connection.synchronize(); const queryRunner = connection.createQueryRunner(); const postTable = await queryRunner.getTable("post"); await queryRunner.release(); expect(postTable!.findColumnByName("name")).to.be.undefined; postTable!.findColumnByName("title")!.should.be.exist; // revert changes nameColumn.propertyName = "name"; nameColumn.build(connection); })); it("should correctly change column length", () => PromiseUtils.runInSequence(connections, async connection => { const postMetadata = connection.getMetadata(Post); const nameColumn = postMetadata.findColumnWithPropertyName("name")!; const textColumn = postMetadata.findColumnWithPropertyName("text")!; nameColumn.length = "500"; textColumn.length = "300"; await connection.synchronize(); const queryRunner = connection.createQueryRunner(); const postTable = await queryRunner.getTable("post"); await queryRunner.release(); postTable!.findColumnByName("name")!.length.should.be.equal("500"); postTable!.findColumnByName("text")!.length.should.be.equal("300"); if (connection.driver instanceof MysqlDriver || connection.driver instanceof AuroraDataApiDriver || connection.driver instanceof SapDriver) { postTable!.indices.length.should.be.equal(2); } else { postTable!.uniques.length.should.be.equal(2); } // revert changes nameColumn.length = "255"; textColumn.length = "255"; })); it("should correctly change column type", () => PromiseUtils.runInSequence(connections, async connection => { const postMetadata = connection.getMetadata(Post); const versionColumn = postMetadata.findColumnWithPropertyName("version")!; versionColumn.type = "int"; // in test we must manually change referenced column too, but in real sync, it changes automatically const postVersionMetadata = connection.getMetadata(PostVersion); const postVersionColumn = postVersionMetadata.findColumnWithPropertyName("post")!; postVersionColumn.type = "int"; await connection.synchronize(); const queryRunner = connection.createQueryRunner(); const postVersionTable = await queryRunner.getTable("post_version"); await queryRunner.release(); postVersionTable!.foreignKeys.length.should.be.equal(1); // revert changes versionColumn.type = "varchar"; postVersionColumn.type = "varchar"; })); it("should correctly make column primary and generated", () => PromiseUtils.runInSequence(connections, async connection => { // CockroachDB does not allow changing PK if (false/*connection.driver instanceof CockroachDriver*/) // TODO(uki00a) uncomment this when CockroachDriver is implemented. return; const postMetadata = connection.getMetadata(Post); const idColumn = postMetadata.findColumnWithPropertyName("id")!; const versionColumn = postMetadata.findColumnWithPropertyName("version")!; idColumn.isGenerated = true; idColumn.generationStrategy = "increment"; // SQLite does not support AUTOINCREMENT with composite primary keys // Oracle does not support both unique and primary attributes on such column if (!(connection.driver instanceof AbstractSqliteDriver) && !(connection.driver instanceof OracleDriver)) versionColumn.isPrimary = true; await connection.synchronize(); const queryRunner = connection.createQueryRunner(); const postTable = await queryRunner.getTable("post"); await queryRunner.release(); postTable!.findColumnByName("id")!.isGenerated.should.be.true; postTable!.findColumnByName("id")!.generationStrategy!.should.be.equal("increment"); // SQLite does not support AUTOINCREMENT with composite primary keys if (!(connection.driver instanceof AbstractSqliteDriver) && !(connection.driver instanceof OracleDriver)) postTable!.findColumnByName("version")!.isPrimary.should.be.true; // revert changes idColumn.isGenerated = false; idColumn.generationStrategy = undefined; versionColumn.isPrimary = false; })); it("should correctly change column `isGenerated` property when column is on foreign key", () => PromiseUtils.runInSequence(connections, async connection => { const teacherMetadata = connection.getMetadata("teacher"); const idColumn = teacherMetadata.findColumnWithPropertyName("id")!; idColumn.isGenerated = false; idColumn.generationStrategy = undefined; await connection.synchronize(); const queryRunner = connection.createQueryRunner(); const teacherTable = await queryRunner.getTable("teacher"); await queryRunner.release(); teacherTable!.findColumnByName("id")!.isGenerated.should.be.false; expect(teacherTable!.findColumnByName("id")!.generationStrategy).to.be.undefined; // revert changes idColumn.isGenerated = true; idColumn.generationStrategy = "increment"; })); it("should correctly change non-generated column on to uuid-generated column", () => PromiseUtils.runInSequence(connections, async connection => { // CockroachDB does not allow changing PK if (false/*connection.driver instanceof CockroachDriver*/) // TODO(uki00a) uncomment this when CockroachDriver is implemented. return; const queryRunner = connection.createQueryRunner(); if (false/*connection.driver instanceof PostgresDriver*/) // TODO(uki00a) uncomment this when PostgresDriver is implemented. await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`); const postMetadata = connection.getMetadata(Post); const idColumn = postMetadata.findColumnWithPropertyName("id")!; idColumn.isGenerated = true; idColumn.generationStrategy = "uuid"; // depending on driver, we must change column and referenced column types if (false/*connection.driver instanceof PostgresDriver || connection.driver instanceof CockroachDriver*/) { // TODO(uki00a) uncomment this when PostgresDriver is implemented. // TODO(uki00a) uncomment this when CockroachDriver is implemented. idColumn.type = "uuid"; } else if (connection.driver instanceof SqlServerDriver) { idColumn.type = "uniqueidentifier"; } else { idColumn.type = "varchar"; } await connection.synchronize(); const postTable = await queryRunner.getTable("post"); await queryRunner.release(); if (/*connection.driver instanceof PostgresDriver || */connection.driver instanceof SqlServerDriver/* || connection.driver instanceof CockroachDriver*/) { // TODO(uki00a) uncomment this when PostgresDriver is implemented. // TODO(uki00a) uncomment this when CockroachDriver is implemented. postTable!.findColumnByName("id")!.isGenerated.should.be.true; postTable!.findColumnByName("id")!.generationStrategy!.should.be.equal("uuid"); } else { // other driver does not natively supports uuid type postTable!.findColumnByName("id")!.isGenerated.should.be.false; expect(postTable!.findColumnByName("id")!.generationStrategy).to.be.undefined; } // revert changes idColumn.isGenerated = false; idColumn.generationStrategy = undefined; idColumn.type = "int"; postMetadata.generatedColumns.splice(postMetadata.generatedColumns.indexOf(idColumn), 1); postMetadata.hasUUIDGeneratedColumns = false; })); it("should correctly change generated column generation strategy", () => PromiseUtils.runInSequence(connections, async connection => { // CockroachDB does not allow changing PK if (false/*connection.driver instanceof CockroachDriver*/) // TODO(uki00a) uncomment this when CockroachDriver is implemented. return; const teacherMetadata = connection.getMetadata("teacher"); const studentMetadata = connection.getMetadata("student"); const idColumn = teacherMetadata.findColumnWithPropertyName("id")!; const teacherColumn = studentMetadata.findColumnWithPropertyName("teacher")!; idColumn.generationStrategy = "uuid"; // depending on driver, we must change column and referenced column types if (false/*connection.driver instanceof PostgresDriver || connection.driver instanceof CockroachDriver*/) { // TODO(uki00a) uncomment this when PostgresDriver is implemented. // TODO(uki00a) uncomment this when CockroachDriver is implemented. idColumn.type = "uuid"; teacherColumn.type = "uuid"; } else if (connection.driver instanceof SqlServerDriver) { idColumn.type = "uniqueidentifier"; teacherColumn.type = "uniqueidentifier"; } else { idColumn.type = "varchar"; teacherColumn.type = "varchar"; } await connection.synchronize(); const queryRunner = connection.createQueryRunner(); const teacherTable = await queryRunner.getTable("teacher"); await queryRunner.release(); if (/*connection.driver instanceof PostgresDriver || */connection.driver instanceof SqlServerDriver) { // TODO(uki00a) uncomment this when PostgresDriver is implemented. teacherTable!.findColumnByName("id")!.isGenerated.should.be.true; teacherTable!.findColumnByName("id")!.generationStrategy!.should.be.equal("uuid"); } else { // other driver does not natively supports uuid type teacherTable!.findColumnByName("id")!.isGenerated.should.be.false; expect(teacherTable!.findColumnByName("id")!.generationStrategy).to.be.undefined; } // revert changes idColumn.isGenerated = true; idColumn.generationStrategy = "increment"; idColumn.type = "int"; teacherColumn.type = "int"; })); }); runIfMain(import.meta);
the_stack
import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import { empty } from 'rxjs/observable/empty'; import { toPayload, Actions } from '@ngrx/effects'; import { async } from 'rxjs/scheduler/async'; import { Action, Store } from '@ngrx/store'; import { Entities, Entity } from './entity.model'; import { typeFor, PayloadAction, PayloadActions, completeAssign } from '../util'; import { actions, EntityAction } from './entity.actions'; import * as EntityActions from './entity.actions'; import * as sliceFunctions from '../slice/slice.functions'; import { RootState } from '../'; import { DataService } from '../../services/data.service'; export function addEntityToStore<T extends Entity>(state: Entities<T>, action: EntityActions.Add<T> | EntityActions.Load<T>): Entities<T> { const entities = completeAssign({}, state.entities); const newEntity = reduceOne(state, null, action); newEntity.slice = state; entities[newEntity.id] = { ...newEntity, id: '' + newEntity.id }; const newState = completeAssign({}, state, { ids: Object.keys(entities), entities, selectedEntityId: action.payload.id }); return newState; }; /** * @whatItDoes updates a given slice with a whole new set of entities in one fell swoop * * @param state the set of entities * @param action needs a payload that is an array of entities */ export function addEntitiesToStore<T extends Entity>(state: Entities<T>, action: EntityActions.Update<T>): Entities<T> { const entities = action.payload.entities.reduce(function(map, obj) { map[obj.id] = completeAssign({}, state.initialEntity, obj, { id: '' + obj.id, dirty: false }); return map; }, {}); return completeAssign({}, state, { ids: Object.keys(entities), entities }); }; /* * Delete the property from state.entities, the element from state.ids and * if the one being deleted is the selectedEntity, then select a different one. * * Only delete pessimistically */ export function deleteEntity<T extends Entity>(state: Entities<T>, action: EntityActions.Delete<T> | EntityActions.DeleteTemp<T>): Entities<T> { const entities = completeAssign({}, state.entities); const id = action.payload.id; delete entities[id]; const idx = state.ids.indexOf(id); const lastIdx = state.ids.length > 1 ? state.ids.length - 2 : null const newIdx = idx > 0 ? idx - 1 : lastIdx; const selectedEntityId = idx === -1 ? state.selectedEntityId : state.ids[newIdx]; const i = state.ids.findIndex((findId) => findId === id); const ids = [...state.ids.slice(0, i), ...state.ids.slice(i + 1)]; const newState = completeAssign({}, state, { entities, ids, selectedEntityId }); return newState; }; /** * Called from OnDestroy hooks and from dataService after a successful add to remove unsaved records with TEMP ID */ export function deleteTemp<T extends Entity>(state: Entities<T>, action: EntityActions.DeleteTemp<T>): Entities<T> { let newState = state; const entities = completeAssign({}, state.entities); if (entities[action.payload.id]) { newState = deleteEntity<T>(state, action); } return newState; } export function select<T extends Entity>(state: Entities<T>, action: EntityActions.Select<T>): Entities<T> { return completeAssign({}, state, { selectedEntityId: action.payload.id }); }; export function selectNext<T extends Entity>(state: Entities<T>, action: EntityActions.SelectNext<T>): Entities<T> { let ix = 1 + state.ids.indexOf(state.selectedEntityId); if (ix >= state.ids.length) { ix = 0; } return completeAssign({}, state, { selectedEntityId: state.ids[ix] }); }; export function unload<T extends Entity>(state: Entities<T>, action: EntityActions.Select<T>): Entities<T> { return completeAssign({}, state, { entities: {}, ids: [], selectedEntityId: null, loaded: false }); }; /** * Add entities in the action's payload into the state if they are not yet there * * @param state * @param action */ export function union<T extends Entity>(state: Entities<T>, action: EntityActions.LoadSuccess<T>) { const entities = action.payload; let newEntities = entities.filter((entity) => !state.entities[entity.id]); const newEntityIds = newEntities.map((entity) => entity.id); newEntities = newEntities.reduce((ents: { [id: string]: T }, entity: T) => { return completeAssign(ents, { [entity.id]: entity }); }, {}); return completeAssign({}, state, { ids: [...state.ids, ...newEntityIds], entities: completeAssign({}, state.entities, newEntities), selectedEntityId: state.selectedEntityId }); } /** * @whatItDoes updates, patches, sets loading, unsets dirty (for temps) or sets deleteMe of a single entity * * @param state the set of entities * @param action needs a payload that has an id */ export function update<T extends Entity>(state: Entities<T>, action: EntityActions.Update<T>): Entities<T> { // for ADD actions, there may or may not be a temporary entity whose dirty must be set to true // so skip this for ADDs without that if (!state.entities[action.payload.id]) { return state; } const entities = completeAssign({}, state.entities); const id = action.payload.id; entities[id] = reduceOne(state, entities[id], action); return completeAssign({}, state, { ids: Object.keys(entities), entities }); }; export function patchEach<T extends Entity>(state: Entities<T>, action: any): Entities<T> { const entities = completeAssign({}, state.entities); for (const id of Object.keys(entities)) { entities[id] = completeAssign({}, entities[id], action.payload); } return completeAssign({}, state, { entities }); }; function reduceOne<T extends Entity>(state: Entities<T>, entity: T = null, action: EntityAction<T>): T { // console.log('reduceOne entity:' + JSON.stringify(entity) + ' ' + action.type) let newState; switch (action.type) { // this will possibly save changes to a TEMP entity case typeFor(state.slice, actions.ADD): case typeFor(state.slice, actions.ADD_TEMP): case typeFor(state.slice, actions.ADD_OPTIMISTICALLY): // dirty serves to distinguish temp entities that are // being processed on the server from those that aren't newState = completeAssign({}, state.initialEntity, action.payload, { dirty: true }); break; case typeFor(state.slice, actions.DELETE): newState = completeAssign({}, entity, action.payload, { deleteMe: true }); break; case typeFor(state.slice, actions.DELETE_FAIL): newState = completeAssign({}, entity, action.payload, { deleteMe: false }); break; case typeFor(state.slice, actions.UPDATE): newState = completeAssign({}, state.initialEntity, action.payload, { dirty: true }); case typeFor(state.slice, actions.PATCH): newState = completeAssign({}, entity, action.payload, { dirty: true }); break; case typeFor(state.slice, actions.RESTORE_TEMP): newState = completeAssign({}, entity, { dirty: false }); break; case typeFor(state.slice, actions.ADD_SUCCESS): // entity could be a client-side-created object with client-side state not returned by // the server. If so, preserve this state by having entity as part of this newState = completeAssign({}, state.initialEntity, entity, action.payload, { dirty: false }); break; case typeFor(state.slice, actions.LOAD_SUCCESS): // maybe remove initialEntity. it is merged in the effect newState = completeAssign({}, state.initialEntity, action.payload, { dirty: false }); break; case typeFor(state.slice, actions.UPDATE_SUCCESS): case typeFor(state.slice, actions.PATCH_SUCCESS): newState = completeAssign({}, entity, action.payload, { dirty: false }); break; default: newState = entity; } return newState; }; /** * * Effects * */ export function loadFromRemote$(actions$: PayloadActions, slice: keyof RootState, dataService: DataService, store: Store<RootState>, initialEntity: Entity, debounce = 0, scheduler?, loadIndividually = true): Observable<Action> { // TODO: should return PayloadAction return actions$ .ofType(typeFor(slice, actions.LOAD), typeFor(slice, actions.ASYNC_SUCCESS)) .debounceTime(debounce, this.scheduler || async) .withLatestFrom(store) .switchMap(([action, state]) => { // First this happens // for actions.LOAD - dispatch a AsyncSuccess let o: Observable<any>; if (action.type === typeFor(slice, actions.LOAD)) { if (action.payload && action.payload.query === '') { return empty(); } const nextSearch$ = actions$.ofType(typeFor(slice, actions.LOAD)).skip(1); if (!action.payload) { o = dataService.getEntities(slice, null, state); } else if (action.payload && action.payload.query) { o = dataService.getEntities(slice, action.payload.query, state); } else { o = dataService.getEntity(slice, action.payload.id, state, store); } return o .takeUntil(nextSearch$) .mergeMap((responseObject) => Observable.of(new EntityActions.AsyncSuccess(slice, responseObject))) .catch((err) => { console.log(err); return Observable.of(new EntityActions.AsyncFail(slice, null)); }); } // Then this happens // for actions.ASYNC_SUCCESS - dispatch a LoadSuccess for each entity returned else { // action.type === typeFor(slice, actions.ASYNC_SUCCESS) if (loadIndividually && Array.isArray(action.payload.entities)) { o = Observable.from(action.payload.entities); return o.map((responseEntity) => new EntityActions.LoadSuccess(slice, completeAssign({}, initialEntity, responseEntity))) // one action per entity } else { o = Observable.of(action.payload) return o.map((responseEntity) => new EntityActions.LoadSuccess(slice, completeAssign({}, initialEntity, responseEntity))) // one action per entity } } } ); } export function addToRemote$(actions$: Actions, slice: keyof RootState, dataService: DataService, store: Store<RootState>, initialEntity: Entity): Observable<Action> { return actions$ .ofType(typeFor(slice, actions.ADD), typeFor(slice, actions.ADD_OPTIMISTICALLY)) .withLatestFrom(store) .switchMap(([action, state]) => dataService.add(slice, (<any>action).payloadForPost(), state, store) // TODO: find better way .map((responseEntity: Entity) => new EntityActions.AddSuccess(slice, completeAssign({}, initialEntity, responseEntity))) .catch((err) => { console.log(err); return Observable.of(new EntityActions.AddUpdateFail(slice, null)); }) ); } /** * @whatItDoes This function creates a subscription to UPDATE and PATCH actions for a given entity type and calls the dataservice to send the * update to the server * * @param actions$ * @param slice * @param dataService * @param store */ export function updateToRemote$(actions$: Actions<EntityAction<any>>, slice: keyof RootState, dataService: DataService, store: Store<RootState>, initialEntity: Entity): Observable<Action> { return actions$ .ofType(typeFor(slice, actions.UPDATE), typeFor(slice, actions.PATCH)) .withLatestFrom(store) .switchMap(([action, state]) => { let entity = (<EntityAction<any>>action).payload; if (action.type === typeFor(slice, actions.PATCH)) { entity = { ...state[slice].entities[entity.id], ...entity } } return Observable.combineLatest(Observable.of(action), dataService.update(slice, entity, state, store)); }) .map(([action, responseEntity]) => { if (action.verb === actions.UPDATE) { return new EntityActions.UpdateSuccess(slice, completeAssign({}, initialEntity, responseEntity)); } else { return new EntityActions.PatchSuccess(slice, completeAssign({}, initialEntity, responseEntity)); } } ); } export function deleteFromRemote$(actions$: Actions, slice: keyof RootState, dataService: DataService, store: Store<RootState>): Observable<EntityAction<any>> { // TODO: fix this any return actions$ .ofType(typeFor(slice, actions.DELETE)) .withLatestFrom(store) .switchMap(([action, state]) => dataService.remove(slice, (<EntityAction<any>>action).payload, state, store)) .map((responseEntity: Entity) => new EntityActions.DeleteSuccess(slice, responseEntity)) .catch((err) => { console.log(err); return Observable.of(new EntityActions.DeleteFail(slice, err)); }) } /** * @whatItDoes This will fetch a selected entity from the server if it is not in the store. The * response returning will trigger a load action which will trigger another select action. The reducer will get that * and set the entity selectedId * * @param actions$ stream of actions * @param slice the type of entity * @param dataService the service that makes the http request * @param store the ngrx store * @param initialEntity this contains all the default entity properties to be merged with a fetched entity */ export function select$(actions$: Actions, slice: keyof RootState, dataService: DataService, store: Store<RootState>, initialEntity: Entity): Observable<EntityAction<any>> { // TODO: fix this any return actions$ .ofType(typeFor(slice, actions.SELECT)) .withLatestFrom(store) .filter(([action, state]) => { return !state[slice].entities[(<EntityAction<any>>action).payload.id]; }) .switchMap(([action, state]) => { return dataService.getEntity(slice, (<EntityAction<any>>action).payload.id, state, store) .map((responseEntity) => { const payload = completeAssign({}, initialEntity, responseEntity) return new EntityActions.LoadSuccess(slice, payload); }); }); }
the_stack
import React, {ChangeEvent, Component, FormEvent, Fragment} from 'react'; import './App.css'; import {Auth, Hub} from 'aws-amplify'; import {CognitoUser} from '@aws-amplify/auth'; import {Pet} from "../model/pet"; import {User} from "../model/user"; import {APIService} from "../service/APIService"; const numberFormat = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD', minimumFractionDigits: 0, maximumFractionDigits: 0 }); interface AppProps { apiService: APIService } export interface State { authState?: 'signedIn' | 'signedOut' | 'loading'; user?: User; pets?: Pet[]; error?: any; message?: string; selectedPet?: Pet; loading?: boolean; } class App extends Component<AppProps, State> { private apiService: APIService; constructor(props: AppProps) { super(props); this.apiService = props.apiService; this.state = { authState: 'loading', } } async componentDidMount() { console.log("componentDidMount"); Hub.listen('auth', async ({payload: {event, data}}) => { switch (event) { case 'cognitoHostedUI': let user = await this.getUser(); // workaround for FF bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1422334 // eslint-disable-next-line // noinspection SillyAssignmentJS window.location.hash = window.location.hash; this.setState({authState: 'signedIn', user: user}); break; case 'cognitoHostedUI_failure': this.setState({authState: 'signedOut', user: null, error: data}); break; default: break; } }); // if the URL contains ?identity_provider=x, and the user is signed out, we redirect to the IdP on load const urlParams = new URLSearchParams(window.location.search); const idpParamName = 'identity_provider'; const idp = urlParams.get(idpParamName); try { let user = await this.getUser(); // remove identity_provider query param (not needed if signed in successfully) if (idp) { urlParams.delete(idpParamName); const params = urlParams.toString(); window.history.replaceState(null, null, window.location.pathname + (params ? '?' + params : '')); } this.setState({authState: 'signedIn', user: user}); } catch (e) { // user is not authenticated, and we have an IdP in the request if (e === 'not authenticated' && idp) { await Auth.federatedSignIn({customProvider: idp}); } else { console.warn(e); this.setState({authState: 'signedOut', user: null}); } } } private async getUser() { let cognitoUser: CognitoUser = await Auth.currentAuthenticatedUser(); return new User(cognitoUser); } async componentDidUpdate(prevProps: Readonly<any>, prevState: Readonly<State>) { if (prevState.authState !== this.state.authState && this.state.authState === "signedIn") { await this.getAllPets(); } } render() { const {authState, pets, user, error, selectedPet, message, loading}: Readonly<State> = this.state; let username: string; let groups: string[] = []; if(user) { // using first name for display username = user.name || user.email; groups = user.groups; } return ( <Fragment> <nav className="navbar navbar-expand-md navbar-dark bg-dark"> <a className="navbar-brand" href="/">Amazon Cognito + AWS Amplify + React Demo</a> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"/> </button> <div className="collapse navbar-collapse" id="navbarsExampleDefault"> <ul className="navbar-nav mr-auto"> <li className="nav-item active"> <a className="nav-link" href="/">Home <span className="sr-only">(current)</span></a> </li> </ul> {[...groups].map(group => <span className={`badge badge-${group.endsWith("admins") ? "success" : "info"} mr-2`} key={group}>{group}</span>)} <div className="my-2 my-lg-0 navbar-nav"> {authState === 'loading' && (<div>loading...</div>)} {authState === 'signedOut' && <Fragment> <button className="btn btn-primary m-1" onClick={() => Auth.federatedSignIn({customProvider: "IdP"})}>Single Sign On</button> <button className="btn btn-primary m-1" onClick={() => Auth.federatedSignIn()}>Sign In / Sign Up</button> </Fragment> } {authState === 'signedIn' && <div className="nav-item dropdown"> <button className="nav-link dropdown-toggle btn btn-link" data-toggle="dropdown">{username}</button> <div className="dropdown-menu dropdown-menu-right"> <button className="dropdown-item btn btn-warning" onClick={() => this.signOut()}>Sign Out</button> </div> </div> } </div> </div> </nav> <div className="container-fluid"> {error && <div className="alert alert-warning" onClick={() => this.setState({error: null})}>{error.toString()}</div>} {message && <div className="alert alert-info" onClick={() => this.setState({message: null})}>{message.toString()}</div>} {authState === 'signedOut' && <div className="alert alert-info">Please sign in</div>} {authState === 'signedIn' && <div className="container"> {pets && <table className="table"> <thead> <tr> <th>owner</th> <th>type</th> <th>price</th> </tr> </thead> <tbody> {pets.map(pet => <tr id={"row" + pet.id} key={pet.id} onClick={() => this.setState({selectedPet: pet})} className={selectedPet && pet.id === selectedPet.id ? "table-active" : ""} > <td><span className='badge badge-secondary'>{pet.ownerDisplayName}</span></td> <td><strong>{pet.type}</strong></td> <td>{numberFormat.format(pet.price || 0)}</td> </tr>) } </tbody> </table>} {selectedPet && selectedPet.id && <button className="btn btn-danger m-1" onClick={() => this.deletePet()}>Delete</button>} {<button className="btn btn-primary m-1" onClick={() => this.newOnClick()}>Create New</button>} {<button className="btn btn-success m-1" onClick={() => this.getAllPets()}>Reload</button>} {selectedPet && <div className="card"> <div className="card-body"> <form className="form-inline" onSubmit={e => this.savePet(e)}> <input className="form-control" type="hidden" value={selectedPet.id || ""} placeholder="Id" onChange={e => this.handleChange(e, (state, value) => state.selectedPet.id = value)}/> <input className="form-control" type="text" value={selectedPet.type || ""} placeholder="Type" onChange={e => this.handleChange(e, (state, value) => state.selectedPet.type = value)}/> <input className="form-control" type="text" value={selectedPet.price || ""} placeholder="Price" onChange={e => this.handleChange(e, (state, value) => state.selectedPet.price = this.getAsNumber(value))}/> <button type="submit" className="btn btn-success m-1">{selectedPet.id ? "Update" : "Save"}</button> </form> </div> </div>} {loading && <div className="d-flex justify-content-center"> <div className="spinner-border" role="status"> <span className="sr-only">Loading...</span> </div> </div>} </div>} </div> </Fragment> ); } handleChange(event: ChangeEvent<HTMLInputElement>, mapper: (state: State, value: any) => void) { const value = event.target.value; this.setState(state => { mapper(state, value); return state; }); } newOnClick() { // we explicitly set to null, undefined causes react to assume there was no change this.setState({selectedPet: new Pet()}); } async getAllPets() { try { this.setState({loading: true, selectedPet: undefined}); let pets: Pet[] = await this.apiService.getAllPets(); this.setState({pets, loading: false}); } catch (e) { console.log(e); this.setState({error: `Failed to load pets: ${e}`, pets: [], loading: false}); } } async savePet(event: FormEvent<HTMLFormElement>) { event.preventDefault(); const pet = this.state.selectedPet; if (!pet) { this.setState({error: "Pet is needed"}); return; } try { this.setState({loading: true}); await this.apiService.savePet(pet); await this.getAllPets(); } catch (e) { this.setState({error: "Failed to save pet. " + e.message, loading: false}); } } async deletePet() { if (!window.confirm("Are you sure?")) { return; } const pet = this.state.selectedPet; if (!pet) { this.setState({error: "Pet is needed"}); return; } try { this.setState({loading: true}); await this.apiService.deletePet(pet); return this.getAllPets(); } catch (e) { this.setState({error: "Failed to save pet. " + e.message, loading: false}); } } async signOut() { try { this.setState({authState: 'signedOut', pets: null, user: null}); await this.apiService.forceSignOut(); } catch (e) { console.log(e); } } private getAsNumber(value: any): number | undefined { if (value) { try { return parseInt(value) } catch (ignored) { } } return undefined; } } export default App;
the_stack
import directionConverter from '@aesthetic/addon-direction'; import vendorPrefixer from '@aesthetic/addon-vendor'; import { createClientEngine } from '@aesthetic/style'; import { getRenderedStyles, purgeStyles } from '@aesthetic/style/test'; import { ClassName } from '@aesthetic/types'; import { toArray } from '@aesthetic/utils'; import { Aesthetic, AestheticOptions, FeatureSheet, Sheet, SheetRenderResult } from '../src'; import { createTestEngine, darkTheme, getAestheticState, lightTheme, setupAesthetic, teardownAesthetic, } from '../src/test'; function createVariant(type: string[] | string, result: string) { return { types: toArray(type), result }; } function createAesthetic() { const aesthetic = new Aesthetic(); // Dont use test engine since we need to test the DOM aesthetic.configureEngine(createClientEngine()); return aesthetic; } function createComponentSheet(aesthetic: Aesthetic, options?: Partial<AestheticOptions>) { if (options) { aesthetic.configure(options); } return aesthetic.createStyleSheet(() => ({ foo: { display: 'block', }, bar: { color: 'black', '@variants': { 'type:red': { color: 'red', }, // Compounds 'border:thick + size:small': { border: '3px solid blue', }, }, }, baz: { position: 'absolute', }, })); } function createThemeSheet(aesthetic: Aesthetic) { return aesthetic.createThemeSheet(() => ({ '@root': { display: 'block', width: '100%', }, })); } describe('Aesthetic', () => { let aesthetic: Aesthetic; beforeEach(() => { purgeStyles(); aesthetic = createAesthetic(); setupAesthetic(aesthetic); }); afterEach(() => { purgeStyles(); teardownAesthetic(aesthetic); document.documentElement.setAttribute('dir', 'ltr'); }); it('can subscribe and unsubscribe events', () => { const spy = jest.fn(); aesthetic.subscribe('change:theme', spy); expect(getAestheticState(aesthetic).listeners.get('change:theme')?.has(spy)).toBe(true); aesthetic.unsubscribe('change:theme', spy); expect(getAestheticState(aesthetic).listeners.get('change:theme')?.has(spy)).toBe(false); }); it('can subscribe and unsubscribe events using the return value', () => { const spy = jest.fn(); const unsub = aesthetic.subscribe('change:theme', spy); expect(getAestheticState(aesthetic).listeners.get('change:theme')?.has(spy)).toBe(true); unsub(); expect(getAestheticState(aesthetic).listeners.get('change:theme')?.has(spy)).toBe(false); }); describe('changeDirection()', () => { beforeEach(() => { // @ts-expect-error Allow access aesthetic.activeDirection = undefined; }); it('sets active direction', () => { expect(getAestheticState(aesthetic).activeDirection).toBeUndefined(); aesthetic.changeDirection('rtl'); expect(getAestheticState(aesthetic).activeDirection).toBe('rtl'); }); it('sets direction on engine', () => { expect(aesthetic.getEngine().direction).toBe('ltr'); aesthetic.changeDirection('rtl'); expect(aesthetic.getEngine().direction).toBe('rtl'); }); it('doesnt run if changing to same name', () => { const spy = jest.fn(); aesthetic.subscribe('change:direction', spy); aesthetic.changeDirection('rtl'); aesthetic.changeDirection('rtl'); expect(spy).toHaveBeenCalledTimes(1); }); it('sets document attribute', () => { document.documentElement.dir = 'ltr'; expect(document.documentElement.dir).toBe('ltr'); aesthetic.changeDirection('rtl'); expect(document.documentElement.dir).toBe('rtl'); }); it('emits `change:direction` event', () => { const spy = jest.fn(); aesthetic.subscribe('change:direction', spy); aesthetic.changeDirection('rtl'); expect(spy).toHaveBeenCalledWith('rtl'); }); it('doesnt emit `change:direction` event if `propagate` is false', () => { const spy = jest.fn(); aesthetic.subscribe('change:direction', spy); aesthetic.changeDirection('rtl', false); expect(spy).not.toHaveBeenCalled(); }); }); describe('changeTheme()', () => { it('sets active theme', () => { expect(getAestheticState(aesthetic).activeTheme).toBeUndefined(); aesthetic.changeTheme('night'); expect(getAestheticState(aesthetic).activeTheme).toBe('night'); }); it('doesnt run if changing to same name', () => { const spy = jest.spyOn(aesthetic, 'renderThemeSheet'); aesthetic.changeTheme('night'); aesthetic.changeTheme('night'); expect(spy).toHaveBeenCalledTimes(1); spy.mockRestore(); }); it('applies root css variables if `rootVariables` is true', () => { const spy = jest.spyOn(aesthetic.getEngine(), 'setRootVariables'); // @ts-expect-error Allow access aesthetic.options.rootVariables = true; aesthetic.changeTheme('night'); expect(spy).toHaveBeenCalledWith(darkTheme.toVariables()); spy.mockRestore(); }); it('doesnt apply root css variables if `rootVariables` is false', () => { const spy = jest.spyOn(aesthetic.getEngine(), 'setRootVariables'); aesthetic.changeTheme('night'); expect(spy).not.toHaveBeenCalled(); spy.mockRestore(); }); it('renders theme sheet and sets body class name', () => { aesthetic.registerTheme('night', darkTheme, createThemeSheet(aesthetic)); aesthetic.changeTheme('night'); expect(document.body.className).toBe('c1qxhd3i cemumis'); }); it('emits `change:theme` event', () => { const spy = jest.fn(); aesthetic.subscribe('change:theme', spy); aesthetic.changeTheme('night'); expect(spy).toHaveBeenCalledWith('night', ['c1qxhd3i']); }); it('doesnt emit `change:theme` event if `propagate` is false', () => { const spy = jest.fn(); aesthetic.subscribe('change:theme', spy); aesthetic.changeTheme('night', false); expect(spy).not.toHaveBeenCalled(); }); }); describe('configure()', () => { it('sets options', () => { expect(getAestheticState(aesthetic).options).toEqual({}); aesthetic.configure({ defaultUnit: 'em', directionConverter, vendorPrefixer, }); expect(getAestheticState(aesthetic).options).toEqual({ defaultUnit: 'em', directionConverter, vendorPrefixer, }); }); it('can customize through constructor', () => { aesthetic = new Aesthetic({ defaultUnit: 'em', directionConverter, vendorPrefixer, }); expect(getAestheticState(aesthetic).options).toEqual({ defaultUnit: 'em', directionConverter, vendorPrefixer, }); }); }); describe('createStyleSheet()', () => { it('returns a `FeatureSheet` instance', () => { expect(aesthetic.createStyleSheet(() => ({}))).toBeInstanceOf(FeatureSheet); }); it('can utilize mixins', () => { const sheet = aesthetic.createStyleSheet((css) => ({ element: css.mixin('reset-typography', { display: 'flex', color: css.var('palette-brand-text'), }), })); aesthetic.renderStyleSheet(sheet); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); describe('createScopedStyleSheet()', () => { it('returns a `FeatureSheet` instance using an object', () => { const sheet = aesthetic.createScopedStyleSheet({ display: 'block', color: 'red', ':hover': { color: 'darkred', }, }); expect(sheet).toBeInstanceOf(FeatureSheet); expect(aesthetic.renderStyleSheet(sheet)).toEqual({ element: { result: 'a b c' } }); }); it('returns a `FeatureSheet` instance using a function', () => { const sheet = aesthetic.createScopedStyleSheet((css) => ({ display: 'block', color: css.var('palette-brand-fg-base'), ':hover': { color: css.var('palette-brand-fg-hovered'), }, })); expect(sheet).toBeInstanceOf(FeatureSheet); expect(aesthetic.renderStyleSheet(sheet)).toEqual({ element: { result: 'a b c' } }); }); it('can customize the selector', () => { const sheet = aesthetic.createScopedStyleSheet( { display: 'block', color: 'red', ':hover': { color: 'darkred', }, }, 'test', ); expect(sheet).toBeInstanceOf(FeatureSheet); expect(aesthetic.renderStyleSheet(sheet)).toEqual({ test: { result: 'a b c' } }); }); }); describe('createThemeSheet()', () => { it('returns a `Sheet` instance', () => { expect(aesthetic.createThemeSheet(() => ({}))).toBeInstanceOf(Sheet); }); it('can utilize mixins', () => { const sheet = aesthetic.createThemeSheet((css) => ({ '@root': css.mixin('root', { backgroundColor: css.var('palette-neutral-bg-base'), }), })); sheet.render(aesthetic.getEngine(), lightTheme, {}); expect(getRenderedStyles('global')).toMatchSnapshot(); }); }); describe('generateResults()', () => { const classes: SheetRenderResult<ClassName> = { a: { result: 'a', variants: [createVariant('size:df', 'a_size_df')] }, b: { result: 'b' }, c: { result: 'c', variants: [createVariant('size:md', 'c_size_md'), createVariant('type:red', 'c_type_red')], }, d: { variants: [createVariant('size:df', 'd_size_df')] }, e: { result: 'e' }, f: { result: 'f', variants: [createVariant('size:df', 'f_size_df'), createVariant('size:md', 'f_size_md')], }, g: { result: 'g', variants: [createVariant('type:red', 'g_type_red')] }, h: { result: 'h', variants: [createVariant(['type:red', 'size:df'], 'h_type_red__size_df')] }, }; it('returns class names', () => { expect(aesthetic.generateResults(['a', 'e'], new Set(), classes)).toEqual(['a', 'e']); }); it('returns nothing for an invalid selector', () => { expect(aesthetic.generateResults(['z'], new Set(), classes)).toEqual([]); }); it('returns nothing for a valid selector but no class name', () => { expect(aesthetic.generateResults(['d'], new Set(), classes)).toEqual([]); }); it('can append custom class names using an array', () => { expect( aesthetic.generateResults( ['a', ['qux'], 'e', ['foo', false && 'bar', true && 'baz']], new Set(), classes, ), ).toEqual(['a', 'qux', 'e', 'foo', 'baz']); }); describe('variants', () => { it('returns class names and matching variants', () => { expect(aesthetic.generateResults(['a'], new Set(['size:df']), classes)).toEqual([ 'a', 'a_size_df', ]); expect(aesthetic.generateResults(['a', 'f'], new Set(['size:df']), classes)).toEqual([ 'a', 'a_size_df', 'f', 'f_size_df', ]); }); it('returns variants even if theres no base class name', () => { expect(aesthetic.generateResults(['d'], new Set(['size:df']), classes)).toEqual([ 'd_size_df', ]); }); it('only returns compound variant result if all names match', () => { expect(aesthetic.generateResults(['h'], new Set(), classes)).toEqual(['h']); expect(aesthetic.generateResults(['h'], new Set(['type:red']), classes)).toEqual(['h']); expect(aesthetic.generateResults(['h'], new Set(['size:df']), classes)).toEqual(['h']); expect(aesthetic.generateResults(['h'], new Set(['type:red', 'size:df']), classes)).toEqual( ['h', 'h_type_red__size_df'], ); // Different enums expect(aesthetic.generateResults(['h'], new Set(['type:red', 'size:md']), classes)).toEqual( ['h'], ); expect( aesthetic.generateResults(['h'], new Set(['type:blue', 'size:md']), classes), ).toEqual(['h']); }); it('can append custom class names', () => { expect( aesthetic.generateResults(['a', ['foo', false && 'bar']], new Set(['size:df']), classes), ).toEqual(['a', 'a_size_df', 'foo']); }); }); }); describe('getActiveDirection()', () => { beforeEach(() => { // @ts-expect-error Allow access aesthetic.activeDirection = undefined; }); it('returns the direction defined on the html `dir` attribute', () => { const changeSpy = jest.fn(); document.documentElement.setAttribute('dir', 'rtl'); document.body.removeAttribute('dir'); // Reset to detect attribute aesthetic = createAesthetic(); aesthetic.subscribe('change:direction', changeSpy); expect(aesthetic.getActiveDirection()).toBe('rtl'); expect(changeSpy).toHaveBeenCalledWith('rtl'); }); it('returns the direction defined on the body `dir` attribute', () => { document.documentElement.removeAttribute('dir'); document.body.setAttribute('dir', 'rtl'); // Reset to detect attribute aesthetic = createAesthetic(); expect(aesthetic.getActiveDirection()).toBe('rtl'); }); it('returns ltr if no dir found', () => { document.documentElement.removeAttribute('dir'); document.body.removeAttribute('dir'); // Reset to detect attribute aesthetic = createAesthetic(); expect(aesthetic.getActiveDirection()).toBe('ltr'); }); it('caches result for subsequent lookups', () => { expect(aesthetic.getActiveDirection()).toBe('ltr'); document.documentElement.setAttribute('dir', 'rtl'); expect(aesthetic.getActiveDirection()).toBe('ltr'); }); }); describe('getActiveTheme()', () => { it('errors if no themes registered', () => { aesthetic = createAesthetic(); expect(() => { aesthetic.getActiveTheme(); }).toThrow('No themes have been registered.'); }); it('returns the active theme defined by property', () => { const changeSpy = jest.fn(); aesthetic.subscribe('change:theme', changeSpy); setupAesthetic(aesthetic); aesthetic.changeTheme('night'); expect(aesthetic.getActiveTheme()).toBe(darkTheme); expect(changeSpy).toHaveBeenCalledWith('night', ['c1qxhd3i']); }); it('returns the preferred theme if no active defined', () => { const getSpy = jest.spyOn(getAestheticState(aesthetic).themeRegistry, 'getPreferredTheme'); const changeSpy = jest.fn(); aesthetic.subscribe('change:theme', changeSpy); setupAesthetic(aesthetic); expect(aesthetic.getActiveTheme()).toBe(lightTheme); expect(getSpy).toHaveBeenCalled(); expect(changeSpy).toHaveBeenCalledWith('day', ['cslosem']); }); }); describe('getTheme()', () => { it('errors if not registered', () => { expect(() => { aesthetic.getTheme('unknown'); }).toThrow('Theme "unknown" does not exist. Has it been registered?'); }); it('returns the theme defined by name', () => { aesthetic.registerTheme('day', lightTheme); expect(aesthetic.getTheme('day')).toBe(lightTheme); }); }); describe('mergeStyleSheets()', () => { function createTestMergeSheets() { const a = aesthetic.createStyleSheet(() => ({ foo: { color: 'red', }, })); const b = aesthetic .createStyleSheet(() => ({ bar: { backgroundColor: 'green', }, })) .addThemeOverride('night', () => ({ bar: { backgroundColor: 'lightgreen', }, })); const c = aesthetic .createStyleSheet(() => ({ foo: { display: 'block', }, baz: { borderColor: 'yellow', }, })) .addContrastOverride('low', () => ({ baz: { borderColor: 'orange', }, })); const d = aesthetic .createStyleSheet(() => ({ foo: { color: 'pink', }, })) .addOverride(() => ({ foo: { color: 'pinkred', }, })); const e = aesthetic .createScopedStyleSheet({}, 'qux') .addColorSchemeOverride('dark', () => ({ qux: { padding: 0, }, })) .addThemeOverride('night', () => ({ qux: { padding: 10, }, })); return { a, b, c, d, e }; } it('merges all style sheets into a single sheet and inherits overrides', () => { const { a, b, c, d, e } = createTestMergeSheets(); const sheet = aesthetic.mergeStyleSheets(a, b, c, d, e); // @ts-expect-error Allow access expect(sheet.overrides).toHaveLength(5); // 6 with base factory // @ts-expect-error Allow access const { low, normal, high } = sheet.contrastOverrides; expect(low).toHaveLength(1); expect(normal).toBeUndefined(); expect(high).toBeUndefined(); // @ts-expect-error Allow access const { light, dark } = sheet.schemeOverrides; expect(light).toBeUndefined(); expect(dark).toHaveLength(1); // @ts-expect-error Allow access expect(sheet.themeOverrides.night).toHaveLength(2); }); it('merges default objects', () => { const { a, b, c, d, e } = createTestMergeSheets(); const sheet = aesthetic.mergeStyleSheets(a, b, c, d, e); expect(sheet.compose({})(aesthetic.getActiveTheme())).toEqual({ foo: { color: 'pinkred', display: 'block' }, bar: { backgroundColor: 'green' }, baz: { borderColor: 'yellow' }, qux: {}, }); }); it('merges for contrast', () => { const { a, b, c, d, e } = createTestMergeSheets(); const sheet = aesthetic.mergeStyleSheets(a, b, c, d, e); expect(sheet.compose({ contrast: 'high' })(aesthetic.getActiveTheme())).toEqual({ foo: { color: 'pinkred', display: 'block' }, bar: { backgroundColor: 'green' }, baz: { borderColor: 'yellow' }, qux: {}, }); expect(sheet.compose({ contrast: 'low' })(aesthetic.getActiveTheme())).toEqual({ foo: { color: 'pinkred', display: 'block' }, bar: { backgroundColor: 'green' }, baz: { borderColor: 'orange' }, qux: {}, }); }); it('merges for color scheme', () => { const { a, b, c, d, e } = createTestMergeSheets(); const sheet = aesthetic.mergeStyleSheets(a, b, c, d, e); expect(sheet.compose({ scheme: 'light' })(aesthetic.getActiveTheme())).toEqual({ foo: { color: 'pinkred', display: 'block' }, bar: { backgroundColor: 'green' }, baz: { borderColor: 'yellow' }, qux: {}, }); expect(sheet.compose({ scheme: 'dark' })(aesthetic.getActiveTheme())).toEqual({ foo: { color: 'pinkred', display: 'block' }, bar: { backgroundColor: 'green' }, baz: { borderColor: 'yellow' }, qux: { padding: 0 }, }); }); it('merges for theme', () => { const { a, b, c, d, e } = createTestMergeSheets(); const sheet = aesthetic.mergeStyleSheets(a, b, c, d, e); expect(sheet.compose({ theme: 'unknown' })(aesthetic.getActiveTheme())).toEqual({ foo: { color: 'pinkred', display: 'block' }, bar: { backgroundColor: 'green' }, baz: { borderColor: 'yellow' }, qux: {}, }); expect(sheet.compose({ theme: 'night' })(aesthetic.getActiveTheme())).toEqual({ foo: { color: 'pinkred', display: 'block' }, bar: { backgroundColor: 'lightgreen' }, baz: { borderColor: 'yellow' }, qux: { padding: 10 }, }); }); it('returns same sheet if only 1', () => { const { a } = createTestMergeSheets(); const sheet = aesthetic.mergeStyleSheets(a); expect(a).toBe(sheet); }); }); describe('registerDefaultTheme()', () => { it('registers a default theme', () => { const spy = jest.spyOn(getAestheticState(aesthetic).themeRegistry, 'register'); aesthetic.registerDefaultTheme('day', lightTheme); expect(spy).toHaveBeenCalledWith('day', lightTheme, true); }); }); describe('registerTheme()', () => { it('registers a theme', () => { const spy = jest.spyOn(getAestheticState(aesthetic).themeRegistry, 'register'); aesthetic.registerTheme('day', lightTheme); expect(spy).toHaveBeenCalledWith('day', lightTheme, false); }); it('registers an optional sheet', () => { const sheet = aesthetic.createThemeSheet(() => ({})); aesthetic.registerTheme('day', lightTheme, sheet); expect(getAestheticState(aesthetic).globalSheetRegistry.get('day')).toBe(sheet); }); it('errors if sheet is not a `Sheet` instance', () => { expect(() => { aesthetic.registerTheme( 'day', lightTheme, // @ts-expect-error Invalid type 123, ); }).toThrow('Rendering theme styles require a `Sheet` instance.'); }); }); describe('getEngine()', () => { it('errors if not defined', () => { expect(() => { // @ts-expect-error Allow access aesthetic.styleEngine = undefined; aesthetic.getEngine(); }).toThrow('No style engine defined. Have you configured one with `configureEngine()`?'); }); it('returns a client engine by default', () => { expect(aesthetic.getEngine()).toBeDefined(); }); it('can define a custom engine by using a global variable', () => { const customEngine = createClientEngine(); global.AESTHETIC_CUSTOM_ENGINE = customEngine; expect(aesthetic.getEngine()).toBe(customEngine); // @ts-expect-error Allow delete delete global.AESTHETIC_CUSTOM_ENGINE; }); }); describe('renderStyles()', () => { it('renders the styles and returns an output result', () => { const result = aesthetic.renderStyles({ color: 'black', '@variants': { 'type:red': { color: 'red', }, // Compounds 'border:thick + size:small': { border: '3px solid blue', }, }, }); expect(result).toEqual({ result: 'a', variants: [ createVariant('type:red', 'b'), createVariant(['border:thick', 'size:small'], 'c'), ], }); }); }); describe('renderStyleSheet()', () => { it('errors if sheet is not a `Sheet` instance', () => { expect(() => { aesthetic.renderStyleSheet( // @ts-expect-error Invalid type 123, ); }).toThrow('Rendering component styles require a `Sheet` instance.'); }); it('returns an empty object if no sheet selectors', () => { expect(aesthetic.renderStyleSheet(aesthetic.createStyleSheet(() => ({})))).toEqual({}); }); it('renders a sheet and returns an object class name', () => { const sheet = createComponentSheet(aesthetic); const spy = jest.spyOn(sheet, 'render'); expect(aesthetic.renderStyleSheet(sheet)).toEqual({ foo: { result: 'a' }, bar: { result: 'b', variants: [ createVariant('type:red', 'c'), createVariant(['border:thick', 'size:small'], 'd'), ], variantTypes: new Set(['border', 'type', 'size']), }, baz: { result: 'e' }, }); expect(spy).toHaveBeenCalledWith(aesthetic.getEngine(), lightTheme, { deterministic: false, direction: expect.any(String), vendor: false, }); }); it('renders with deterministic classes', () => { const sheet = createComponentSheet(aesthetic, { deterministicClasses: true, }); const spy = jest.spyOn(sheet, 'render'); expect(aesthetic.renderStyleSheet(sheet)).toEqual({ foo: { result: 'c1s7hmty' }, bar: { result: 'cddrzz3', variants: [ createVariant('type:red', 'csjf8sr'), createVariant(['border:thick', 'size:small'], 'c1bdyxox'), ], variantTypes: new Set(['border', 'type', 'size']), }, baz: { result: 'chj83d7' }, }); expect(spy).toHaveBeenCalledWith(aesthetic.getEngine(), lightTheme, { deterministic: true, direction: expect.any(String), vendor: false, }); }); it('renders with a test engine and fixed classes', () => { aesthetic.configureEngine(createTestEngine()); const sheet = createComponentSheet(aesthetic); expect(aesthetic.renderStyleSheet(sheet)).toEqual({ foo: { result: 'foo' }, bar: { result: 'bar', variants: [ createVariant('type:red', 'variant:type:red'), createVariant( ['border:thick', 'size:small'], 'variant:border:thick variant:size:small', ), ], variantTypes: new Set(['border', 'type', 'size']), }, baz: { result: 'baz' }, }); }); it('can customize params with options', () => { const sheet = createComponentSheet(aesthetic, { defaultUnit: 'em', vendorPrefixer, }); const spy = jest.spyOn(sheet, 'render'); aesthetic.renderStyleSheet(sheet, { direction: 'rtl' }); expect(spy).toHaveBeenCalledWith(aesthetic.getEngine(), lightTheme, { deterministic: false, direction: 'rtl', vendor: true, }); }); it('can customize theme with options', () => { const sheet = createComponentSheet(aesthetic); const spy = jest.spyOn(sheet, 'render'); aesthetic.renderStyleSheet(sheet, { theme: 'night' }); expect(spy).toHaveBeenCalledWith(aesthetic.getEngine(), darkTheme, { deterministic: false, direction: expect.any(String), theme: 'night', vendor: false, }); }); }); describe('renderFontFace()', () => { it('passes to engine', () => { const spy = jest.spyOn(aesthetic.getEngine(), 'renderFontFace'); const fontFace = { fontFamily: 'Roboto', src: "url('fonts/Roboto.woff2') format('woff2')", }; aesthetic.renderFontFace(fontFace); expect(spy).toHaveBeenCalledWith(fontFace, undefined); spy.mockRestore(); }); it('supports source paths', () => { const spy = jest.spyOn(aesthetic.getEngine(), 'renderFontFace'); aesthetic.renderFontFace( { srcPaths: ['fonts/Roboto.woff2'], }, 'Roboto', ); expect(spy).toHaveBeenCalledWith( { fontFamily: 'Roboto', srcPaths: ['fonts/Roboto.woff2'], }, undefined, ); spy.mockRestore(); }); }); describe('renderImport()', () => { it('passes to engine', () => { const spy = jest.spyOn(aesthetic.getEngine(), 'renderImport'); const path = 'test.css'; aesthetic.renderImport(path); expect(spy).toHaveBeenCalledWith(path, undefined); spy.mockRestore(); }); }); describe('renderKeyframes()', () => { it('passes to engine', () => { const spy = jest.spyOn(aesthetic.getEngine(), 'renderKeyframes'); const keyframes = { from: { opacity: 0 }, to: { opacity: 1 }, }; aesthetic.renderKeyframes(keyframes); expect(spy).toHaveBeenCalledWith(keyframes, undefined, undefined); spy.mockRestore(); }); it('can pass a name and params', () => { const spy = jest.spyOn(aesthetic.getEngine(), 'renderKeyframes'); const keyframes = { from: { opacity: 0 }, to: { opacity: 1 }, }; aesthetic.renderKeyframes(keyframes, 'fade', { direction: 'rtl' }); expect(spy).toHaveBeenCalledWith(keyframes, 'fade', { direction: 'rtl' }); spy.mockRestore(); }); }); describe('renderThemeSheet()', () => { it('renders a sheet and returns class names', () => { const sheet = createThemeSheet(aesthetic); const spy = jest.spyOn(sheet, 'render'); aesthetic.registerDefaultTheme('day', lightTheme, sheet); expect(aesthetic.renderThemeSheet(lightTheme)).toEqual(['cslosem', 'cemumis']); expect(spy).toHaveBeenCalledWith(aesthetic.getEngine(), lightTheme, { deterministic: false, direction: expect.any(String), vendor: false, }); }); it('renders with deterministic classes even if disabled', () => { const sheet = createThemeSheet(aesthetic); const spy = jest.spyOn(sheet, 'render'); aesthetic.configure({ deterministicClasses: false, }); aesthetic.registerDefaultTheme('day', lightTheme, sheet); expect(aesthetic.renderThemeSheet(lightTheme)).toEqual(['cslosem', 'cemumis']); expect(spy).toHaveBeenCalledWith(aesthetic.getEngine(), lightTheme, { deterministic: false, direction: expect.any(String), vendor: false, }); }); it('renders theme CSS variables as a rule group', () => { const sheet = createThemeSheet(aesthetic); const spy = jest.spyOn(aesthetic.getEngine(), 'renderRuleGrouped'); aesthetic.registerDefaultTheme('day', lightTheme, sheet); aesthetic.renderThemeSheet(lightTheme); expect(spy).toHaveBeenCalledWith( { '@variables': lightTheme.toVariables(), }, expect.objectContaining({ type: 'global' }), ); }); it('can customize params with options', () => { const sheet = createThemeSheet(aesthetic); const spy = jest.spyOn(sheet, 'render'); aesthetic.configure({ defaultUnit: 'em', vendorPrefixer, }); aesthetic.registerDefaultTheme('day', lightTheme, sheet); aesthetic.renderThemeSheet(lightTheme, { direction: 'rtl' }); expect(spy).toHaveBeenCalledWith(aesthetic.getEngine(), lightTheme, { deterministic: false, direction: 'rtl', vendor: true, }); }); }); });
the_stack
module TDev.IntelliTrain { // compute the top-level goal properties can be null, or a string. // Used only during training on Json ASTs. // Note: during prediction use in the calculator, there's a different GoalState defined in calculator.ts export class GoalState extends AST.Json.NodeVisitor { // used during compute public localTypes = {}; public resolver: AST.Json.ScriptResolver; public globalOnly: boolean; public goalWindow: string[] = []; public windowSize = 3; public pushGoal(goal: string) { if (this.goalWindow.length >= this.windowSize) { this.goalWindow.shift(); } this.goalWindow.push(goal); } /// dispatcher for goal computation public compute(expr: AST.Json.JExprStmt): string { var goal = this.dispatch(expr.expr.tree); if (goal) { // if it is a property with non-Nothing return type, use the type. var s = goal.split(":", 3); if (s[0] == "prop") { var prop = this.resolver.resolveProp(s[1], s[2]); if (prop && prop.result && <any>prop.result.type != "Nothing") { return "a:" + this.resolver.normalizeType(<any>prop.result.type); } } } return goal; } public visit_stringLiteral(lit: AST.Json.JStringLiteral): any { return "a:String"; } public visit_numberLiteral(lit: AST.Json.JNumberLiteral): any { return "a:Number"; } public visit_booleanLiteral(lit: AST.Json.JBooleanLiteral): any { return "a:Boolean"; } public visit_localRef(local: AST.Json.JLocalRef): any { var type = this.localTypes[<any>local.localId]; if (type) { return "a:" + this.resolver.normalizeType(type); } else { throw new Error("local type not found"); } } public visit_singletonRef(singleton: AST.Json.JSingletonRef): any { // shouldn't be top level return this.resolver.normalizeType(<any>singleton.type); } public visit_call(call: AST.Json.JCall): any { if (call.name == ":=") { return this.dispatch(call.args[1]); } if (<any>call.parent == "data") { var type = this.resolver.dataType(call.declId); return "a:" + this.resolver.normalizeType(type); } if (call.declId) { var action = this.resolver.action(call.declId); var resultType; var tokenContext; if (action && action.outParameters && action.outParameters.length > 0) { return "a:" + this.resolver.normalizeType(<any>action.outParameters[0].type); } else { return "a:Nothing"; } } // top-level property must be the goal. return "prop:" + this.resolver.normalizeType(<any>call.parent) + ":" + call.name; } } export class CorrelationCount implements ICorrelation { public histoA = new TokenCount(); public histoB = new TokenCount(); public correlations: { [a: string]: TokenCount } = {}; public total = 0; private getCount(a: string) { var result = this.correlations[a]; if (!result) { result = new TokenCount(); this.correlations[a] = result; } return result; } public countPair(g1: string, g2: string, toAdd = 1) { var count = this.getCount(g1); count.count(g2, toAdd); this.total++; this.histoA.count(g1, toAdd); this.histoB.count(g2, toAdd); } public probability(g1: string, g2: string) { var count = this.getCount(g1); var freq = count[g2]; if (freq >= 0) { return freq / this.total; } return 0; } public sortedPrecision(): { aLabel: string; bLabel: string; freq: number; aCount: number; bCount: number }[] { var elems: { aLabel: string; bLabel: string; freq: number; aCount: number; bCount: number }[] = []; Object.keys(this.correlations).forEach(g1 => { var c = this.correlations[g1]; Object.keys(c.counts).forEach(g2 => { var c1 = this.histoA.counts[g1]; var c2 = this.histoB.counts[g2]; var cc = c.counts[g2]; elems.push({ aLabel: g1, bLabel: g2, freq: cc, aCount: c1, bCount: c2 }); }); }); elems.sort((a, b) => b.freq / b.aCount - a.freq / a.aCount); return elems; } } export class GoalCounter { public windowCorrelation: CorrelationCount = new CorrelationCount(); public nestedCorrelation: CorrelationCount = new CorrelationCount(); public countPair(g1: string, g2: string) { this.windowCorrelation.countPair(g1, g2); } public countNested(g1: string, g2: string, count = 1) { this.nestedCorrelation.countPair(g1, g2, count); } public display(out: Util.IOutput) { out.show("Window Correlations"); out.show("==================="); this.windowCorrelation.sortedPrecision().forEach(elem => out.show(elem.aLabel + " ==> " + elem.bLabel + " -- precision: " + PredictionEvaluator.percentage(elem.freq, elem.aCount) + " recall: " + PredictionEvaluator.percentage(elem.freq, elem.bCount))); out.show("Nested Correlations"); out.show("==================="); this.nestedCorrelation.sortedPrecision().forEach(elem => out.show(elem.aLabel + " ==> " + elem.bLabel + " -- precision: " + PredictionEvaluator.percentage(elem.freq, elem.aCount) + " recall: " + PredictionEvaluator.percentage(elem.freq, elem.bCount))); } } export class IntelliTracer extends AST.Json.NodeVisitor { private localTypes; public state: AstState; constructor(public observer: ITokenObserver, public apiresolver: AST.Json.IResolver, private globalOnly = true) { super(); this.localTypes = {}; this.state = new AstState(this.apiresolver, globalOnly); this.state.goalState.localTypes = this.localTypes; } public observe(s: string) { // do not observe these switch (s) { case 'op:(': case 'op:)': case 'op:,': return; } } private visit_block(context: Cat, b: AST.Json.JStmt[]) { //this.state.features.push(Cat.stmt_context, context); b.forEach(s => { this.dispatch(s) }); //this.state.features.pop(Cat.stmt_context); } public visit_expression(goalType: string, e: AST.Json.JExprHolder) { this.analyzeExprHolder(goalType, e); } public visit_for(n: AST.Json.JFor) { this.visit_localDef(n.index); this.visit_expression("a:Boolean", n.bound); //this.state.forStack.push(n.index); this.visit_block(Cat.for_body, n.body); //this.state.forStack.pop(); } public visit_foreach(n: AST.Json.JForeach) { this.visit_localDef(n.iterator); this.visit_expression("a:Enumerator", n.collection); n.conditions.forEach(v => this.dispatch(v)); //this.state.foreachStack.push(n.iterator); this.visit_block(Cat.foreach_body, n.body); //this.state.foreachStack.pop(); } public visit_token(tok: AST.Json.JToken) { throw "missing token specialization"; } private lastHandlerProp: string[] = []; public visit_localDef(local: AST.Json.JLocalDef): any { this.localTypes[local.id] = local.type; } public analyzeExprHolder(goal: string, holder: AST.Json.JExprHolder): any { holder.locals.forEach(v => this.visit_localDef(v)); var tokenState = new TokenState(goal, holder.tokens, this.state.resolver, (id) => this.localTypes[id], this.observer); var dist:IFrequencies = {}; dist[goal] = 1; tokenState.analyze(dist); } public visit_exprStmt(node: AST.Json.JExprStmt): any { if (node.expr.tokens.length <= 0) return; var goal = this.state.goalState.compute(node); if (goal) { this.observer.observeGoal(this.state, goal); this.state.goalState.pushGoal(goal); } else { // no goal is possible for side-effecting methods. We don't record the method names. // for library methods we maybe should do it. goal = "a:Nothing"; } this.visit_expression(goal, node.expr); } public visit_inlineAction(action: AST.Json.JInlineAction): any { action.inParameters.forEach(p => this.visit_localDef(p)); action.outParameters.forEach(p => this.visit_localDef(p)); var lastHandlerProp = this.lastHandlerProp.peek(); var savedWindow = this.state.goalState.goalWindow; if (lastHandlerProp) { this.state.goalState.goalWindow = ["start:" + lastHandlerProp]; } this.visit_block(Cat.handler_body, action.body); if (lastHandlerProp) { this.state.goalState.goalWindow = savedWindow; } } public visit_inlineActions(actions: AST.Json.JInlineActions): any { this.visit_exprStmt(actions); var thisGoal = this.state.goalState.compute(actions); this.lastHandlerProp.push(thisGoal); actions.actions.forEach(a => this.dispatch(a)); this.lastHandlerProp.pop(); } public visit_boxed(boxed: AST.Json.JBoxed): any { this.visit_block(Cat.boxed_body, boxed.body); } public visit_if(node: AST.Json.JIf): any { this.visit_expression("a:Boolean", node.condition); this.visit_block(Cat.then_body, node.thenBody); if (node.elseBody) { this.visit_block(Cat.else_body, node.elseBody); } } public visit_action(action: AST.Json.JAction): any { action.inParameters.forEach(i => this.visit_localDef(i)); action.outParameters.forEach(i => this.visit_localDef(i)); this.lastHandlerProp.push(null); var name = action.name; if (name != "main") { name = "action"; } this.state.goalState.goalWindow = ["start:" + name]; this.visit_block(Cat.top, action.body); this.lastHandlerProp.pop(); } public visit_comment(comment: AST.Json.JComment): any { return; } public visit_while(stmt: AST.Json.JWhile): any { this.visit_expression("a:Boolean", stmt.condition); this.visit_block(Cat.while_body, stmt.body); } public visit_where(clause: AST.Json.JWhere): any { this.visit_expression("a:Boolean", clause.condition); } public visit_typeRef(type: AST.Json.JTypeRef): any { } public visit_page(p: AST.Json.JPage): any { p.inParameters.forEach(i => this.visit_localDef(i)); p.outParameters.forEach(i => this.visit_localDef(i)); this.state.goalState.goalWindow = ["start:pageinit"]; this.visit_block(Cat.top, p.initBody); this.state.goalState.goalWindow = ["start:pagebody"]; this.visit_block(Cat.top, p.displayBody); } public visit_event(e: AST.Json.JEvent): any { e.inParameters.forEach(i => this.visit_localDef(i)); e.outParameters.forEach(i => this.visit_localDef(i)); this.state.goalState.goalWindow = ["start:" + e.eventName]; this.visit_block(Cat.top, e.body); } public visit_libAction(la: AST.Json.JLibAction): any { } public visit_art(art: AST.Json.JArt): any { } public visit_data(data: AST.Json.JData): any { } public visit_library(lib: AST.Json.JLibrary): any { } public visit_typeBinding(type: AST.Json.JTypeBinding): any { } public visit_actionBinding(action: AST.Json.JActionBinding): any { } public visit_resolveClause(r: AST.Json.JResolveClause): any { } public visit_record(r: AST.Json.JRecord): any { } public visit_recordField(rf: AST.Json.JRecordField): any { } public visit_recordKey(rk: AST.Json.JRecordKey): any { } public visit_app(app: AST.Json.JApp): any { this.state.resolver.setCurrentScript(app); app.decls.forEach(d => this.dispatch(d)); } public visit_propertyParameter(p: AST.Json.JPropertyParameter): any { } public visit_property(p: AST.Json.JProperty): any { } public visit_typeDef(td: AST.Json.JTypeDef): any { } public visit_apis(apis: AST.Json.JApis): any { } private script: AST.Json.JApp; public visitScript(id: string, finished: () => void) { var script = TDev.Util.httpRequestAsync("http://www.touchdevelop.com/api/" + id + "/webast"); script.done((v) => { var rval = JSON.parse(v); if (rval) { this.script = rval; this.dispatch(rval); } finished(); }, (e) => { throw e; }); } } export class TokenCount implements IHistogram { public total = 0; // maps tokens to counts based on context public counts: IFrequencies = {}; public count(token: string, toAdd = 1) { this.total++; if (this.counts[token]) { this.counts[token] = toAdd + this.counts[token]; } else { this.counts[token] = toAdd; } } public display(out: Util.IOutput) { var elems = []; Object.keys(this.counts).forEach((label) => { elems.push({ key: label, value: this.counts[label] }); }); elems.sort((a, b) => b.value - a.value); out.vertical(() => { var i = 0; out.show("Total counts: " + this.total); while (i < 50 && i < elems.length) { var elem = elems[i++]; out.horizontal(() => { out.show(elem.key); out.show(" : "); out.show(elem.value); }) } }); } public sortedValues(): IKeyValue[] { return this.sorted((a, b) => b.value - a.value); } public sortedKeys(): IKeyValue[] { return this.sorted((a, b) => (a.key < b.key) ? -1 : 1); } public sorted(comp: (a: IKeyValue, b: IKeyValue) => number): { key: string; value: number }[] { var elems = []; Object.keys(this.counts).forEach((label) => { elems.push({ key: label, value: this.counts[label] }); }); elems.sort(comp); return elems; } } export interface IKeyValue { key: string; value: number; } interface IFeatureState { featureCat: Cat; push(value: any): void; pop(): void; } class FeatureState implements IFeatureState { private stack: string[] = []; private counts = {}; private allowed_values = null; public feature: string; constructor(public featureCat: Cat, allowed: Cat[]= null, private replace: boolean = false, public offset = 1) { if (allowed) { this.allowed_values = {}; allowed.forEach(v=> this.allowed_values[v] = true); } this.feature = Cat[featureCat] + offset; } public current(): string { if (this.stack.length >= this.offset) { return this.stack[this.stack.length - this.offset]; } return null; } public push(value: any) { if (this.replace) { this.stack = []; } if (this.allowed_values) { if (!this.allowed_values[value]) { throw ("value not allowed: " + value); } // convert to string value = Cat[value]; } this.stack.push(value); var current = this.current(); } public pop() { this.stack.pop(); } public display(out: Util.IOutput) { out.horizontal(() => { out.show("Feature " + Cat[this.featureCat] + " offset " + this.offset); out.vertical(() => { Object.keys(this.counts).forEach(label => { var v = this.counts[label]; if (v instanceof TokenCount) { out.horizontal(() => { out.show("Cat " + label); v.display(out); }); } }); }); }); } } class FeatureStateStack implements IFeatureState { constructor(public featureCat: Cat, public depth: number, allowed: Cat[]= null) { for (var i = 0; i < depth; i++) { var feature = new FeatureState(featureCat, allowed, false, i + 1); this[i] = feature; } } public pop() { for (var i = 0; i < this.depth; i++) { this[i].pop(); } } public push(v: any) { for (var i = 0; i < this.depth; i++) { this[i].push(v); } } public at(i: number): FeatureState { return this[i]; } } class FeatureStates { public features: FeatureState[] = []; private register(fs: IFeatureState) { if (fs instanceof FeatureStateStack) { var fss = <FeatureStateStack>fs; for (var i = 0; i < fss.depth; i++) { var f = fss.at(i); this.features.push(f); this[f.feature] = f; } } else if (fs instanceof FeatureState) { var pfs = <FeatureState>fs; if (pfs.featureCat == Cat.intrinsic) { pfs.push(Cat.all); } this.features.push(pfs); this[pfs.feature] = f; } else { throw "unknown kind of feature state" } this[fs.featureCat] = fs; } constructor() { this.register(new FeatureState(Cat.intrinsic, [Cat.all])); this.register(new FeatureState(Cat.expr_context, [Cat.for_bound, Cat.foreach_collection, Cat.if_cond, Cat.while_cond, Cat.where, Cat.expr_stmt])); this.register(new FeatureState(Cat.top_context, [Cat.page_init, Cat.page_body, Cat.action_body, Cat.event_body])); this.register(new FeatureState(Cat.token_context, null, true)); this.register(new FeatureStateStack(Cat.stmt_context, 3, [Cat.top, Cat.then_body, Cat.else_body, Cat.for_body, Cat.foreach_body, Cat.while_body, Cat.handler_body, Cat.boxed_body])); this.register(new FeatureStateStack(Cat.prop_context, 2)); this.register(new FeatureState(Cat.selected_type, null, true)); } public push(feature: Cat, value: any) { this[feature].push(value); } public pop(feature: Cat) { this[feature].pop(); } public state(f: string): string { var feature = this[f]; if (feature) { return feature.current(); } return null; } } enum Cat { // categories intrinsic, expr_context, top_context, token_context, stmt_context, expected_type, prop_context, selected_type, // intrinsic all, // expr_context for_bound, foreach_collection, if_cond, while_cond, where, expr_stmt, // stmt_context top, then_body, else_body, for_body, foreach_body, while_body, handler_body, boxed_body, // top_context page_init, page_body, action_body, event_body, // token_context first_token, singleton, thing, nothing, } export interface ITokenObserver { observeGoal(s: AstState, goal: string): void; observeEnumerable(type: string): void; observeProperty(name: string): void; observeNestedGoal(outer: IFrequencies, inner: IFrequencies): void; observeSelectedType(type: string, topGoal: string): void; } interface ICategoryMap { [cat: string]: TokenCount; } export class FrequencyCounter implements ITokenObserver { public goals: GoalCounter = new GoalCounter(); public props = new TokenCount(); public types = new TokenCount(); public observeEnumerable(type: string) { } public observeProperty(name: string) { this.props.count(name); var sp = name.split(":"); this.types.count(sp[0]); } public observeNestedGoal(outer: IFrequencies, inner: IFrequencies) { Object.keys(outer).forEach(k1 => Object.keys(inner).forEach(k2=> { this.goals.countNested(k1, k2, outer[k1] * inner[k2]); }) ); } public observeGoal(s: AstState, goal: string) { s.goalState.goalWindow.forEach(g => { this.goals.countPair(g, goal); }); } public observeSelectedType(type: string, topGoal: string): void { this.goals.countPair("selected:" + type, topGoal); } public display(out: Util.IOutput) { out.vertical(() => { this.props.sortedValues().forEach(pair => out.horizontal(() => { out.show("Property " + pair.key + " : " + PredictionEvaluator.percentage(pair.value, this.props.total)); }) ); }); out.vertical(() => { this.goals.display(out); }); } public classifier(max: number): IClassifier { return { topGoals: this.goals.windowCorrelation, propFreq: this.props, typeFreq: this.types }; } } interface ICallingContext { prop: string; isLocal: boolean; type: string; args: string[]; index: number; open_parens: number; } interface IFixContext { precedence: number; goal: any; resultType: string; } interface IGoalContext { start: number; goal: IFrequencies; fixContext: IFixContext[]; } class RecentWindow { public recents: string[] = []; constructor(private max: number) { } public use(name: string) { var present = this.recents.indexOf(name); if (present >= 0) { this.recents.splice(present, 1); this.recents.push(name); } else { this.recents.push(name); if (this.recents.length > this.max) { this.recents.shift(); } } } } class TokenState extends AST.Json.NodeVisitor { public propStack: ICallingContext[] = []; public fixContext: IGoalContext[] = []; public currentSelectedType: string = null; private lastPos = -1; private selectedType: string[] = []; private goal: any[] = []; public nestedParenthesis: number[] = []; constructor(private topGoal: string, private tokens: AST.Json.JToken[], private resolver: AST.Json.IScriptResolver, private localType: (id: string) => string, private observer: ITokenObserver, private guessNestedGoal?: (parent: IFrequencies) => IFrequencies) { super(); } public visit_token(tok: AST.Json.JToken) { throw "missing token specialization"; } sanitizeType(type: string): string { if (type && type.indexOf('{') >= 0) { type = "UserRecord"; } return type; } changeSelectedType(type: string) { type = this.sanitizeType(type); if (this.currentSelectedType != type) { this.currentSelectedType = type; if (type && this.topGoal && this.observer && this.fixContext.length == 1) { this.observer.observeSelectedType(type, this.topGoal); } } } public visit_stringLiteral(lit: AST.Json.JStringLiteral): any { //this.observe("strlit:" + lit.value); //this.state.features.push(Cat.token_context, Cat.thing); this.changeSelectedType("String"); } public visit_numberLiteral(lit: AST.Json.JNumberLiteral): any { //this.observe("numlit:" + lit.value.toString()); //this.state.features.push(Cat.token_context, Cat.thing); this.changeSelectedType("Number"); } public visit_booleanLiteral(lit: AST.Json.JBooleanLiteral): any { //this.observe("boolit:" + lit.value.toString()); //this.state.features.push(Cat.token_context, Cat.thing); this.changeSelectedType("Boolean"); } public visit_placeholder(p: AST.Json.JPlaceholder): any { this.changeSelectedType(<any>p.type); } public visit_localRef(local: AST.Json.JLocalRef): any { var localId: string = <any>(local.localId); var type = this.localType(localId); if (type) { this.changeSelectedType(type); } else { throw "local type not found"; } } public visit_singletonRef(singleton: AST.Json.JSingletonRef): any { this.changeSelectedType(<any>singleton.type); } public visit_propertyRef(property: AST.Json.JPropertyRef): any { var parent = <string><any>property.parent; if (parent == "data") { var type = this.resolver.dataType(property.declId); this.changeSelectedType(type); return; } if (parent == "art") { var type = this.resolver.artType(property.declId); this.changeSelectedType(type); return; } if (parent == "♻") { this.changeSelectedType(property.name); return; } if (parent == "records") { this.changeSelectedType("UserRecord"); return; } if (parent == "code" || property.declId) { var action = this.resolver.action(property.declId); var resultType; var tokenContext; if (action.outParameters.length >= 1) { resultType = action.outParameters[0].type; } else { resultType = "Nothing"; } if (action.inParameters.length > 0) { this.propStack.push({ prop: action.name, type: this.sanitizeType(resultType), args: action.inParameters.map(p => this.sanitizeType(<any>p.type)), index: 0, open_parens: 0, isLocal: true }); this.changeSelectedType(null); // need to see parentheses } else { this.changeSelectedType(resultType); } return; } var record = this.resolver.asRecord(property); if (record) { // todo return; } if (parent.indexOf('{') == 0) { return; var ptype = JSON.parse(parent); if (ptype) { if (ptype.o) { // object type return; } else if (ptype.g) { // generic type return; } else { return; } } else { return; } } var jprop = this.resolver.resolve(property); if (jprop) { if (this.observer) { this.observer.observeProperty(property.parent + ":" + property.name); } if (jprop.parameters.length <= 1) { // implicit this parameter is always 1st parameter var rtype = this.resolver.returnType(jprop); this.changeSelectedType(rtype); } else { this.propStack.push({ prop: jprop.name, type: this.sanitizeType(<any>jprop.result.type), args: jprop.parameters.map(p => this.sanitizeType(<string><any>p.type)), index: 0, open_parens: 0, isLocal: false }); this.changeSelectedType(null); // need to see parentheses } } else { // deal with lvalues? switch (property.name) { case 'get': if (this.observer) { this.observer.observeProperty("UserRecord:" + property.name); } // selected type does not change return; case 'confirmed': case 'invalid row': if (this.observer) { this.observer.observeProperty("UserRecord:" + property.name); } this.changeSelectedType("Boolean"); return; case 'count': if (this.observer) { this.observer.observeProperty("UserRecord:" + property.name); } this.changeSelectedType("Number"); return; case 'set': case 'clear': case 'post to wall': if (this.observer) { this.observer.observeProperty("UserRecord:" + property.name); } this.changeSelectedType("Nothing"); return; case 'add': if (this.observer) { this.observer.observeProperty("UserRecord:" + property.name); } this.changeSelectedType(null); this.propStack.push({ prop: property.name, type: "Number", args: ["Number"], index: 0, open_parens: 0, isLocal: false }); return; case 'singleton': case 'add row': if (this.observer) { this.observer.observeProperty("UserRecord:" + property.name); } var rtype = this.getRecordAtType(parent); this.changeSelectedType(rtype); return; case 'row at': case 'at': if (this.observer) { this.observer.observeProperty("UserRecord:" + property.name); } this.changeSelectedType(null); var rtype = this.getRecordAtType(parent); this.propStack.push({ prop: property.name, type: rtype, args: ["Number"], index: 0, open_parens: 0, isLocal: false }); return; case 'test and set': if (this.observer) { this.observer.observeProperty("UserRecord:" + property.name); } this.changeSelectedType(null); var rtype = "Nothing"; this.propStack.push({ prop: property.name, type: rtype, args: [parent], index: 0, open_parens: 0, isLocal: false }); return; } throw ("unknown property " + property.name); } } private getRecordAtType(record: string): string { if (record.length > 6) { var end = record.slice(record.length - 6); if (end == " index") { return record.slice(0, record.length - 6); } if (end == " table") { return record.slice(0, record.length - 6); } if (record.length > 11) { end = record.slice(record.length - 10); if (end == " decorator") { return record.slice(0, record.length - 10); } } throw "unknown record name:" + record; } return this.sanitizeType(record); } private guessGoal(parent: IFrequencies): any { this.nestedParenthesis.push(this.lastPos); if (this.guessNestedGoal) { return this.guessNestedGoal(parent); } return null; } private resultType(goal: IGoalContext): string { if (goal.fixContext.length > 0) { return goal.fixContext[0].resultType; } return this.currentSelectedType; } public visit_operator(op: AST.Json.JOperator): any { switch (op.op) { case '(': var parentGoal = this.lastIncompleteGoal(this.fixContext.peek()); var newGoal = { start: this.lastPos, goal: <IFrequencies>{}, fixContext: [] }; this.fixContext.push(newGoal); // new fix context var prop = this.propStack.peek(); this.changeSelectedType("Initial"); if (prop) { if (prop.open_parens == 0) { if (prop.args.length > 0) { newGoal.goal["a:" + prop.args[0]] = 1; } else { newGoal.goal["a:Number"] = 1; // buggy code, pretend } } else { // guess a new goal! // TODO: newGoal.goal = this.guessGoal(parentGoal); } prop.open_parens++; } else { newGoal.goal = this.guessGoal(parentGoal); } break; case ')': var topFix = this.fixContext.pop(); if (!topFix) break; var prop = this.propStack.peek(); if (prop) { if (--prop.open_parens == 0) { // pop prop this.propStack.pop(); this.changeSelectedType(prop.type); } else { this.changeSelectedType(this.resultType(topFix)); this.fixupGoal(topFix.start, this.lastPos, "a:" + this.currentSelectedType); } } else { this.changeSelectedType(this.resultType(topFix)); this.fixupGoal(topFix.start, this.lastPos, "a:" + this.currentSelectedType); } break; case ',': var topFix = this.fixContext.peek(); topFix.fixContext = []; topFix.goal = {}; var prop = this.propStack.peek(); if (prop) { prop.index++; if (prop.args.length > prop.index) { topFix.goal["a:" + prop.args[prop.index]] = 1; } else { topFix.goal["a:Nothing"] = 1; // parse error } } else { topFix.goal["a:Nothing"] = 1; } this.changeSelectedType("Initial"); break; case ':=': var topFix = this.fixContext.peek(); topFix.fixContext = []; topFix.goal = {}; topFix.goal["a:Nothing"] = 1; this.changeSelectedType("Initial"); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': throw "Digit not expected here"; break; case '+': this.pushFix(5, "a:Number", "Number", "Number:+"); break; case '-': if (this.currentSelectedType == "Number") { this.pushFix(5, "a:Number", "Number", "Number:-"); } else { // prefix this.pushFix(7, "a:Number", "Number", "Number:u-"); } break; case 'not': this.pushFix(2.5, "a:Boolean", "Boolean", "Boolean:not"); break; case 'and': this.pushFix(2, "a:Boolean", "Boolean", "Boolean:and"); break; case 'or': this.pushFix(1, "a:Boolean", "Boolean", "Boolean:or"); break; case '*': this.pushFix(6, "a:Number", "Number", "Number:*"); break; case '/': this.pushFix(6, "a:Number", "Number", "Number:/"); break; case '=': case '\u2260': // "!=" case '<': case '\u2264': // "<=" case '>': case '\u2265': // ">=" this.pushFix(3, "a:Number", "Boolean", "Number:" + op.op); break; case '\u2225': // "||" this.pushFix(4, "a:String", "String", "String:\u2225"); break; case 'async': case 'await': // skip break; default: throw "Unknown operator " + op.op; break; } } private fixupGoal(start: number, end: number, goal: string) { if (this.observer) { for (var i = start + 1; i <= end; i++) { if (!this.goal[i]) { var dist = {}; this.goal[i] = dist; dist[goal] = 1; } } } } private pushFix(precedence: number, goal: any, resultType: string, opProp: string) { if (this.observer) { this.observer.observeProperty(opProp); } var topFix = this.fixContext.peek(); while (topFix.fixContext.length > 0 && topFix.fixContext.peek().precedence >= precedence) { topFix.fixContext.pop(); } topFix.fixContext.push({ goal: goal, precedence: precedence, resultType: resultType }); this.currentSelectedType = "Initial"; } public analyze(topGoal: IFrequencies): any { this.propStack = []; this.fixContext = []; this.currentSelectedType = "Initial"; var numberToken = null; this.fixContext.push({ start: 0, goal: topGoal, fixContext: [] }); for (var i = 0; i < this.tokens.length; i++) { this.lastPos = i; this.recordPosInfo(i); var token = this.tokens[i]; if (token.nodeType == "operator") { var op = <AST.Json.JOperator>token; switch (op.op) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': if (!numberToken) { numberToken = ""; this.changeSelectedType("Number"); } numberToken = numberToken + op.op; continue; default: break; } } if (numberToken) { // observe entire number here numberToken = null; } this.dispatch(token); } if (numberToken) { // observe entire number here numberToken = null; } this.recordPosInfo(this.tokens.length); if (this.observer) { this.observeNestedGoals(); } } private observeNestedGoals() { this.nestedParenthesis.forEach(n => { var outer = this.goal[n]; var inner = this.goal[n + 1]; this.observer.observeNestedGoal(outer, inner); }); } private recordPosInfo(i: number) { this.selectedType[i] = this.currentSelectedType; this.goal[i] = this.lastIncompleteGoal(this.fixContext.peek()); } private lastIncompleteGoal(context: IGoalContext): IFrequencies { var pos = context.fixContext.length - 1; while (pos >= 0 && context.fixContext[pos].goal == this.currentSelectedType) { pos--; } if (pos < 0) { return context.goal; } var result:IFrequencies = {}; result[context.fixContext[pos].goal] = 1; return result; } } export class AstState { public resolver: AST.Json.ScriptResolver; public goalState: GoalState = new GoalState(); constructor(public apiresolver: AST.Json.IResolver, private globalOnly: boolean) { this.resolver = new AST.Json.ScriptResolver(apiresolver); this.goalState.resolver = this.resolver; this.goalState.globalOnly = globalOnly; } public display(out: Util.IOutput) { out.vertical(() => { // this.features.features.forEach(v => v.display(out)); }); } } export interface IFrequencies { [key: string]: number; } export interface IHistogram { counts: IFrequencies; total: number; } export interface ICorrelation { histoA: IHistogram; histoB: IHistogram; correlations: { [a: string]: IHistogram } total: number; } export interface IClassifier { topGoals: ICorrelation; propFreq: IHistogram; typeFreq: IHistogram; } /// Used only during training. Calculator.ts has its own predictor class Predictor { constructor(public classifier: IClassifier) { } public topGoalPrediction(window: string[]): { prediction: string; probability: number }[] { var freq:IFrequencies = {}; var factor = 0; window.forEach(g => factor += this.classifier.topGoals.histoA[g]); if (factor == 0) factor = 1; factor = 1 / (factor); window.forEach(a => { var counts = this.classifier.topGoals.correlations[a]; if (counts) { Predictor.add(freq, counts.counts); } }); var result = []; Object.keys(freq).forEach(k => result.push({ prediction: k, probability: freq[k] * factor })); result.sort((a, b) => b.probability - a.probability); return result; } static add(target: IFrequencies, source: IFrequencies) { Object.keys(source).forEach(k => { var value = source[k]; if (target[k]) { target[k] = target[k] + value; } else { target[k] = value; } }); } static mul(target: IFrequencies, n: number) { Object.keys(target).forEach(k => { var value = target[k]; target[k] = value * n; }); } static top(from: IFrequencies): { token: string; value: number; }[] { var elems = []; Object.keys(from).forEach((token) => { elems.push({ token: token, value: from[token] }); }); elems.sort((a, b) => b.value - a.value); return elems; } } class HitCounter { features: { [feature: string]: { [cat: string]: { hits: number; misses: number; distance: number } } } = {}; counter(feature: string, cat: string): { hits: number; misses: number; distance: number } { var f = this.features[feature]; if (!f) { f = {}; this.features[feature] = f; } var c = f[cat]; if (!c) { c = { hits: 0, misses: 0, distance: 0 }; f[cat] = c; } return c; } public hit(feature: string, cat: string, distance: number) { var c = this.counter(feature, cat); c.hits++; c.distance += distance; } public miss(feature: string, cat: string) { var c = this.counter(feature, cat); c.misses++; } public display(out: Util.IOutput) { out.vertical(() => { Object.keys(this.features).forEach(fname => { var f = this.features[fname]; out.horizontal(() => { out.show("Feature " + fname); out.vertical(() => { Object.keys(f).forEach(label => { var counter = f[label]; out.horizontal(() => { out.show("Cat " + label); out.show(" Rate: " + PredictionEvaluator.percentage(counter.hits, counter.hits + counter.misses)); out.show(" Distance: " + counter.distance / counter.hits); }); }); }); }); }); }); } } export class PredictionEvaluator implements ITokenObserver { private predictor: Predictor; private hitmap = new TokenCount(); private missmap = new TokenCount(); private hitdistance = 0; private hitcounter: HitCounter = new HitCounter(); private goalHistogram = new TokenCount(); private nestedGoalHistogram = new TokenCount(); constructor(classifier: IClassifier) { this.predictor = new Predictor(classifier); } public observeGoal(state: AstState, goal: string) { var predictor = this.predictor.topGoalPrediction(state.goalState.goalWindow); var pos = -1; for (var i = 0; i < predictor.length; i++) { if (predictor[i].prediction == goal) { pos = i; break; } } if (pos < 0) { this.goalHistogram.count("missed"); } else { this.goalHistogram.count(pos.toString()); } } public observeSelectedType(type: string, topGoal: string) { } public observeNestedGoal(outer: IFrequencies, inner: IFrequencies) { // we no longer do this. } public observeProperty(prop: string) { } public observeEnumerable(type: string) { } public display(out: Util.IOutput): void { var total = this.hitmap.total + this.missmap.total; var hits = this.hitmap.total; out.horizontal(() => { out.show("Total: " + total); out.show(" Hits: " + hits); out.show(" Rate: " + PredictionEvaluator.percentage(hits, total)); out.show(" Hit distance: " + this.hitdistance / hits); }); this.hitcounter.display(out); out.horizontal(() => { out.vertical(() => { out.show("missed tokens"); this.missmap.display(out); }); out.show('============='); out.vertical(() => { out.show("hit tokens"); this.hitmap.display(out); }); }); out.show('============='); out.horizontal(() => out.show("Top Goal prediction")); var running = 0; var missed = 0; this.goalHistogram.sorted((a, b) => parseFloat(a.key) - parseFloat(b.key)).forEach(item => { running += item.value; if (item.key == "missed") missed = item.value; else { out.show("within " + item.key + " : " + PredictionEvaluator.percentage(running, this.goalHistogram.total)); } }); out.show("missed: " + PredictionEvaluator.percentage(missed, this.goalHistogram.total)); out.show('============='); out.horizontal(() => out.show("Nested Goal prediction")); var running = 0; var missed = 0; this.nestedGoalHistogram.sortedKeys().forEach(item => { running += item.value; if (item.key == "missed") missed = item.value; else { out.show("within " + item.key + " : " + PredictionEvaluator.percentage(running, this.nestedGoalHistogram.total)); } }); out.show("missed: " + PredictionEvaluator.percentage(missed, this.nestedGoalHistogram.total)); } static percentage(num: number, den: number) { if (!den) { return "--%"; } var r = 10000 * num / den; r = Math.floor(r); r = r / 100; return r.toString() + "%"; } } }
the_stack
// Generated using the following tsjava options: // tsJavaModulePath: // tsJavaModule.ts // classpath: // target/reflection-1.0.0.jar // classes: // java.lang.Boolean // java.lang.Class // java.lang.ClassLoader // java.lang.Integer // java.lang.reflect.AccessibleObject // java.lang.reflect.Constructor // java.lang.reflect.Executable // java.lang.reflect.Field // java.lang.reflect.Method // java.lang.reflect.Modifier // java.lang.reflect.Parameter // java.lang.reflect.Type // packages: // <none> /* tslint:disable:max-line-length class-name */ declare function require(name: string): any; require('source-map-support').install(); import _java = require('java'); import _ = require('lodash'); import BluePromise = require('bluebird'); import path = require('path'); _java.asyncOptions = { syncSuffix: '', asyncSuffix: 'A', promiseSuffix: 'P', promisify: BluePromise.promisify }; // JVM initialization callback which adds tsjava.classpath to the JVM classpath. function beforeJvm(): BluePromise<void> { var moduleJars: string[] = ['target/reflection-1.0.0.jar']; moduleJars.forEach((jarPath: string) => { var fullJarPath: string = path.join(__dirname, '', jarPath); _java.classpath.push(fullJarPath); }); return BluePromise.resolve(); } _java.registerClientP(beforeJvm); export module Java { 'use strict'; interface StringDict { [index: string]: string; } export type NodeJavaAPI = typeof _java; export function getJava(): NodeJavaAPI { return _java; } export function ensureJvm(): Promise<void> { return _java.ensureJvm(); } export function getClassLoader(): Java.java.lang.ClassLoader { return _java.getClassLoader(); } // Return the fully qualified class path for a class name. // Returns undefined if the className is ambiguous or not present in the configured classes. export function fullyQualifiedName(className: string): string { var shortToLongMap: StringDict = { 'Boolean': 'java.lang.Boolean', 'Class': 'java.lang.Class', 'ClassLoader': 'java.lang.ClassLoader', 'Integer': 'java.lang.Integer', 'Object': 'java.lang.Object', 'AccessibleObject': 'java.lang.reflect.AccessibleObject', 'Constructor': 'java.lang.reflect.Constructor', 'Executable': 'java.lang.reflect.Executable', 'Field': 'java.lang.reflect.Field', 'Method': 'java.lang.reflect.Method', 'Modifier': 'java.lang.reflect.Modifier', 'Parameter': 'java.lang.reflect.Parameter', 'Type': 'java.lang.reflect.Type', 'String': 'java.lang.String' }; return shortToLongMap[className]; } export function importClass(className: 'Boolean'): Java.java.lang.Boolean.Static; export function importClass(className: 'Class'): Java.java.lang.Class.Static; export function importClass(className: 'ClassLoader'): Java.java.lang.ClassLoader.Static; export function importClass(className: 'Integer'): Java.java.lang.Integer.Static; export function importClass(className: 'Object'): Java.java.lang.Object.Static; export function importClass(className: 'AccessibleObject'): Java.java.lang.reflect.AccessibleObject.Static; export function importClass(className: 'Constructor'): Java.java.lang.reflect.Constructor.Static; export function importClass(className: 'Executable'): Java.java.lang.reflect.Executable.Static; export function importClass(className: 'Field'): Java.java.lang.reflect.Field.Static; export function importClass(className: 'Method'): Java.java.lang.reflect.Method.Static; export function importClass(className: 'Modifier'): Java.java.lang.reflect.Modifier.Static; export function importClass(className: 'Parameter'): Java.java.lang.reflect.Parameter.Static; export function importClass(className: 'Type'): Java.java.lang.reflect.Type.Static; export function importClass(className: 'String'): Java.java.lang.String.Static; export function importClass(className: 'java.lang.Boolean'): Java.java.lang.Boolean.Static; export function importClass(className: 'java.lang.Class'): Java.java.lang.Class.Static; export function importClass(className: 'java.lang.ClassLoader'): Java.java.lang.ClassLoader.Static; export function importClass(className: 'java.lang.Integer'): Java.java.lang.Integer.Static; export function importClass(className: 'java.lang.Object'): Java.java.lang.Object.Static; export function importClass(className: 'java.lang.reflect.AccessibleObject'): Java.java.lang.reflect.AccessibleObject.Static; export function importClass(className: 'java.lang.reflect.Constructor'): Java.java.lang.reflect.Constructor.Static; export function importClass(className: 'java.lang.reflect.Executable'): Java.java.lang.reflect.Executable.Static; export function importClass(className: 'java.lang.reflect.Field'): Java.java.lang.reflect.Field.Static; export function importClass(className: 'java.lang.reflect.Method'): Java.java.lang.reflect.Method.Static; export function importClass(className: 'java.lang.reflect.Modifier'): Java.java.lang.reflect.Modifier.Static; export function importClass(className: 'java.lang.reflect.Parameter'): Java.java.lang.reflect.Parameter.Static; export function importClass(className: 'java.lang.reflect.Type'): Java.java.lang.reflect.Type.Static; export function importClass(className: 'java.lang.String'): Java.java.lang.String.Static; export function importClass(className: string): any; export function importClass(className: string): any { var fullName: string = fullyQualifiedName(className) || className; return _java.import(fullName); } export function asInstanceOf(obj: any, className: 'Boolean'): Java.java.lang.Boolean; export function asInstanceOf(obj: any, className: 'Class'): Java.java.lang.Class; export function asInstanceOf(obj: any, className: 'ClassLoader'): Java.java.lang.ClassLoader; export function asInstanceOf(obj: any, className: 'Integer'): Java.java.lang.Integer; export function asInstanceOf(obj: any, className: 'Object'): Java.java.lang.Object; export function asInstanceOf(obj: any, className: 'AccessibleObject'): Java.java.lang.reflect.AccessibleObject; export function asInstanceOf(obj: any, className: 'Constructor'): Java.java.lang.reflect.Constructor; export function asInstanceOf(obj: any, className: 'Executable'): Java.java.lang.reflect.Executable; export function asInstanceOf(obj: any, className: 'Field'): Java.java.lang.reflect.Field; export function asInstanceOf(obj: any, className: 'Method'): Java.java.lang.reflect.Method; export function asInstanceOf(obj: any, className: 'Modifier'): Java.java.lang.reflect.Modifier; export function asInstanceOf(obj: any, className: 'Parameter'): Java.java.lang.reflect.Parameter; export function asInstanceOf(obj: any, className: 'Type'): Java.java.lang.reflect.Type; export function asInstanceOf(obj: any, className: 'String'): Java.java.lang.String; export function asInstanceOf(obj: any, className: 'java.lang.Boolean'): Java.java.lang.Boolean; export function asInstanceOf(obj: any, className: 'java.lang.Class'): Java.java.lang.Class; export function asInstanceOf(obj: any, className: 'java.lang.ClassLoader'): Java.java.lang.ClassLoader; export function asInstanceOf(obj: any, className: 'java.lang.Integer'): Java.java.lang.Integer; export function asInstanceOf(obj: any, className: 'java.lang.Object'): Java.java.lang.Object; export function asInstanceOf(obj: any, className: 'java.lang.reflect.AccessibleObject'): Java.java.lang.reflect.AccessibleObject; export function asInstanceOf(obj: any, className: 'java.lang.reflect.Constructor'): Java.java.lang.reflect.Constructor; export function asInstanceOf(obj: any, className: 'java.lang.reflect.Executable'): Java.java.lang.reflect.Executable; export function asInstanceOf(obj: any, className: 'java.lang.reflect.Field'): Java.java.lang.reflect.Field; export function asInstanceOf(obj: any, className: 'java.lang.reflect.Method'): Java.java.lang.reflect.Method; export function asInstanceOf(obj: any, className: 'java.lang.reflect.Modifier'): Java.java.lang.reflect.Modifier; export function asInstanceOf(obj: any, className: 'java.lang.reflect.Parameter'): Java.java.lang.reflect.Parameter; export function asInstanceOf(obj: any, className: 'java.lang.reflect.Type'): Java.java.lang.reflect.Type; export function asInstanceOf(obj: any, className: 'java.lang.String'): Java.java.lang.String; export function asInstanceOf(obj: any, className: string): any; export function asInstanceOf(obj: any, className: string): any { var fullName: string = fullyQualifiedName(className) || className; if (_java.instanceOf(obj, fullName)) { return obj; } else { throw new Error('asInstanceOf fails, obj is not a ' + fullName); } } export interface Callback<T> { (err?: Error, result?: T): void; } // Returns true if javaObject is an instance of the named class, which may be a short className. // Returns false if javaObject is not an instance of the named class. // Throws an exception if the named class does not exist, or is an ambiguous short name. export function instanceOf(javaObject: any, className: string): boolean { var fullName: string = fullyQualifiedName(className) || className; return smellsLikeJavaObject(javaObject) && _java.instanceOf(javaObject, fullName); } export function newInstanceA(className: 'Boolean', arg0: string_t, cb: Callback<boolean>): void; export function newInstanceA(className: 'Boolean', arg0: boolean_t, cb: Callback<boolean>): void; export function newInstanceA(className: 'Integer', arg0: string_t, cb: Callback<number>): void; export function newInstanceA(className: 'Integer', arg0: integer_t, cb: Callback<number>): void; export function newInstanceA(className: 'Object', cb: Callback<object_t>): void; export function newInstanceA(className: 'Modifier', cb: Callback<Java.Modifier>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: integer_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: array_t<integer_t>, arg1: integer_t, arg2: integer_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, arg1: integer_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', arg0: object_array_t, cb: Callback<string>): void; export function newInstanceA(className: 'String', cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.Boolean', arg0: string_t, cb: Callback<boolean>): void; export function newInstanceA(className: 'java.lang.Boolean', arg0: boolean_t, cb: Callback<boolean>): void; export function newInstanceA(className: 'java.lang.Integer', arg0: string_t, cb: Callback<number>): void; export function newInstanceA(className: 'java.lang.Integer', arg0: integer_t, cb: Callback<number>): void; export function newInstanceA(className: 'java.lang.Object', cb: Callback<object_t>): void; export function newInstanceA(className: 'java.lang.reflect.Modifier', cb: Callback<Java.Modifier>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: integer_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: array_t<integer_t>, arg1: integer_t, arg2: integer_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: string_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', arg0: object_array_t, cb: Callback<string>): void; export function newInstanceA(className: 'java.lang.String', cb: Callback<string>): void; export function newInstanceA(className: string, ...args: any[]): void; export function newInstanceA(className: string, ...args: any[]): any { var fullName: string = fullyQualifiedName(className) || className; args.unshift(fullName); return _java.newInstance.apply(_java, args); } export function newInstance(className: 'Boolean', arg0: string_t): boolean; export function newInstance(className: 'Boolean', arg0: boolean_t): boolean; export function newInstance(className: 'Integer', arg0: string_t): number; export function newInstance(className: 'Integer', arg0: integer_t): number; export function newInstance(className: 'Object'): object_t; export function newInstance(className: 'Modifier'): Java.Modifier; export function newInstance(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: object_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: string_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: integer_t): string; export function newInstance(className: 'String', arg0: array_t<integer_t>, arg1: integer_t, arg2: integer_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: object_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: string_t): string; export function newInstance(className: 'String', arg0: object_array_t, arg1: integer_t): string; export function newInstance(className: 'String', arg0: object_t): string; export function newInstance(className: 'String', arg0: object_t): string; export function newInstance(className: 'String', arg0: string_t): string; export function newInstance(className: 'String', arg0: object_array_t): string; export function newInstance(className: 'String', arg0: object_array_t): string; export function newInstance(className: 'String'): string; export function newInstance(className: 'java.lang.Boolean', arg0: string_t): boolean; export function newInstance(className: 'java.lang.Boolean', arg0: boolean_t): boolean; export function newInstance(className: 'java.lang.Integer', arg0: string_t): number; export function newInstance(className: 'java.lang.Integer', arg0: integer_t): number; export function newInstance(className: 'java.lang.Object'): object_t; export function newInstance(className: 'java.lang.reflect.Modifier'): Java.Modifier; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: string_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: integer_t): string; export function newInstance(className: 'java.lang.String', arg0: array_t<integer_t>, arg1: integer_t, arg2: integer_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: string_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t): string; export function newInstance(className: 'java.lang.String', arg0: object_t): string; export function newInstance(className: 'java.lang.String', arg0: object_t): string; export function newInstance(className: 'java.lang.String', arg0: string_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t): string; export function newInstance(className: 'java.lang.String', arg0: object_array_t): string; export function newInstance(className: 'java.lang.String'): string; export function newInstance(className: string, ...args: any[]): any; export function newInstance(className: string, ...args: any[]): any { var fullName: string = fullyQualifiedName(className) || className; args.unshift(fullName); return _java.newInstanceSync.apply(_java, args); } export function newInstanceP(className: 'Boolean', arg0: string_t): Promise<boolean>; export function newInstanceP(className: 'Boolean', arg0: boolean_t): Promise<boolean>; export function newInstanceP(className: 'Integer', arg0: string_t): Promise<number>; export function newInstanceP(className: 'Integer', arg0: integer_t): Promise<number>; export function newInstanceP(className: 'Object'): Promise<object_t>; export function newInstanceP(className: 'Modifier'): Promise<Java.Modifier>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: string_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: integer_t): Promise<string>; export function newInstanceP(className: 'String', arg0: array_t<integer_t>, arg1: integer_t, arg2: integer_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: integer_t, arg2: integer_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: string_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t, arg1: integer_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_t): Promise<string>; export function newInstanceP(className: 'String', arg0: string_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t): Promise<string>; export function newInstanceP(className: 'String', arg0: object_array_t): Promise<string>; export function newInstanceP(className: 'String'): Promise<string>; export function newInstanceP(className: 'java.lang.Boolean', arg0: string_t): Promise<boolean>; export function newInstanceP(className: 'java.lang.Boolean', arg0: boolean_t): Promise<boolean>; export function newInstanceP(className: 'java.lang.Integer', arg0: string_t): Promise<number>; export function newInstanceP(className: 'java.lang.Integer', arg0: integer_t): Promise<number>; export function newInstanceP(className: 'java.lang.Object'): Promise<object_t>; export function newInstanceP(className: 'java.lang.reflect.Modifier'): Promise<Java.Modifier>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: string_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: integer_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: array_t<integer_t>, arg1: integer_t, arg2: integer_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t, arg2: integer_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: string_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t, arg1: integer_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: string_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t): Promise<string>; export function newInstanceP(className: 'java.lang.String', arg0: object_array_t): Promise<string>; export function newInstanceP(className: 'java.lang.String'): Promise<string>; export function newInstanceP(className: string, ...args: any[]): Promise<any>; export function newInstanceP(className: string, ...args: any[]): Promise<any> { var fullName: string = fullyQualifiedName(className) || className; args.unshift(fullName); return _java.newInstanceP.apply(_java, args); } export function newArray(className: 'Boolean', arg: boolean_t[]): array_t<java.lang.Boolean>; export function newArray(className: 'Class', arg: Java.Class[]): array_t<java.lang.Class>; export function newArray(className: 'ClassLoader', arg: Java.ClassLoader[]): array_t<java.lang.ClassLoader>; export function newArray(className: 'Integer', arg: integer_t[]): array_t<java.lang.Integer>; export function newArray(className: 'Object', arg: object_t[]): array_t<java.lang.Object>; export function newArray(className: 'AccessibleObject', arg: Java.AccessibleObject[]): array_t<java.lang.reflect.AccessibleObject>; export function newArray(className: 'Constructor', arg: Java.Constructor[]): array_t<java.lang.reflect.Constructor>; export function newArray(className: 'Executable', arg: Java.Executable[]): array_t<java.lang.reflect.Executable>; export function newArray(className: 'Field', arg: Java.Field[]): array_t<java.lang.reflect.Field>; export function newArray(className: 'Method', arg: Java.Method[]): array_t<java.lang.reflect.Method>; export function newArray(className: 'Modifier', arg: Java.Modifier[]): array_t<java.lang.reflect.Modifier>; export function newArray(className: 'Parameter', arg: Java.Parameter[]): array_t<java.lang.reflect.Parameter>; export function newArray(className: 'Type', arg: Java.Type[]): array_t<java.lang.reflect.Type>; export function newArray(className: 'String', arg: string_t[]): array_t<java.lang.String>; export function newArray(className: 'java.lang.Boolean', arg: boolean_t[]): array_t<java.lang.Boolean>; export function newArray(className: 'java.lang.Class', arg: Java.Class[]): array_t<java.lang.Class>; export function newArray(className: 'java.lang.ClassLoader', arg: Java.ClassLoader[]): array_t<java.lang.ClassLoader>; export function newArray(className: 'java.lang.Integer', arg: integer_t[]): array_t<java.lang.Integer>; export function newArray(className: 'java.lang.Object', arg: object_t[]): array_t<java.lang.Object>; export function newArray(className: 'java.lang.reflect.AccessibleObject', arg: Java.AccessibleObject[]): array_t<java.lang.reflect.AccessibleObject>; export function newArray(className: 'java.lang.reflect.Constructor', arg: Java.Constructor[]): array_t<java.lang.reflect.Constructor>; export function newArray(className: 'java.lang.reflect.Executable', arg: Java.Executable[]): array_t<java.lang.reflect.Executable>; export function newArray(className: 'java.lang.reflect.Field', arg: Java.Field[]): array_t<java.lang.reflect.Field>; export function newArray(className: 'java.lang.reflect.Method', arg: Java.Method[]): array_t<java.lang.reflect.Method>; export function newArray(className: 'java.lang.reflect.Modifier', arg: Java.Modifier[]): array_t<java.lang.reflect.Modifier>; export function newArray(className: 'java.lang.reflect.Parameter', arg: Java.Parameter[]): array_t<java.lang.reflect.Parameter>; export function newArray(className: 'java.lang.reflect.Type', arg: Java.Type[]): array_t<java.lang.reflect.Type>; export function newArray(className: 'java.lang.String', arg: string_t[]): array_t<java.lang.String>; export function newArray<T>(className: string, arg: any[]): array_t<T>; export function newArray<T>(className: string, arg: any[]): array_t<T> { var fullName: string = fullyQualifiedName(className) || className; return _java.newArray(fullName, arg); } // export module Java { // Node-java has special handling for methods that return long or java.lang.Long, // returning a Javascript Number but with an additional property longValue. export interface longValue_t extends Number { longValue: string; } // Node-java can automatically coerce a javascript string into a java.lang.String. // This special type alias allows to declare that possiblity to Typescript. export type string_t = string | Java.java.lang.String; // Java methods that take java.lang.Object parameters implicitly will take a java.lang.String. // But string_t is not sufficient for this case, we need object_t. export type object_t = Java.java.lang.Object | string | boolean | number | longValue_t; // Java methods that take long or java.lang.Long parameters may take javascript numbers, // longValue_t (see above) or java.lang.Long. // This special type alias allows to declare that possiblity to Typescript. export type long_t = number | longValue_t ; // Handling of other primitive numeric types is simpler, as there is no loss of precision. export type boolean_t = boolean | Java.java.lang.Boolean; export type short_t = number ; export type integer_t = number | Java.java.lang.Integer; export type double_t = number ; export type float_t = number ; export type number_t = number ; export interface array_t<T> extends Java.java.lang.Object { // This is an opaque type for a java array_t T[]; // Use Java.newArray<T>(className, [...]) to create wherever a Java method expects a T[], // most notably for vararg parameteters. __dummy: T; } export type object_array_t = array_t<Java.java.lang.Object> | object_t[]; export import Boolean = java.lang.Boolean; export import Class = java.lang.Class; export import ClassLoader = java.lang.ClassLoader; export import Integer = java.lang.Integer; export import Object = java.lang.Object; export import AccessibleObject = java.lang.reflect.AccessibleObject; export import Constructor = java.lang.reflect.Constructor; export import Executable = java.lang.reflect.Executable; export import Field = java.lang.reflect.Field; export import Method = java.lang.reflect.Method; export import Modifier = java.lang.reflect.Modifier; export import Parameter = java.lang.reflect.Parameter; export import Type = java.lang.reflect.Type; export import String = java.lang.String; export module java.lang { export interface Boolean extends Java.java.lang.Object { // public boolean java.lang.Boolean.booleanValue() booleanValueA( cb: Callback<boolean>): void; booleanValue(): boolean; booleanValueP(): Promise<boolean>; // public int java.lang.Boolean.compareTo(java.lang.Boolean) compareToA(arg0: boolean_t, cb: Callback<number>): void; compareTo(arg0: boolean_t): number; compareToP(arg0: boolean_t): Promise<number>; // public int java.lang.Boolean.compareTo(java.lang.Object) compareToA(arg0: object_t, cb: Callback<number>): void; compareTo(arg0: object_t): number; compareToP(arg0: object_t): Promise<number>; // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Boolean { export interface Static { TRUE: boolean; FALSE: boolean; TYPE: Java.Class; class: Java.Class; new (arg0: string_t): java.lang.Boolean; new (arg0: boolean_t): java.lang.Boolean; // public static int java.lang.Boolean.compare(boolean,boolean) compareA(arg0: boolean_t, arg1: boolean_t, cb: Callback<number>): void; compare(arg0: boolean_t, arg1: boolean_t): number; compareP(arg0: boolean_t, arg1: boolean_t): Promise<number>; // public static boolean java.lang.Boolean.getBoolean(java.lang.String) getBooleanA(arg0: string_t, cb: Callback<boolean>): void; getBoolean(arg0: string_t): boolean; getBooleanP(arg0: string_t): Promise<boolean>; // public static int java.lang.Boolean.hashCode(boolean) hashCodeA(arg0: boolean_t, cb: Callback<number>): void; hashCode(arg0: boolean_t): number; hashCodeP(arg0: boolean_t): Promise<number>; // public static boolean java.lang.Boolean.logicalAnd(boolean,boolean) logicalAndA(arg0: boolean_t, arg1: boolean_t, cb: Callback<boolean>): void; logicalAnd(arg0: boolean_t, arg1: boolean_t): boolean; logicalAndP(arg0: boolean_t, arg1: boolean_t): Promise<boolean>; // public static boolean java.lang.Boolean.logicalOr(boolean,boolean) logicalOrA(arg0: boolean_t, arg1: boolean_t, cb: Callback<boolean>): void; logicalOr(arg0: boolean_t, arg1: boolean_t): boolean; logicalOrP(arg0: boolean_t, arg1: boolean_t): Promise<boolean>; // public static boolean java.lang.Boolean.logicalXor(boolean,boolean) logicalXorA(arg0: boolean_t, arg1: boolean_t, cb: Callback<boolean>): void; logicalXor(arg0: boolean_t, arg1: boolean_t): boolean; logicalXorP(arg0: boolean_t, arg1: boolean_t): Promise<boolean>; // public static boolean java.lang.Boolean.parseBoolean(java.lang.String) parseBooleanA(arg0: string_t, cb: Callback<boolean>): void; parseBoolean(arg0: string_t): boolean; parseBooleanP(arg0: string_t): Promise<boolean>; // public static java.lang.String java.lang.Boolean.toString(boolean) toStringA(arg0: boolean_t, cb: Callback<string>): void; toString(arg0: boolean_t): string; toStringP(arg0: boolean_t): Promise<string>; // public static java.lang.Boolean java.lang.Boolean.valueOf(java.lang.String) valueOfA(arg0: string_t, cb: Callback<boolean>): void; valueOf(arg0: string_t): boolean; valueOfP(arg0: string_t): Promise<boolean>; // public static java.lang.Boolean java.lang.Boolean.valueOf(boolean) valueOfA(arg0: boolean_t, cb: Callback<boolean>): void; valueOf(arg0: boolean_t): boolean; valueOfP(arg0: boolean_t): Promise<boolean>; } } } export module java.lang { export interface Class extends Java.java.lang.Object, Java.java.lang.reflect.Type { // public <U> java.lang.Class<? extends U> java.lang.Class.asSubclass(java.lang.Class<U>) asSubclassA(arg0: Java.Class, cb: Callback<Java.Class>): void; asSubclass(arg0: Java.Class): Java.Class; asSubclassP(arg0: Java.Class): Promise<Java.Class>; // public T java.lang.Class.cast(java.lang.Object) castA(arg0: object_t, cb: Callback<object_t>): void; cast(arg0: object_t): object_t; castP(arg0: object_t): Promise<object_t>; // public boolean java.lang.Class.desiredAssertionStatus() desiredAssertionStatusA( cb: Callback<boolean>): void; desiredAssertionStatus(): boolean; desiredAssertionStatusP(): Promise<boolean>; // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public java.lang.reflect.AnnotatedType[] java.lang.Class.getAnnotatedInterfaces() getAnnotatedInterfacesA( cb: Callback<object_t[]>): void; getAnnotatedInterfaces(): object_t[]; getAnnotatedInterfacesP(): Promise<object_t[]>; // public java.lang.reflect.AnnotatedType java.lang.Class.getAnnotatedSuperclass() getAnnotatedSuperclassA( cb: Callback<object_t>): void; getAnnotatedSuperclass(): object_t; getAnnotatedSuperclassP(): Promise<object_t>; // public <A> A java.lang.Class.getAnnotation(java.lang.Class<A>) getAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getAnnotation(arg0: Java.Class): object_t; getAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.Class.getAnnotations() getAnnotationsA( cb: Callback<object_t[]>): void; getAnnotations(): object_t[]; getAnnotationsP(): Promise<object_t[]>; // public <A> A[] java.lang.Class.getAnnotationsByType(java.lang.Class<A>) getAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getAnnotationsByType(arg0: Java.Class): object_t[]; getAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public java.lang.String java.lang.Class.getCanonicalName() getCanonicalNameA( cb: Callback<string>): void; getCanonicalName(): string; getCanonicalNameP(): Promise<string>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public java.lang.Class<?>[] java.lang.Class.getClasses() getClassesA( cb: Callback<Java.Class[]>): void; getClasses(): Java.Class[]; getClassesP(): Promise<Java.Class[]>; // public java.lang.ClassLoader java.lang.Class.getClassLoader() getClassLoaderA( cb: Callback<Java.ClassLoader>): void; getClassLoader(): Java.ClassLoader; getClassLoaderP(): Promise<Java.ClassLoader>; // public native java.lang.Class<?> java.lang.Class.getComponentType() getComponentTypeA( cb: Callback<Java.Class>): void; getComponentType(): Java.Class; getComponentTypeP(): Promise<Java.Class>; // public java.lang.reflect.Constructor<T> java.lang.Class.getConstructor(java.lang.Class<?>...) throws java.lang.NoSuchMethodException,java.lang.SecurityException getConstructorA(arg0: array_t<Java.Class>, cb: Callback<Java.Constructor>): void; getConstructor(...arg0: Java.Class[]): Java.Constructor; getConstructor(arg0: array_t<Java.Class>): Java.Constructor; getConstructorP(...arg0: Java.Class[]): Promise<Java.Constructor>; getConstructorP(arg0: array_t<Java.Class>): Promise<Java.Constructor>; // public java.lang.reflect.Constructor<?>[] java.lang.Class.getConstructors() throws java.lang.SecurityException getConstructorsA( cb: Callback<Java.Constructor[]>): void; getConstructors(): Java.Constructor[]; getConstructorsP(): Promise<Java.Constructor[]>; // public <A> A java.lang.Class.getDeclaredAnnotation(java.lang.Class<A>) getDeclaredAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getDeclaredAnnotation(arg0: Java.Class): object_t; getDeclaredAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.Class.getDeclaredAnnotations() getDeclaredAnnotationsA( cb: Callback<object_t[]>): void; getDeclaredAnnotations(): object_t[]; getDeclaredAnnotationsP(): Promise<object_t[]>; // public <A> A[] java.lang.Class.getDeclaredAnnotationsByType(java.lang.Class<A>) getDeclaredAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getDeclaredAnnotationsByType(arg0: Java.Class): object_t[]; getDeclaredAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public java.lang.Class<?>[] java.lang.Class.getDeclaredClasses() throws java.lang.SecurityException getDeclaredClassesA( cb: Callback<Java.Class[]>): void; getDeclaredClasses(): Java.Class[]; getDeclaredClassesP(): Promise<Java.Class[]>; // public java.lang.reflect.Constructor<T> java.lang.Class.getDeclaredConstructor(java.lang.Class<?>...) throws java.lang.NoSuchMethodException,java.lang.SecurityException getDeclaredConstructorA(arg0: array_t<Java.Class>, cb: Callback<Java.Constructor>): void; getDeclaredConstructor(...arg0: Java.Class[]): Java.Constructor; getDeclaredConstructor(arg0: array_t<Java.Class>): Java.Constructor; getDeclaredConstructorP(...arg0: Java.Class[]): Promise<Java.Constructor>; getDeclaredConstructorP(arg0: array_t<Java.Class>): Promise<Java.Constructor>; // public java.lang.reflect.Constructor<?>[] java.lang.Class.getDeclaredConstructors() throws java.lang.SecurityException getDeclaredConstructorsA( cb: Callback<Java.Constructor[]>): void; getDeclaredConstructors(): Java.Constructor[]; getDeclaredConstructorsP(): Promise<Java.Constructor[]>; // public java.lang.reflect.Field java.lang.Class.getDeclaredField(java.lang.String) throws java.lang.NoSuchFieldException,java.lang.SecurityException getDeclaredFieldA(arg0: string_t, cb: Callback<Java.Field>): void; getDeclaredField(arg0: string_t): Java.Field; getDeclaredFieldP(arg0: string_t): Promise<Java.Field>; // public java.lang.reflect.Field[] java.lang.Class.getDeclaredFields() throws java.lang.SecurityException getDeclaredFieldsA( cb: Callback<Java.Field[]>): void; getDeclaredFields(): Java.Field[]; getDeclaredFieldsP(): Promise<Java.Field[]>; // public java.lang.reflect.Method java.lang.Class.getDeclaredMethod(java.lang.String,java.lang.Class<?>...) throws java.lang.NoSuchMethodException,java.lang.SecurityException getDeclaredMethodA(arg0: string_t, arg1: array_t<Java.Class>, cb: Callback<Java.Method>): void; getDeclaredMethod(arg0: string_t, ...arg1: Java.Class[]): Java.Method; getDeclaredMethod(arg0: string_t, arg1: array_t<Java.Class>): Java.Method; getDeclaredMethodP(arg0: string_t, ...arg1: Java.Class[]): Promise<Java.Method>; getDeclaredMethodP(arg0: string_t, arg1: array_t<Java.Class>): Promise<Java.Method>; // public java.lang.reflect.Method[] java.lang.Class.getDeclaredMethods() throws java.lang.SecurityException getDeclaredMethodsA( cb: Callback<Java.Method[]>): void; getDeclaredMethods(): Java.Method[]; getDeclaredMethodsP(): Promise<Java.Method[]>; // public java.lang.Class<?> java.lang.Class.getDeclaringClass() throws java.lang.SecurityException getDeclaringClassA( cb: Callback<Java.Class>): void; getDeclaringClass(): Java.Class; getDeclaringClassP(): Promise<Java.Class>; // public java.lang.Class<?> java.lang.Class.getEnclosingClass() throws java.lang.SecurityException getEnclosingClassA( cb: Callback<Java.Class>): void; getEnclosingClass(): Java.Class; getEnclosingClassP(): Promise<Java.Class>; // public java.lang.reflect.Constructor<?> java.lang.Class.getEnclosingConstructor() throws java.lang.SecurityException getEnclosingConstructorA( cb: Callback<Java.Constructor>): void; getEnclosingConstructor(): Java.Constructor; getEnclosingConstructorP(): Promise<Java.Constructor>; // public java.lang.reflect.Method java.lang.Class.getEnclosingMethod() throws java.lang.SecurityException getEnclosingMethodA( cb: Callback<Java.Method>): void; getEnclosingMethod(): Java.Method; getEnclosingMethodP(): Promise<Java.Method>; // public T[] java.lang.Class.getEnumConstants() getEnumConstantsA( cb: Callback<object_t[]>): void; getEnumConstants(): object_t[]; getEnumConstantsP(): Promise<object_t[]>; // public java.lang.reflect.Field java.lang.Class.getField(java.lang.String) throws java.lang.NoSuchFieldException,java.lang.SecurityException getFieldA(arg0: string_t, cb: Callback<Java.Field>): void; getField(arg0: string_t): Java.Field; getFieldP(arg0: string_t): Promise<Java.Field>; // public java.lang.reflect.Field[] java.lang.Class.getFields() throws java.lang.SecurityException getFieldsA( cb: Callback<Java.Field[]>): void; getFields(): Java.Field[]; getFieldsP(): Promise<Java.Field[]>; // public java.lang.reflect.Type[] java.lang.Class.getGenericInterfaces() getGenericInterfacesA( cb: Callback<Java.Type[]>): void; getGenericInterfaces(): Java.Type[]; getGenericInterfacesP(): Promise<Java.Type[]>; // public java.lang.reflect.Type java.lang.Class.getGenericSuperclass() getGenericSuperclassA( cb: Callback<Java.Type>): void; getGenericSuperclass(): Java.Type; getGenericSuperclassP(): Promise<Java.Type>; // public java.lang.Class<?>[] java.lang.Class.getInterfaces() getInterfacesA( cb: Callback<Java.Class[]>): void; getInterfaces(): Java.Class[]; getInterfacesP(): Promise<Java.Class[]>; // public java.lang.reflect.Method java.lang.Class.getMethod(java.lang.String,java.lang.Class<?>...) throws java.lang.NoSuchMethodException,java.lang.SecurityException getMethodA(arg0: string_t, arg1: array_t<Java.Class>, cb: Callback<Java.Method>): void; getMethod(arg0: string_t, ...arg1: Java.Class[]): Java.Method; getMethod(arg0: string_t, arg1: array_t<Java.Class>): Java.Method; getMethodP(arg0: string_t, ...arg1: Java.Class[]): Promise<Java.Method>; getMethodP(arg0: string_t, arg1: array_t<Java.Class>): Promise<Java.Method>; // public java.lang.reflect.Method[] java.lang.Class.getMethods() throws java.lang.SecurityException getMethodsA( cb: Callback<Java.Method[]>): void; getMethods(): Java.Method[]; getMethodsP(): Promise<Java.Method[]>; // public native int java.lang.Class.getModifiers() getModifiersA( cb: Callback<number>): void; getModifiers(): number; getModifiersP(): Promise<number>; // public java.lang.String java.lang.Class.getName() getNameA( cb: Callback<string>): void; getName(): string; getNameP(): Promise<string>; // public java.lang.Package java.lang.Class.getPackage() getPackageA( cb: Callback<object_t>): void; getPackage(): object_t; getPackageP(): Promise<object_t>; // public java.security.ProtectionDomain java.lang.Class.getProtectionDomain() getProtectionDomainA( cb: Callback<object_t>): void; getProtectionDomain(): object_t; getProtectionDomainP(): Promise<object_t>; // public java.net.URL java.lang.Class.getResource(java.lang.String) getResourceA(arg0: string_t, cb: Callback<object_t>): void; getResource(arg0: string_t): object_t; getResourceP(arg0: string_t): Promise<object_t>; // public java.io.InputStream java.lang.Class.getResourceAsStream(java.lang.String) getResourceAsStreamA(arg0: string_t, cb: Callback<object_t>): void; getResourceAsStream(arg0: string_t): object_t; getResourceAsStreamP(arg0: string_t): Promise<object_t>; // public native java.lang.Object[] java.lang.Class.getSigners() getSignersA( cb: Callback<object_t[]>): void; getSigners(): object_t[]; getSignersP(): Promise<object_t[]>; // public java.lang.String java.lang.Class.getSimpleName() getSimpleNameA( cb: Callback<string>): void; getSimpleName(): string; getSimpleNameP(): Promise<string>; // public native java.lang.Class<? super T> java.lang.Class.getSuperclass() getSuperclassA( cb: Callback<Java.Class>): void; getSuperclass(): Java.Class; getSuperclassP(): Promise<Java.Class>; // public default java.lang.String java.lang.reflect.Type.getTypeName() getTypeNameA( cb: Callback<string>): void; getTypeName(): string; getTypeNameP(): Promise<string>; // public java.lang.reflect.TypeVariable<java.lang.Class<T>>[] java.lang.Class.getTypeParameters() getTypeParametersA( cb: Callback<object_t[]>): void; getTypeParameters(): object_t[]; getTypeParametersP(): Promise<object_t[]>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public boolean java.lang.Class.isAnnotation() isAnnotationA( cb: Callback<boolean>): void; isAnnotation(): boolean; isAnnotationP(): Promise<boolean>; // public boolean java.lang.Class.isAnnotationPresent(java.lang.Class<? extends java.lang.annotation.Annotation>) isAnnotationPresentA(arg0: Java.Class, cb: Callback<boolean>): void; isAnnotationPresent(arg0: Java.Class): boolean; isAnnotationPresentP(arg0: Java.Class): Promise<boolean>; // public boolean java.lang.Class.isAnonymousClass() isAnonymousClassA( cb: Callback<boolean>): void; isAnonymousClass(): boolean; isAnonymousClassP(): Promise<boolean>; // public native boolean java.lang.Class.isArray() isArrayA( cb: Callback<boolean>): void; isArray(): boolean; isArrayP(): Promise<boolean>; // public native boolean java.lang.Class.isAssignableFrom(java.lang.Class<?>) isAssignableFromA(arg0: Java.Class, cb: Callback<boolean>): void; isAssignableFrom(arg0: Java.Class): boolean; isAssignableFromP(arg0: Java.Class): Promise<boolean>; // public boolean java.lang.Class.isEnum() isEnumA( cb: Callback<boolean>): void; isEnum(): boolean; isEnumP(): Promise<boolean>; // public native boolean java.lang.Class.isInstance(java.lang.Object) isInstanceA(arg0: object_t, cb: Callback<boolean>): void; isInstance(arg0: object_t): boolean; isInstanceP(arg0: object_t): Promise<boolean>; // public native boolean java.lang.Class.isInterface() isInterfaceA( cb: Callback<boolean>): void; isInterface(): boolean; isInterfaceP(): Promise<boolean>; // public boolean java.lang.Class.isLocalClass() isLocalClassA( cb: Callback<boolean>): void; isLocalClass(): boolean; isLocalClassP(): Promise<boolean>; // public boolean java.lang.Class.isMemberClass() isMemberClassA( cb: Callback<boolean>): void; isMemberClass(): boolean; isMemberClassP(): Promise<boolean>; // public native boolean java.lang.Class.isPrimitive() isPrimitiveA( cb: Callback<boolean>): void; isPrimitive(): boolean; isPrimitiveP(): Promise<boolean>; // public boolean java.lang.Class.isSynthetic() isSyntheticA( cb: Callback<boolean>): void; isSynthetic(): boolean; isSyntheticP(): Promise<boolean>; // public T java.lang.Class.newInstance() throws java.lang.InstantiationException,java.lang.IllegalAccessException newInstanceA( cb: Callback<object_t>): void; newInstance(): object_t; newInstanceP(): Promise<object_t>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public java.lang.String java.lang.Class.toGenericString() toGenericStringA( cb: Callback<string>): void; toGenericString(): string; toGenericStringP(): Promise<string>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Class { export interface Static { class: Java.Class; // public static java.lang.Class<?> java.lang.Class.forName(java.lang.String,boolean,java.lang.ClassLoader) throws java.lang.ClassNotFoundException forNameA(arg0: string_t, arg1: boolean_t, arg2: Java.ClassLoader, cb: Callback<Java.Class>): void; forName(arg0: string_t, arg1: boolean_t, arg2: Java.ClassLoader): Java.Class; forNameP(arg0: string_t, arg1: boolean_t, arg2: Java.ClassLoader): Promise<Java.Class>; // public static java.lang.Class<?> java.lang.Class.forName(java.lang.String) throws java.lang.ClassNotFoundException forNameA(arg0: string_t, cb: Callback<Java.Class>): void; forName(arg0: string_t): Java.Class; forNameP(arg0: string_t): Promise<Java.Class>; } } } export module java.lang { export interface ClassLoader extends Java.java.lang.Object { // public void java.lang.ClassLoader.clearAssertionStatus() clearAssertionStatusA( cb: Callback<void>): void; clearAssertionStatus(): void; clearAssertionStatusP(): Promise<void>; // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public final java.lang.ClassLoader java.lang.ClassLoader.getParent() getParentA( cb: Callback<Java.ClassLoader>): void; getParent(): Java.ClassLoader; getParentP(): Promise<Java.ClassLoader>; // public java.net.URL java.lang.ClassLoader.getResource(java.lang.String) getResourceA(arg0: string_t, cb: Callback<object_t>): void; getResource(arg0: string_t): object_t; getResourceP(arg0: string_t): Promise<object_t>; // public java.io.InputStream java.lang.ClassLoader.getResourceAsStream(java.lang.String) getResourceAsStreamA(arg0: string_t, cb: Callback<object_t>): void; getResourceAsStream(arg0: string_t): object_t; getResourceAsStreamP(arg0: string_t): Promise<object_t>; // public java.util.Enumeration<java.net.URL> java.lang.ClassLoader.getResources(java.lang.String) throws java.io.IOException getResourcesA(arg0: string_t, cb: Callback<object_t>): void; getResources(arg0: string_t): object_t; getResourcesP(arg0: string_t): Promise<object_t>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public java.lang.Class<?> java.lang.ClassLoader.loadClass(java.lang.String) throws java.lang.ClassNotFoundException loadClassA(arg0: string_t, cb: Callback<Java.Class>): void; loadClass(arg0: string_t): Java.Class; loadClassP(arg0: string_t): Promise<Java.Class>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public void java.lang.ClassLoader.setClassAssertionStatus(java.lang.String,boolean) setClassAssertionStatusA(arg0: string_t, arg1: boolean_t, cb: Callback<void>): void; setClassAssertionStatus(arg0: string_t, arg1: boolean_t): void; setClassAssertionStatusP(arg0: string_t, arg1: boolean_t): Promise<void>; // public void java.lang.ClassLoader.setDefaultAssertionStatus(boolean) setDefaultAssertionStatusA(arg0: boolean_t, cb: Callback<void>): void; setDefaultAssertionStatus(arg0: boolean_t): void; setDefaultAssertionStatusP(arg0: boolean_t): Promise<void>; // public void java.lang.ClassLoader.setPackageAssertionStatus(java.lang.String,boolean) setPackageAssertionStatusA(arg0: string_t, arg1: boolean_t, cb: Callback<void>): void; setPackageAssertionStatus(arg0: string_t, arg1: boolean_t): void; setPackageAssertionStatusP(arg0: string_t, arg1: boolean_t): Promise<void>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module ClassLoader { export interface Static { class: Java.Class; // public static java.lang.ClassLoader java.lang.ClassLoader.getSystemClassLoader() getSystemClassLoaderA( cb: Callback<Java.ClassLoader>): void; getSystemClassLoader(): Java.ClassLoader; getSystemClassLoaderP(): Promise<Java.ClassLoader>; // public static java.net.URL java.lang.ClassLoader.getSystemResource(java.lang.String) getSystemResourceA(arg0: string_t, cb: Callback<object_t>): void; getSystemResource(arg0: string_t): object_t; getSystemResourceP(arg0: string_t): Promise<object_t>; // public static java.io.InputStream java.lang.ClassLoader.getSystemResourceAsStream(java.lang.String) getSystemResourceAsStreamA(arg0: string_t, cb: Callback<object_t>): void; getSystemResourceAsStream(arg0: string_t): object_t; getSystemResourceAsStreamP(arg0: string_t): Promise<object_t>; // public static java.util.Enumeration<java.net.URL> java.lang.ClassLoader.getSystemResources(java.lang.String) throws java.io.IOException getSystemResourcesA(arg0: string_t, cb: Callback<object_t>): void; getSystemResources(arg0: string_t): object_t; getSystemResourcesP(arg0: string_t): Promise<object_t>; } } } export module java.lang { export interface Integer extends Java.java.lang.Object { // public byte java.lang.Integer.byteValue() byteValueA( cb: Callback<object_t>): void; byteValue(): object_t; byteValueP(): Promise<object_t>; // public int java.lang.Integer.compareTo(java.lang.Integer) compareToA(arg0: integer_t, cb: Callback<number>): void; compareTo(arg0: integer_t): number; compareToP(arg0: integer_t): Promise<number>; // public int java.lang.Integer.compareTo(java.lang.Object) compareToA(arg0: object_t, cb: Callback<number>): void; compareTo(arg0: object_t): number; compareToP(arg0: object_t): Promise<number>; // public double java.lang.Integer.doubleValue() doubleValueA( cb: Callback<object_t>): void; doubleValue(): object_t; doubleValueP(): Promise<object_t>; // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public float java.lang.Integer.floatValue() floatValueA( cb: Callback<object_t>): void; floatValue(): object_t; floatValueP(): Promise<object_t>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public int java.lang.Integer.intValue() intValueA( cb: Callback<number>): void; intValue(): number; intValueP(): Promise<number>; // public long java.lang.Integer.longValue() longValueA( cb: Callback<object_t>): void; longValue(): object_t; longValueP(): Promise<object_t>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public short java.lang.Integer.shortValue() shortValueA( cb: Callback<object_t>): void; shortValue(): object_t; shortValueP(): Promise<object_t>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Integer { export interface Static { MIN_VALUE: number; MAX_VALUE: number; TYPE: Java.Class; SIZE: number; BYTES: number; class: Java.Class; new (arg0: string_t): java.lang.Integer; new (arg0: integer_t): java.lang.Integer; // public static int java.lang.Integer.bitCount(int) bitCountA(arg0: integer_t, cb: Callback<number>): void; bitCount(arg0: integer_t): number; bitCountP(arg0: integer_t): Promise<number>; // public static int java.lang.Integer.compare(int,int) compareA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; compare(arg0: integer_t, arg1: integer_t): number; compareP(arg0: integer_t, arg1: integer_t): Promise<number>; // public static int java.lang.Integer.compareUnsigned(int,int) compareUnsignedA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; compareUnsigned(arg0: integer_t, arg1: integer_t): number; compareUnsignedP(arg0: integer_t, arg1: integer_t): Promise<number>; // public static java.lang.Integer java.lang.Integer.decode(java.lang.String) throws java.lang.NumberFormatException decodeA(arg0: string_t, cb: Callback<number>): void; decode(arg0: string_t): number; decodeP(arg0: string_t): Promise<number>; // public static int java.lang.Integer.divideUnsigned(int,int) divideUnsignedA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; divideUnsigned(arg0: integer_t, arg1: integer_t): number; divideUnsignedP(arg0: integer_t, arg1: integer_t): Promise<number>; // public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,java.lang.Integer) getIntegerA(arg0: string_t, arg1: integer_t, cb: Callback<number>): void; getInteger(arg0: string_t, arg1: integer_t): number; getIntegerP(arg0: string_t, arg1: integer_t): Promise<number>; // public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String,int) getIntegerA(arg0: string_t, arg1: integer_t, cb: Callback<number>): void; getInteger(arg0: string_t, arg1: integer_t): number; getIntegerP(arg0: string_t, arg1: integer_t): Promise<number>; // public static java.lang.Integer java.lang.Integer.getInteger(java.lang.String) getIntegerA(arg0: string_t, cb: Callback<number>): void; getInteger(arg0: string_t): number; getIntegerP(arg0: string_t): Promise<number>; // public static int java.lang.Integer.hashCode(int) hashCodeA(arg0: integer_t, cb: Callback<number>): void; hashCode(arg0: integer_t): number; hashCodeP(arg0: integer_t): Promise<number>; // public static int java.lang.Integer.highestOneBit(int) highestOneBitA(arg0: integer_t, cb: Callback<number>): void; highestOneBit(arg0: integer_t): number; highestOneBitP(arg0: integer_t): Promise<number>; // public static int java.lang.Integer.lowestOneBit(int) lowestOneBitA(arg0: integer_t, cb: Callback<number>): void; lowestOneBit(arg0: integer_t): number; lowestOneBitP(arg0: integer_t): Promise<number>; // public static int java.lang.Integer.max(int,int) maxA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; max(arg0: integer_t, arg1: integer_t): number; maxP(arg0: integer_t, arg1: integer_t): Promise<number>; // public static int java.lang.Integer.min(int,int) minA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; min(arg0: integer_t, arg1: integer_t): number; minP(arg0: integer_t, arg1: integer_t): Promise<number>; // public static int java.lang.Integer.numberOfLeadingZeros(int) numberOfLeadingZerosA(arg0: integer_t, cb: Callback<number>): void; numberOfLeadingZeros(arg0: integer_t): number; numberOfLeadingZerosP(arg0: integer_t): Promise<number>; // public static int java.lang.Integer.numberOfTrailingZeros(int) numberOfTrailingZerosA(arg0: integer_t, cb: Callback<number>): void; numberOfTrailingZeros(arg0: integer_t): number; numberOfTrailingZerosP(arg0: integer_t): Promise<number>; // public static int java.lang.Integer.parseInt(java.lang.String,int) throws java.lang.NumberFormatException parseIntA(arg0: string_t, arg1: integer_t, cb: Callback<number>): void; parseInt(arg0: string_t, arg1: integer_t): number; parseIntP(arg0: string_t, arg1: integer_t): Promise<number>; // public static int java.lang.Integer.parseInt(java.lang.String) throws java.lang.NumberFormatException parseIntA(arg0: string_t, cb: Callback<number>): void; parseInt(arg0: string_t): number; parseIntP(arg0: string_t): Promise<number>; // public static int java.lang.Integer.parseUnsignedInt(java.lang.String,int) throws java.lang.NumberFormatException parseUnsignedIntA(arg0: string_t, arg1: integer_t, cb: Callback<number>): void; parseUnsignedInt(arg0: string_t, arg1: integer_t): number; parseUnsignedIntP(arg0: string_t, arg1: integer_t): Promise<number>; // public static int java.lang.Integer.parseUnsignedInt(java.lang.String) throws java.lang.NumberFormatException parseUnsignedIntA(arg0: string_t, cb: Callback<number>): void; parseUnsignedInt(arg0: string_t): number; parseUnsignedIntP(arg0: string_t): Promise<number>; // public static int java.lang.Integer.remainderUnsigned(int,int) remainderUnsignedA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; remainderUnsigned(arg0: integer_t, arg1: integer_t): number; remainderUnsignedP(arg0: integer_t, arg1: integer_t): Promise<number>; // public static int java.lang.Integer.reverse(int) reverseA(arg0: integer_t, cb: Callback<number>): void; reverse(arg0: integer_t): number; reverseP(arg0: integer_t): Promise<number>; // public static int java.lang.Integer.reverseBytes(int) reverseBytesA(arg0: integer_t, cb: Callback<number>): void; reverseBytes(arg0: integer_t): number; reverseBytesP(arg0: integer_t): Promise<number>; // public static int java.lang.Integer.rotateLeft(int,int) rotateLeftA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; rotateLeft(arg0: integer_t, arg1: integer_t): number; rotateLeftP(arg0: integer_t, arg1: integer_t): Promise<number>; // public static int java.lang.Integer.rotateRight(int,int) rotateRightA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; rotateRight(arg0: integer_t, arg1: integer_t): number; rotateRightP(arg0: integer_t, arg1: integer_t): Promise<number>; // public static int java.lang.Integer.signum(int) signumA(arg0: integer_t, cb: Callback<number>): void; signum(arg0: integer_t): number; signumP(arg0: integer_t): Promise<number>; // public static int java.lang.Integer.sum(int,int) sumA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; sum(arg0: integer_t, arg1: integer_t): number; sumP(arg0: integer_t, arg1: integer_t): Promise<number>; // public static java.lang.String java.lang.Integer.toBinaryString(int) toBinaryStringA(arg0: integer_t, cb: Callback<string>): void; toBinaryString(arg0: integer_t): string; toBinaryStringP(arg0: integer_t): Promise<string>; // public static java.lang.String java.lang.Integer.toHexString(int) toHexStringA(arg0: integer_t, cb: Callback<string>): void; toHexString(arg0: integer_t): string; toHexStringP(arg0: integer_t): Promise<string>; // public static java.lang.String java.lang.Integer.toOctalString(int) toOctalStringA(arg0: integer_t, cb: Callback<string>): void; toOctalString(arg0: integer_t): string; toOctalStringP(arg0: integer_t): Promise<string>; // public static java.lang.String java.lang.Integer.toString(int,int) toStringA(arg0: integer_t, arg1: integer_t, cb: Callback<string>): void; toString(arg0: integer_t, arg1: integer_t): string; toStringP(arg0: integer_t, arg1: integer_t): Promise<string>; // public static java.lang.String java.lang.Integer.toString(int) toStringA(arg0: integer_t, cb: Callback<string>): void; toString(arg0: integer_t): string; toStringP(arg0: integer_t): Promise<string>; // public static long java.lang.Integer.toUnsignedLong(int) toUnsignedLongA(arg0: integer_t, cb: Callback<object_t>): void; toUnsignedLong(arg0: integer_t): object_t; toUnsignedLongP(arg0: integer_t): Promise<object_t>; // public static java.lang.String java.lang.Integer.toUnsignedString(int,int) toUnsignedStringA(arg0: integer_t, arg1: integer_t, cb: Callback<string>): void; toUnsignedString(arg0: integer_t, arg1: integer_t): string; toUnsignedStringP(arg0: integer_t, arg1: integer_t): Promise<string>; // public static java.lang.String java.lang.Integer.toUnsignedString(int) toUnsignedStringA(arg0: integer_t, cb: Callback<string>): void; toUnsignedString(arg0: integer_t): string; toUnsignedStringP(arg0: integer_t): Promise<string>; // public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String,int) throws java.lang.NumberFormatException valueOfA(arg0: string_t, arg1: integer_t, cb: Callback<number>): void; valueOf(arg0: string_t, arg1: integer_t): number; valueOfP(arg0: string_t, arg1: integer_t): Promise<number>; // public static java.lang.Integer java.lang.Integer.valueOf(java.lang.String) throws java.lang.NumberFormatException valueOfA(arg0: string_t, cb: Callback<number>): void; valueOf(arg0: string_t): number; valueOfP(arg0: string_t): Promise<number>; // public static java.lang.Integer java.lang.Integer.valueOf(int) valueOfA(arg0: integer_t, cb: Callback<number>): void; valueOf(arg0: integer_t): number; valueOfP(arg0: integer_t): Promise<number>; } } } export module java.lang { export interface Object { // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Object { export interface Static { class: Java.Class; new (): java.lang.Object; } } } export module java.lang.reflect { export interface AccessibleObject extends Java.java.lang.Object { // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public <T> T java.lang.reflect.AccessibleObject.getAnnotation(java.lang.Class<T>) getAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getAnnotation(arg0: Java.Class): object_t; getAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.AccessibleObject.getAnnotations() getAnnotationsA( cb: Callback<object_t[]>): void; getAnnotations(): object_t[]; getAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.AccessibleObject.getAnnotationsByType(java.lang.Class<T>) getAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getAnnotationsByType(arg0: Java.Class): object_t[]; getAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public <T> T java.lang.reflect.AccessibleObject.getDeclaredAnnotation(java.lang.Class<T>) getDeclaredAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getDeclaredAnnotation(arg0: Java.Class): object_t; getDeclaredAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.AccessibleObject.getDeclaredAnnotations() getDeclaredAnnotationsA( cb: Callback<object_t[]>): void; getDeclaredAnnotations(): object_t[]; getDeclaredAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.AccessibleObject.getDeclaredAnnotationsByType(java.lang.Class<T>) getDeclaredAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getDeclaredAnnotationsByType(arg0: Java.Class): object_t[]; getDeclaredAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public boolean java.lang.reflect.AccessibleObject.isAccessible() isAccessibleA( cb: Callback<boolean>): void; isAccessible(): boolean; isAccessibleP(): Promise<boolean>; // public boolean java.lang.reflect.AccessibleObject.isAnnotationPresent(java.lang.Class<? extends java.lang.annotation.Annotation>) isAnnotationPresentA(arg0: Java.Class, cb: Callback<boolean>): void; isAnnotationPresent(arg0: Java.Class): boolean; isAnnotationPresentP(arg0: Java.Class): Promise<boolean>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public void java.lang.reflect.AccessibleObject.setAccessible(boolean) throws java.lang.SecurityException setAccessibleA(arg0: boolean_t, cb: Callback<void>): void; setAccessible(arg0: boolean_t): void; setAccessibleP(arg0: boolean_t): Promise<void>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module AccessibleObject { export interface Static { class: Java.Class; // public static void java.lang.reflect.AccessibleObject.setAccessible(java.lang.reflect.AccessibleObject[],boolean) throws java.lang.SecurityException setAccessibleA(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t, cb: Callback<void>): void; setAccessible(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t): void; setAccessibleP(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t): Promise<void>; } } } export module java.lang.reflect { export interface Constructor extends Java.java.lang.reflect.Executable { // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public java.lang.reflect.AnnotatedType[] java.lang.reflect.Executable.getAnnotatedExceptionTypes() getAnnotatedExceptionTypesA( cb: Callback<object_t[]>): void; getAnnotatedExceptionTypes(): object_t[]; getAnnotatedExceptionTypesP(): Promise<object_t[]>; // public java.lang.reflect.AnnotatedType[] java.lang.reflect.Executable.getAnnotatedParameterTypes() getAnnotatedParameterTypesA( cb: Callback<object_t[]>): void; getAnnotatedParameterTypes(): object_t[]; getAnnotatedParameterTypesP(): Promise<object_t[]>; // public java.lang.reflect.AnnotatedType java.lang.reflect.Executable.getAnnotatedReceiverType() getAnnotatedReceiverTypeA( cb: Callback<object_t>): void; getAnnotatedReceiverType(): object_t; getAnnotatedReceiverTypeP(): Promise<object_t>; // public abstract java.lang.reflect.AnnotatedType java.lang.reflect.Executable.getAnnotatedReturnType() getAnnotatedReturnTypeA( cb: Callback<object_t>): void; getAnnotatedReturnType(): object_t; getAnnotatedReturnTypeP(): Promise<object_t>; // public <T> T java.lang.reflect.AccessibleObject.getAnnotation(java.lang.Class<T>) getAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getAnnotation(arg0: Java.Class): object_t; getAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.AccessibleObject.getAnnotations() getAnnotationsA( cb: Callback<object_t[]>): void; getAnnotations(): object_t[]; getAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.AccessibleObject.getAnnotationsByType(java.lang.Class<T>) getAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getAnnotationsByType(arg0: Java.Class): object_t[]; getAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public <T> T java.lang.reflect.AccessibleObject.getDeclaredAnnotation(java.lang.Class<T>) getDeclaredAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getDeclaredAnnotation(arg0: Java.Class): object_t; getDeclaredAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.AccessibleObject.getDeclaredAnnotations() getDeclaredAnnotationsA( cb: Callback<object_t[]>): void; getDeclaredAnnotations(): object_t[]; getDeclaredAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.AccessibleObject.getDeclaredAnnotationsByType(java.lang.Class<T>) getDeclaredAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getDeclaredAnnotationsByType(arg0: Java.Class): object_t[]; getDeclaredAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public abstract java.lang.Class<?> java.lang.reflect.Executable.getDeclaringClass() getDeclaringClassA( cb: Callback<Java.Class>): void; getDeclaringClass(): Java.Class; getDeclaringClassP(): Promise<Java.Class>; // public abstract java.lang.Class<?>[] java.lang.reflect.Executable.getExceptionTypes() getExceptionTypesA( cb: Callback<Java.Class[]>): void; getExceptionTypes(): Java.Class[]; getExceptionTypesP(): Promise<Java.Class[]>; // public java.lang.reflect.Type[] java.lang.reflect.Executable.getGenericExceptionTypes() getGenericExceptionTypesA( cb: Callback<Java.Type[]>): void; getGenericExceptionTypes(): Java.Type[]; getGenericExceptionTypesP(): Promise<Java.Type[]>; // public java.lang.reflect.Type[] java.lang.reflect.Executable.getGenericParameterTypes() getGenericParameterTypesA( cb: Callback<Java.Type[]>): void; getGenericParameterTypes(): Java.Type[]; getGenericParameterTypesP(): Promise<Java.Type[]>; // public abstract int java.lang.reflect.Executable.getModifiers() getModifiersA( cb: Callback<number>): void; getModifiers(): number; getModifiersP(): Promise<number>; // public abstract java.lang.String java.lang.reflect.Executable.getName() getNameA( cb: Callback<string>): void; getName(): string; getNameP(): Promise<string>; // public abstract java.lang.annotation.Annotation[][] java.lang.reflect.Executable.getParameterAnnotations() getParameterAnnotationsA( cb: Callback<object_t[][]>): void; getParameterAnnotations(): object_t[][]; getParameterAnnotationsP(): Promise<object_t[][]>; // public int java.lang.reflect.Executable.getParameterCount() getParameterCountA( cb: Callback<number>): void; getParameterCount(): number; getParameterCountP(): Promise<number>; // public java.lang.reflect.Parameter[] java.lang.reflect.Executable.getParameters() getParametersA( cb: Callback<Java.Parameter[]>): void; getParameters(): Java.Parameter[]; getParametersP(): Promise<Java.Parameter[]>; // public abstract java.lang.Class<?>[] java.lang.reflect.Executable.getParameterTypes() getParameterTypesA( cb: Callback<Java.Class[]>): void; getParameterTypes(): Java.Class[]; getParameterTypesP(): Promise<Java.Class[]>; // public abstract java.lang.reflect.TypeVariable<?>[] java.lang.reflect.Executable.getTypeParameters() getTypeParametersA( cb: Callback<object_t[]>): void; getTypeParameters(): object_t[]; getTypeParametersP(): Promise<object_t[]>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public boolean java.lang.reflect.AccessibleObject.isAccessible() isAccessibleA( cb: Callback<boolean>): void; isAccessible(): boolean; isAccessibleP(): Promise<boolean>; // public boolean java.lang.reflect.AccessibleObject.isAnnotationPresent(java.lang.Class<? extends java.lang.annotation.Annotation>) isAnnotationPresentA(arg0: Java.Class, cb: Callback<boolean>): void; isAnnotationPresent(arg0: Java.Class): boolean; isAnnotationPresentP(arg0: Java.Class): Promise<boolean>; // public boolean java.lang.reflect.Executable.isSynthetic() isSyntheticA( cb: Callback<boolean>): void; isSynthetic(): boolean; isSyntheticP(): Promise<boolean>; // public boolean java.lang.reflect.Executable.isVarArgs() isVarArgsA( cb: Callback<boolean>): void; isVarArgs(): boolean; isVarArgsP(): Promise<boolean>; // public T java.lang.reflect.Constructor.newInstance(java.lang.Object...) throws java.lang.InstantiationException,java.lang.IllegalAccessException,java.lang.IllegalArgumentException,java.lang.reflect.InvocationTargetException newInstanceA(arg0: object_array_t, cb: Callback<object_t>): void; newInstance(...arg0: object_t[]): object_t; newInstance(arg0: object_array_t): object_t; newInstanceP(...arg0: object_t[]): Promise<object_t>; newInstanceP(arg0: object_array_t): Promise<object_t>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public void java.lang.reflect.AccessibleObject.setAccessible(boolean) throws java.lang.SecurityException setAccessibleA(arg0: boolean_t, cb: Callback<void>): void; setAccessible(arg0: boolean_t): void; setAccessibleP(arg0: boolean_t): Promise<void>; // public abstract java.lang.String java.lang.reflect.Executable.toGenericString() toGenericStringA( cb: Callback<string>): void; toGenericString(): string; toGenericStringP(): Promise<string>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Constructor { export interface Static { PUBLIC: number; DECLARED: number; class: Java.Class; // public static void java.lang.reflect.AccessibleObject.setAccessible(java.lang.reflect.AccessibleObject[],boolean) throws java.lang.SecurityException setAccessibleA(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t, cb: Callback<void>): void; setAccessible(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t): void; setAccessibleP(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t): Promise<void>; } } } export module java.lang.reflect { export interface Executable extends Java.java.lang.reflect.AccessibleObject { // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public java.lang.reflect.AnnotatedType[] java.lang.reflect.Executable.getAnnotatedExceptionTypes() getAnnotatedExceptionTypesA( cb: Callback<object_t[]>): void; getAnnotatedExceptionTypes(): object_t[]; getAnnotatedExceptionTypesP(): Promise<object_t[]>; // public java.lang.reflect.AnnotatedType[] java.lang.reflect.Executable.getAnnotatedParameterTypes() getAnnotatedParameterTypesA( cb: Callback<object_t[]>): void; getAnnotatedParameterTypes(): object_t[]; getAnnotatedParameterTypesP(): Promise<object_t[]>; // public java.lang.reflect.AnnotatedType java.lang.reflect.Executable.getAnnotatedReceiverType() getAnnotatedReceiverTypeA( cb: Callback<object_t>): void; getAnnotatedReceiverType(): object_t; getAnnotatedReceiverTypeP(): Promise<object_t>; // public abstract java.lang.reflect.AnnotatedType java.lang.reflect.Executable.getAnnotatedReturnType() getAnnotatedReturnTypeA( cb: Callback<object_t>): void; getAnnotatedReturnType(): object_t; getAnnotatedReturnTypeP(): Promise<object_t>; // public <T> T java.lang.reflect.AccessibleObject.getAnnotation(java.lang.Class<T>) getAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getAnnotation(arg0: Java.Class): object_t; getAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.AccessibleObject.getAnnotations() getAnnotationsA( cb: Callback<object_t[]>): void; getAnnotations(): object_t[]; getAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.AccessibleObject.getAnnotationsByType(java.lang.Class<T>) getAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getAnnotationsByType(arg0: Java.Class): object_t[]; getAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public <T> T java.lang.reflect.AccessibleObject.getDeclaredAnnotation(java.lang.Class<T>) getDeclaredAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getDeclaredAnnotation(arg0: Java.Class): object_t; getDeclaredAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.AccessibleObject.getDeclaredAnnotations() getDeclaredAnnotationsA( cb: Callback<object_t[]>): void; getDeclaredAnnotations(): object_t[]; getDeclaredAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.AccessibleObject.getDeclaredAnnotationsByType(java.lang.Class<T>) getDeclaredAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getDeclaredAnnotationsByType(arg0: Java.Class): object_t[]; getDeclaredAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public abstract java.lang.Class<?> java.lang.reflect.Executable.getDeclaringClass() getDeclaringClassA( cb: Callback<Java.Class>): void; getDeclaringClass(): Java.Class; getDeclaringClassP(): Promise<Java.Class>; // public abstract java.lang.Class<?>[] java.lang.reflect.Executable.getExceptionTypes() getExceptionTypesA( cb: Callback<Java.Class[]>): void; getExceptionTypes(): Java.Class[]; getExceptionTypesP(): Promise<Java.Class[]>; // public java.lang.reflect.Type[] java.lang.reflect.Executable.getGenericExceptionTypes() getGenericExceptionTypesA( cb: Callback<Java.Type[]>): void; getGenericExceptionTypes(): Java.Type[]; getGenericExceptionTypesP(): Promise<Java.Type[]>; // public java.lang.reflect.Type[] java.lang.reflect.Executable.getGenericParameterTypes() getGenericParameterTypesA( cb: Callback<Java.Type[]>): void; getGenericParameterTypes(): Java.Type[]; getGenericParameterTypesP(): Promise<Java.Type[]>; // public abstract int java.lang.reflect.Executable.getModifiers() getModifiersA( cb: Callback<number>): void; getModifiers(): number; getModifiersP(): Promise<number>; // public abstract java.lang.String java.lang.reflect.Executable.getName() getNameA( cb: Callback<string>): void; getName(): string; getNameP(): Promise<string>; // public abstract java.lang.annotation.Annotation[][] java.lang.reflect.Executable.getParameterAnnotations() getParameterAnnotationsA( cb: Callback<object_t[][]>): void; getParameterAnnotations(): object_t[][]; getParameterAnnotationsP(): Promise<object_t[][]>; // public int java.lang.reflect.Executable.getParameterCount() getParameterCountA( cb: Callback<number>): void; getParameterCount(): number; getParameterCountP(): Promise<number>; // public java.lang.reflect.Parameter[] java.lang.reflect.Executable.getParameters() getParametersA( cb: Callback<Java.Parameter[]>): void; getParameters(): Java.Parameter[]; getParametersP(): Promise<Java.Parameter[]>; // public abstract java.lang.Class<?>[] java.lang.reflect.Executable.getParameterTypes() getParameterTypesA( cb: Callback<Java.Class[]>): void; getParameterTypes(): Java.Class[]; getParameterTypesP(): Promise<Java.Class[]>; // public abstract java.lang.reflect.TypeVariable<?>[] java.lang.reflect.Executable.getTypeParameters() getTypeParametersA( cb: Callback<object_t[]>): void; getTypeParameters(): object_t[]; getTypeParametersP(): Promise<object_t[]>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public boolean java.lang.reflect.AccessibleObject.isAccessible() isAccessibleA( cb: Callback<boolean>): void; isAccessible(): boolean; isAccessibleP(): Promise<boolean>; // public boolean java.lang.reflect.AccessibleObject.isAnnotationPresent(java.lang.Class<? extends java.lang.annotation.Annotation>) isAnnotationPresentA(arg0: Java.Class, cb: Callback<boolean>): void; isAnnotationPresent(arg0: Java.Class): boolean; isAnnotationPresentP(arg0: Java.Class): Promise<boolean>; // public boolean java.lang.reflect.Executable.isSynthetic() isSyntheticA( cb: Callback<boolean>): void; isSynthetic(): boolean; isSyntheticP(): Promise<boolean>; // public boolean java.lang.reflect.Executable.isVarArgs() isVarArgsA( cb: Callback<boolean>): void; isVarArgs(): boolean; isVarArgsP(): Promise<boolean>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public void java.lang.reflect.AccessibleObject.setAccessible(boolean) throws java.lang.SecurityException setAccessibleA(arg0: boolean_t, cb: Callback<void>): void; setAccessible(arg0: boolean_t): void; setAccessibleP(arg0: boolean_t): Promise<void>; // public abstract java.lang.String java.lang.reflect.Executable.toGenericString() toGenericStringA( cb: Callback<string>): void; toGenericString(): string; toGenericStringP(): Promise<string>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Executable { export interface Static { PUBLIC: number; DECLARED: number; class: Java.Class; // public static void java.lang.reflect.AccessibleObject.setAccessible(java.lang.reflect.AccessibleObject[],boolean) throws java.lang.SecurityException setAccessibleA(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t, cb: Callback<void>): void; setAccessible(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t): void; setAccessibleP(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t): Promise<void>; } } } export module java.lang.reflect { export interface Field extends Java.java.lang.reflect.AccessibleObject { // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public java.lang.Object java.lang.reflect.Field.get(java.lang.Object) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException getA(arg0: object_t, cb: Callback<object_t>): void; get(arg0: object_t): object_t; getP(arg0: object_t): Promise<object_t>; // public java.lang.reflect.AnnotatedType java.lang.reflect.Field.getAnnotatedType() getAnnotatedTypeA( cb: Callback<object_t>): void; getAnnotatedType(): object_t; getAnnotatedTypeP(): Promise<object_t>; // public <T> T java.lang.reflect.AccessibleObject.getAnnotation(java.lang.Class<T>) getAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getAnnotation(arg0: Java.Class): object_t; getAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.AccessibleObject.getAnnotations() getAnnotationsA( cb: Callback<object_t[]>): void; getAnnotations(): object_t[]; getAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.AccessibleObject.getAnnotationsByType(java.lang.Class<T>) getAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getAnnotationsByType(arg0: Java.Class): object_t[]; getAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public boolean java.lang.reflect.Field.getBoolean(java.lang.Object) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException getBooleanA(arg0: object_t, cb: Callback<boolean>): void; getBoolean(arg0: object_t): boolean; getBooleanP(arg0: object_t): Promise<boolean>; // public byte java.lang.reflect.Field.getByte(java.lang.Object) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException getByteA(arg0: object_t, cb: Callback<object_t>): void; getByte(arg0: object_t): object_t; getByteP(arg0: object_t): Promise<object_t>; // public char java.lang.reflect.Field.getChar(java.lang.Object) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException getCharA(arg0: object_t, cb: Callback<object_t>): void; getChar(arg0: object_t): object_t; getCharP(arg0: object_t): Promise<object_t>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public <T> T java.lang.reflect.AccessibleObject.getDeclaredAnnotation(java.lang.Class<T>) getDeclaredAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getDeclaredAnnotation(arg0: Java.Class): object_t; getDeclaredAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.AccessibleObject.getDeclaredAnnotations() getDeclaredAnnotationsA( cb: Callback<object_t[]>): void; getDeclaredAnnotations(): object_t[]; getDeclaredAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.AccessibleObject.getDeclaredAnnotationsByType(java.lang.Class<T>) getDeclaredAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getDeclaredAnnotationsByType(arg0: Java.Class): object_t[]; getDeclaredAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public java.lang.Class<?> java.lang.reflect.Field.getDeclaringClass() getDeclaringClassA( cb: Callback<Java.Class>): void; getDeclaringClass(): Java.Class; getDeclaringClassP(): Promise<Java.Class>; // public double java.lang.reflect.Field.getDouble(java.lang.Object) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException getDoubleA(arg0: object_t, cb: Callback<object_t>): void; getDouble(arg0: object_t): object_t; getDoubleP(arg0: object_t): Promise<object_t>; // public float java.lang.reflect.Field.getFloat(java.lang.Object) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException getFloatA(arg0: object_t, cb: Callback<object_t>): void; getFloat(arg0: object_t): object_t; getFloatP(arg0: object_t): Promise<object_t>; // public java.lang.reflect.Type java.lang.reflect.Field.getGenericType() getGenericTypeA( cb: Callback<Java.Type>): void; getGenericType(): Java.Type; getGenericTypeP(): Promise<Java.Type>; // public int java.lang.reflect.Field.getInt(java.lang.Object) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException getIntA(arg0: object_t, cb: Callback<number>): void; getInt(arg0: object_t): number; getIntP(arg0: object_t): Promise<number>; // public long java.lang.reflect.Field.getLong(java.lang.Object) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException getLongA(arg0: object_t, cb: Callback<object_t>): void; getLong(arg0: object_t): object_t; getLongP(arg0: object_t): Promise<object_t>; // public int java.lang.reflect.Field.getModifiers() getModifiersA( cb: Callback<number>): void; getModifiers(): number; getModifiersP(): Promise<number>; // public java.lang.String java.lang.reflect.Field.getName() getNameA( cb: Callback<string>): void; getName(): string; getNameP(): Promise<string>; // public short java.lang.reflect.Field.getShort(java.lang.Object) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException getShortA(arg0: object_t, cb: Callback<object_t>): void; getShort(arg0: object_t): object_t; getShortP(arg0: object_t): Promise<object_t>; // public java.lang.Class<?> java.lang.reflect.Field.getType() getTypeA( cb: Callback<Java.Class>): void; getType(): Java.Class; getTypeP(): Promise<Java.Class>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public boolean java.lang.reflect.AccessibleObject.isAccessible() isAccessibleA( cb: Callback<boolean>): void; isAccessible(): boolean; isAccessibleP(): Promise<boolean>; // public boolean java.lang.reflect.AccessibleObject.isAnnotationPresent(java.lang.Class<? extends java.lang.annotation.Annotation>) isAnnotationPresentA(arg0: Java.Class, cb: Callback<boolean>): void; isAnnotationPresent(arg0: Java.Class): boolean; isAnnotationPresentP(arg0: Java.Class): Promise<boolean>; // public boolean java.lang.reflect.Field.isEnumConstant() isEnumConstantA( cb: Callback<boolean>): void; isEnumConstant(): boolean; isEnumConstantP(): Promise<boolean>; // public boolean java.lang.reflect.Field.isSynthetic() isSyntheticA( cb: Callback<boolean>): void; isSynthetic(): boolean; isSyntheticP(): Promise<boolean>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public void java.lang.reflect.Field.set(java.lang.Object,java.lang.Object) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException setA(arg0: object_t, arg1: object_t, cb: Callback<void>): void; set(arg0: object_t, arg1: object_t): void; setP(arg0: object_t, arg1: object_t): Promise<void>; // public void java.lang.reflect.AccessibleObject.setAccessible(boolean) throws java.lang.SecurityException setAccessibleA(arg0: boolean_t, cb: Callback<void>): void; setAccessible(arg0: boolean_t): void; setAccessibleP(arg0: boolean_t): Promise<void>; // public void java.lang.reflect.Field.setBoolean(java.lang.Object,boolean) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException setBooleanA(arg0: object_t, arg1: boolean_t, cb: Callback<void>): void; setBoolean(arg0: object_t, arg1: boolean_t): void; setBooleanP(arg0: object_t, arg1: boolean_t): Promise<void>; // public void java.lang.reflect.Field.setByte(java.lang.Object,byte) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException setByteA(arg0: object_t, arg1: object_t, cb: Callback<void>): void; setByte(arg0: object_t, arg1: object_t): void; setByteP(arg0: object_t, arg1: object_t): Promise<void>; // public void java.lang.reflect.Field.setChar(java.lang.Object,char) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException setCharA(arg0: object_t, arg1: object_t, cb: Callback<void>): void; setChar(arg0: object_t, arg1: object_t): void; setCharP(arg0: object_t, arg1: object_t): Promise<void>; // public void java.lang.reflect.Field.setDouble(java.lang.Object,double) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException setDoubleA(arg0: object_t, arg1: object_t, cb: Callback<void>): void; setDouble(arg0: object_t, arg1: object_t): void; setDoubleP(arg0: object_t, arg1: object_t): Promise<void>; // public void java.lang.reflect.Field.setFloat(java.lang.Object,float) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException setFloatA(arg0: object_t, arg1: object_t, cb: Callback<void>): void; setFloat(arg0: object_t, arg1: object_t): void; setFloatP(arg0: object_t, arg1: object_t): Promise<void>; // public void java.lang.reflect.Field.setInt(java.lang.Object,int) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException setIntA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; setInt(arg0: object_t, arg1: integer_t): void; setIntP(arg0: object_t, arg1: integer_t): Promise<void>; // public void java.lang.reflect.Field.setLong(java.lang.Object,long) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException setLongA(arg0: object_t, arg1: object_t, cb: Callback<void>): void; setLong(arg0: object_t, arg1: object_t): void; setLongP(arg0: object_t, arg1: object_t): Promise<void>; // public void java.lang.reflect.Field.setShort(java.lang.Object,short) throws java.lang.IllegalArgumentException,java.lang.IllegalAccessException setShortA(arg0: object_t, arg1: object_t, cb: Callback<void>): void; setShort(arg0: object_t, arg1: object_t): void; setShortP(arg0: object_t, arg1: object_t): Promise<void>; // public java.lang.String java.lang.reflect.Field.toGenericString() toGenericStringA( cb: Callback<string>): void; toGenericString(): string; toGenericStringP(): Promise<string>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Field { export interface Static { PUBLIC: number; DECLARED: number; class: Java.Class; // public static void java.lang.reflect.AccessibleObject.setAccessible(java.lang.reflect.AccessibleObject[],boolean) throws java.lang.SecurityException setAccessibleA(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t, cb: Callback<void>): void; setAccessible(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t): void; setAccessibleP(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t): Promise<void>; } } } export module java.lang.reflect { export interface Method extends Java.java.lang.reflect.Executable { // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public java.lang.reflect.AnnotatedType[] java.lang.reflect.Executable.getAnnotatedExceptionTypes() getAnnotatedExceptionTypesA( cb: Callback<object_t[]>): void; getAnnotatedExceptionTypes(): object_t[]; getAnnotatedExceptionTypesP(): Promise<object_t[]>; // public java.lang.reflect.AnnotatedType[] java.lang.reflect.Executable.getAnnotatedParameterTypes() getAnnotatedParameterTypesA( cb: Callback<object_t[]>): void; getAnnotatedParameterTypes(): object_t[]; getAnnotatedParameterTypesP(): Promise<object_t[]>; // public java.lang.reflect.AnnotatedType java.lang.reflect.Executable.getAnnotatedReceiverType() getAnnotatedReceiverTypeA( cb: Callback<object_t>): void; getAnnotatedReceiverType(): object_t; getAnnotatedReceiverTypeP(): Promise<object_t>; // public abstract java.lang.reflect.AnnotatedType java.lang.reflect.Executable.getAnnotatedReturnType() getAnnotatedReturnTypeA( cb: Callback<object_t>): void; getAnnotatedReturnType(): object_t; getAnnotatedReturnTypeP(): Promise<object_t>; // public <T> T java.lang.reflect.AccessibleObject.getAnnotation(java.lang.Class<T>) getAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getAnnotation(arg0: Java.Class): object_t; getAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.AccessibleObject.getAnnotations() getAnnotationsA( cb: Callback<object_t[]>): void; getAnnotations(): object_t[]; getAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.AccessibleObject.getAnnotationsByType(java.lang.Class<T>) getAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getAnnotationsByType(arg0: Java.Class): object_t[]; getAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public <T> T java.lang.reflect.AccessibleObject.getDeclaredAnnotation(java.lang.Class<T>) getDeclaredAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getDeclaredAnnotation(arg0: Java.Class): object_t; getDeclaredAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.AccessibleObject.getDeclaredAnnotations() getDeclaredAnnotationsA( cb: Callback<object_t[]>): void; getDeclaredAnnotations(): object_t[]; getDeclaredAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.AccessibleObject.getDeclaredAnnotationsByType(java.lang.Class<T>) getDeclaredAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getDeclaredAnnotationsByType(arg0: Java.Class): object_t[]; getDeclaredAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public abstract java.lang.Class<?> java.lang.reflect.Executable.getDeclaringClass() getDeclaringClassA( cb: Callback<Java.Class>): void; getDeclaringClass(): Java.Class; getDeclaringClassP(): Promise<Java.Class>; // public java.lang.Object java.lang.reflect.Method.getDefaultValue() getDefaultValueA( cb: Callback<object_t>): void; getDefaultValue(): object_t; getDefaultValueP(): Promise<object_t>; // public abstract java.lang.Class<?>[] java.lang.reflect.Executable.getExceptionTypes() getExceptionTypesA( cb: Callback<Java.Class[]>): void; getExceptionTypes(): Java.Class[]; getExceptionTypesP(): Promise<Java.Class[]>; // public java.lang.reflect.Type[] java.lang.reflect.Executable.getGenericExceptionTypes() getGenericExceptionTypesA( cb: Callback<Java.Type[]>): void; getGenericExceptionTypes(): Java.Type[]; getGenericExceptionTypesP(): Promise<Java.Type[]>; // public java.lang.reflect.Type[] java.lang.reflect.Executable.getGenericParameterTypes() getGenericParameterTypesA( cb: Callback<Java.Type[]>): void; getGenericParameterTypes(): Java.Type[]; getGenericParameterTypesP(): Promise<Java.Type[]>; // public java.lang.reflect.Type java.lang.reflect.Method.getGenericReturnType() getGenericReturnTypeA( cb: Callback<Java.Type>): void; getGenericReturnType(): Java.Type; getGenericReturnTypeP(): Promise<Java.Type>; // public abstract int java.lang.reflect.Executable.getModifiers() getModifiersA( cb: Callback<number>): void; getModifiers(): number; getModifiersP(): Promise<number>; // public abstract java.lang.String java.lang.reflect.Executable.getName() getNameA( cb: Callback<string>): void; getName(): string; getNameP(): Promise<string>; // public abstract java.lang.annotation.Annotation[][] java.lang.reflect.Executable.getParameterAnnotations() getParameterAnnotationsA( cb: Callback<object_t[][]>): void; getParameterAnnotations(): object_t[][]; getParameterAnnotationsP(): Promise<object_t[][]>; // public int java.lang.reflect.Executable.getParameterCount() getParameterCountA( cb: Callback<number>): void; getParameterCount(): number; getParameterCountP(): Promise<number>; // public java.lang.reflect.Parameter[] java.lang.reflect.Executable.getParameters() getParametersA( cb: Callback<Java.Parameter[]>): void; getParameters(): Java.Parameter[]; getParametersP(): Promise<Java.Parameter[]>; // public abstract java.lang.Class<?>[] java.lang.reflect.Executable.getParameterTypes() getParameterTypesA( cb: Callback<Java.Class[]>): void; getParameterTypes(): Java.Class[]; getParameterTypesP(): Promise<Java.Class[]>; // public java.lang.Class<?> java.lang.reflect.Method.getReturnType() getReturnTypeA( cb: Callback<Java.Class>): void; getReturnType(): Java.Class; getReturnTypeP(): Promise<Java.Class>; // public abstract java.lang.reflect.TypeVariable<?>[] java.lang.reflect.Executable.getTypeParameters() getTypeParametersA( cb: Callback<object_t[]>): void; getTypeParameters(): object_t[]; getTypeParametersP(): Promise<object_t[]>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public java.lang.Object java.lang.reflect.Method.invoke(java.lang.Object,java.lang.Object...) throws java.lang.IllegalAccessException,java.lang.IllegalArgumentException,java.lang.reflect.InvocationTargetException invokeA(arg0: object_t, arg1: object_array_t, cb: Callback<object_t>): void; invoke(arg0: object_t, ...arg1: object_t[]): object_t; invoke(arg0: object_t, arg1: object_array_t): object_t; invokeP(arg0: object_t, ...arg1: object_t[]): Promise<object_t>; invokeP(arg0: object_t, arg1: object_array_t): Promise<object_t>; // public boolean java.lang.reflect.AccessibleObject.isAccessible() isAccessibleA( cb: Callback<boolean>): void; isAccessible(): boolean; isAccessibleP(): Promise<boolean>; // public boolean java.lang.reflect.AccessibleObject.isAnnotationPresent(java.lang.Class<? extends java.lang.annotation.Annotation>) isAnnotationPresentA(arg0: Java.Class, cb: Callback<boolean>): void; isAnnotationPresent(arg0: Java.Class): boolean; isAnnotationPresentP(arg0: Java.Class): Promise<boolean>; // public boolean java.lang.reflect.Method.isBridge() isBridgeA( cb: Callback<boolean>): void; isBridge(): boolean; isBridgeP(): Promise<boolean>; // public boolean java.lang.reflect.Method.isDefault() isDefaultA( cb: Callback<boolean>): void; isDefault(): boolean; isDefaultP(): Promise<boolean>; // public boolean java.lang.reflect.Executable.isSynthetic() isSyntheticA( cb: Callback<boolean>): void; isSynthetic(): boolean; isSyntheticP(): Promise<boolean>; // public boolean java.lang.reflect.Executable.isVarArgs() isVarArgsA( cb: Callback<boolean>): void; isVarArgs(): boolean; isVarArgsP(): Promise<boolean>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public void java.lang.reflect.AccessibleObject.setAccessible(boolean) throws java.lang.SecurityException setAccessibleA(arg0: boolean_t, cb: Callback<void>): void; setAccessible(arg0: boolean_t): void; setAccessibleP(arg0: boolean_t): Promise<void>; // public abstract java.lang.String java.lang.reflect.Executable.toGenericString() toGenericStringA( cb: Callback<string>): void; toGenericString(): string; toGenericStringP(): Promise<string>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Method { export interface Static { PUBLIC: number; DECLARED: number; class: Java.Class; // public static void java.lang.reflect.AccessibleObject.setAccessible(java.lang.reflect.AccessibleObject[],boolean) throws java.lang.SecurityException setAccessibleA(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t, cb: Callback<void>): void; setAccessible(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t): void; setAccessibleP(arg0: array_t<Java.AccessibleObject>, arg1: boolean_t): Promise<void>; } } } export module java.lang.reflect { export interface Modifier extends Java.java.lang.Object { // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Modifier { export interface Static { PUBLIC: number; PRIVATE: number; PROTECTED: number; STATIC: number; FINAL: number; SYNCHRONIZED: number; VOLATILE: number; TRANSIENT: number; NATIVE: number; INTERFACE: number; ABSTRACT: number; STRICT: number; class: Java.Class; new (): java.lang.reflect.Modifier; // public static int java.lang.reflect.Modifier.classModifiers() classModifiersA( cb: Callback<number>): void; classModifiers(): number; classModifiersP(): Promise<number>; // public static int java.lang.reflect.Modifier.constructorModifiers() constructorModifiersA( cb: Callback<number>): void; constructorModifiers(): number; constructorModifiersP(): Promise<number>; // public static int java.lang.reflect.Modifier.fieldModifiers() fieldModifiersA( cb: Callback<number>): void; fieldModifiers(): number; fieldModifiersP(): Promise<number>; // public static int java.lang.reflect.Modifier.interfaceModifiers() interfaceModifiersA( cb: Callback<number>): void; interfaceModifiers(): number; interfaceModifiersP(): Promise<number>; // public static boolean java.lang.reflect.Modifier.isAbstract(int) isAbstractA(arg0: integer_t, cb: Callback<boolean>): void; isAbstract(arg0: integer_t): boolean; isAbstractP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isFinal(int) isFinalA(arg0: integer_t, cb: Callback<boolean>): void; isFinal(arg0: integer_t): boolean; isFinalP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isInterface(int) isInterfaceA(arg0: integer_t, cb: Callback<boolean>): void; isInterface(arg0: integer_t): boolean; isInterfaceP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isNative(int) isNativeA(arg0: integer_t, cb: Callback<boolean>): void; isNative(arg0: integer_t): boolean; isNativeP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isPrivate(int) isPrivateA(arg0: integer_t, cb: Callback<boolean>): void; isPrivate(arg0: integer_t): boolean; isPrivateP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isProtected(int) isProtectedA(arg0: integer_t, cb: Callback<boolean>): void; isProtected(arg0: integer_t): boolean; isProtectedP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isPublic(int) isPublicA(arg0: integer_t, cb: Callback<boolean>): void; isPublic(arg0: integer_t): boolean; isPublicP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isStatic(int) isStaticA(arg0: integer_t, cb: Callback<boolean>): void; isStatic(arg0: integer_t): boolean; isStaticP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isStrict(int) isStrictA(arg0: integer_t, cb: Callback<boolean>): void; isStrict(arg0: integer_t): boolean; isStrictP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isSynchronized(int) isSynchronizedA(arg0: integer_t, cb: Callback<boolean>): void; isSynchronized(arg0: integer_t): boolean; isSynchronizedP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isTransient(int) isTransientA(arg0: integer_t, cb: Callback<boolean>): void; isTransient(arg0: integer_t): boolean; isTransientP(arg0: integer_t): Promise<boolean>; // public static boolean java.lang.reflect.Modifier.isVolatile(int) isVolatileA(arg0: integer_t, cb: Callback<boolean>): void; isVolatile(arg0: integer_t): boolean; isVolatileP(arg0: integer_t): Promise<boolean>; // public static int java.lang.reflect.Modifier.methodModifiers() methodModifiersA( cb: Callback<number>): void; methodModifiers(): number; methodModifiersP(): Promise<number>; // public static int java.lang.reflect.Modifier.parameterModifiers() parameterModifiersA( cb: Callback<number>): void; parameterModifiers(): number; parameterModifiersP(): Promise<number>; // public static java.lang.String java.lang.reflect.Modifier.toString(int) toStringA(arg0: integer_t, cb: Callback<string>): void; toString(arg0: integer_t): string; toStringP(arg0: integer_t): Promise<string>; } } } export module java.lang.reflect { export interface Parameter extends Java.java.lang.Object { // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public java.lang.reflect.AnnotatedType java.lang.reflect.Parameter.getAnnotatedType() getAnnotatedTypeA( cb: Callback<object_t>): void; getAnnotatedType(): object_t; getAnnotatedTypeP(): Promise<object_t>; // public <T> T java.lang.reflect.Parameter.getAnnotation(java.lang.Class<T>) getAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getAnnotation(arg0: Java.Class): object_t; getAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.Parameter.getAnnotations() getAnnotationsA( cb: Callback<object_t[]>): void; getAnnotations(): object_t[]; getAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.Parameter.getAnnotationsByType(java.lang.Class<T>) getAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getAnnotationsByType(arg0: Java.Class): object_t[]; getAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public <T> T java.lang.reflect.Parameter.getDeclaredAnnotation(java.lang.Class<T>) getDeclaredAnnotationA(arg0: Java.Class, cb: Callback<object_t>): void; getDeclaredAnnotation(arg0: Java.Class): object_t; getDeclaredAnnotationP(arg0: Java.Class): Promise<object_t>; // public java.lang.annotation.Annotation[] java.lang.reflect.Parameter.getDeclaredAnnotations() getDeclaredAnnotationsA( cb: Callback<object_t[]>): void; getDeclaredAnnotations(): object_t[]; getDeclaredAnnotationsP(): Promise<object_t[]>; // public <T> T[] java.lang.reflect.Parameter.getDeclaredAnnotationsByType(java.lang.Class<T>) getDeclaredAnnotationsByTypeA(arg0: Java.Class, cb: Callback<object_t[]>): void; getDeclaredAnnotationsByType(arg0: Java.Class): object_t[]; getDeclaredAnnotationsByTypeP(arg0: Java.Class): Promise<object_t[]>; // public java.lang.reflect.Executable java.lang.reflect.Parameter.getDeclaringExecutable() getDeclaringExecutableA( cb: Callback<Java.Executable>): void; getDeclaringExecutable(): Java.Executable; getDeclaringExecutableP(): Promise<Java.Executable>; // public int java.lang.reflect.Parameter.getModifiers() getModifiersA( cb: Callback<number>): void; getModifiers(): number; getModifiersP(): Promise<number>; // public java.lang.String java.lang.reflect.Parameter.getName() getNameA( cb: Callback<string>): void; getName(): string; getNameP(): Promise<string>; // public java.lang.reflect.Type java.lang.reflect.Parameter.getParameterizedType() getParameterizedTypeA( cb: Callback<Java.Type>): void; getParameterizedType(): Java.Type; getParameterizedTypeP(): Promise<Java.Type>; // public java.lang.Class<?> java.lang.reflect.Parameter.getType() getTypeA( cb: Callback<Java.Class>): void; getType(): Java.Class; getTypeP(): Promise<Java.Class>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public default boolean java.lang.reflect.AnnotatedElement.isAnnotationPresent(java.lang.Class<? extends java.lang.annotation.Annotation>) isAnnotationPresentA(arg0: Java.Class, cb: Callback<boolean>): void; isAnnotationPresent(arg0: Java.Class): boolean; isAnnotationPresentP(arg0: Java.Class): Promise<boolean>; // public boolean java.lang.reflect.Parameter.isImplicit() isImplicitA( cb: Callback<boolean>): void; isImplicit(): boolean; isImplicitP(): Promise<boolean>; // public boolean java.lang.reflect.Parameter.isNamePresent() isNamePresentA( cb: Callback<boolean>): void; isNamePresent(): boolean; isNamePresentP(): Promise<boolean>; // public boolean java.lang.reflect.Parameter.isSynthetic() isSyntheticA( cb: Callback<boolean>): void; isSynthetic(): boolean; isSyntheticP(): Promise<boolean>; // public boolean java.lang.reflect.Parameter.isVarArgs() isVarArgsA( cb: Callback<boolean>): void; isVarArgs(): boolean; isVarArgsP(): Promise<boolean>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module Parameter { export interface Static { class: Java.Class; } } } export module java.lang.reflect { export interface Type extends Java.java.lang.Object { // public default java.lang.String java.lang.reflect.Type.getTypeName() getTypeNameA( cb: Callback<string>): void; getTypeName(): string; getTypeNameP(): Promise<string>; } export module Type { export interface Static { class: Java.Class; } } } export module java.lang { export interface String extends Java.java.lang.Object { // public char java.lang.String.charAt(int) charAtA(arg0: integer_t, cb: Callback<object_t>): void; charAt(arg0: integer_t): object_t; charAtP(arg0: integer_t): Promise<object_t>; // public default java.util.stream.IntStream java.lang.CharSequence.chars() charsA( cb: Callback<object_t>): void; chars(): object_t; charsP(): Promise<object_t>; // public int java.lang.String.codePointAt(int) codePointAtA(arg0: integer_t, cb: Callback<number>): void; codePointAt(arg0: integer_t): number; codePointAtP(arg0: integer_t): Promise<number>; // public int java.lang.String.codePointBefore(int) codePointBeforeA(arg0: integer_t, cb: Callback<number>): void; codePointBefore(arg0: integer_t): number; codePointBeforeP(arg0: integer_t): Promise<number>; // public int java.lang.String.codePointCount(int,int) codePointCountA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; codePointCount(arg0: integer_t, arg1: integer_t): number; codePointCountP(arg0: integer_t, arg1: integer_t): Promise<number>; // public default java.util.stream.IntStream java.lang.CharSequence.codePoints() codePointsA( cb: Callback<object_t>): void; codePoints(): object_t; codePointsP(): Promise<object_t>; // public int java.lang.String.compareTo(java.lang.String) compareToA(arg0: string_t, cb: Callback<number>): void; compareTo(arg0: string_t): number; compareToP(arg0: string_t): Promise<number>; // public int java.lang.String.compareTo(java.lang.Object) compareToA(arg0: object_t, cb: Callback<number>): void; compareTo(arg0: object_t): number; compareToP(arg0: object_t): Promise<number>; // public int java.lang.String.compareToIgnoreCase(java.lang.String) compareToIgnoreCaseA(arg0: string_t, cb: Callback<number>): void; compareToIgnoreCase(arg0: string_t): number; compareToIgnoreCaseP(arg0: string_t): Promise<number>; // public java.lang.String java.lang.String.concat(java.lang.String) concatA(arg0: string_t, cb: Callback<string>): void; concat(arg0: string_t): string; concatP(arg0: string_t): Promise<string>; // public boolean java.lang.String.contains(java.lang.CharSequence) containsA(arg0: object_t, cb: Callback<boolean>): void; contains(arg0: object_t): boolean; containsP(arg0: object_t): Promise<boolean>; // public boolean java.lang.String.contentEquals(java.lang.StringBuffer) contentEqualsA(arg0: object_t, cb: Callback<boolean>): void; contentEquals(arg0: object_t): boolean; contentEqualsP(arg0: object_t): Promise<boolean>; // public boolean java.lang.String.contentEquals(java.lang.CharSequence) contentEqualsA(arg0: object_t, cb: Callback<boolean>): void; contentEquals(arg0: object_t): boolean; contentEqualsP(arg0: object_t): Promise<boolean>; // public boolean java.lang.String.endsWith(java.lang.String) endsWithA(arg0: string_t, cb: Callback<boolean>): void; endsWith(arg0: string_t): boolean; endsWithP(arg0: string_t): Promise<boolean>; // public boolean java.lang.Object.equals(java.lang.Object) equalsA(arg0: object_t, cb: Callback<boolean>): void; equals(arg0: object_t): boolean; equalsP(arg0: object_t): Promise<boolean>; // public boolean java.lang.String.equalsIgnoreCase(java.lang.String) equalsIgnoreCaseA(arg0: string_t, cb: Callback<boolean>): void; equalsIgnoreCase(arg0: string_t): boolean; equalsIgnoreCaseP(arg0: string_t): Promise<boolean>; // public void java.lang.String.getBytes(int,int,byte[],int) getBytesA(arg0: integer_t, arg1: integer_t, arg2: object_array_t, arg3: integer_t, cb: Callback<void>): void; getBytes(arg0: integer_t, arg1: integer_t, arg2: object_array_t, arg3: integer_t): void; getBytesP(arg0: integer_t, arg1: integer_t, arg2: object_array_t, arg3: integer_t): Promise<void>; // public byte[] java.lang.String.getBytes(java.nio.charset.Charset) getBytesA(arg0: object_t, cb: Callback<object_t[]>): void; getBytes(arg0: object_t): object_t[]; getBytesP(arg0: object_t): Promise<object_t[]>; // public byte[] java.lang.String.getBytes(java.lang.String) throws java.io.UnsupportedEncodingException getBytesA(arg0: string_t, cb: Callback<object_t[]>): void; getBytes(arg0: string_t): object_t[]; getBytesP(arg0: string_t): Promise<object_t[]>; // public byte[] java.lang.String.getBytes() getBytesA( cb: Callback<object_t[]>): void; getBytes(): object_t[]; getBytesP(): Promise<object_t[]>; // public void java.lang.String.getChars(int,int,char[],int) getCharsA(arg0: integer_t, arg1: integer_t, arg2: object_array_t, arg3: integer_t, cb: Callback<void>): void; getChars(arg0: integer_t, arg1: integer_t, arg2: object_array_t, arg3: integer_t): void; getCharsP(arg0: integer_t, arg1: integer_t, arg2: object_array_t, arg3: integer_t): Promise<void>; // public final native java.lang.Class<?> java.lang.Object.getClass() getClassA( cb: Callback<Java.Class>): void; getClass(): Java.Class; getClassP(): Promise<Java.Class>; // public native int java.lang.Object.hashCode() hashCodeA( cb: Callback<number>): void; hashCode(): number; hashCodeP(): Promise<number>; // public int java.lang.String.indexOf(java.lang.String,int) indexOfA(arg0: string_t, arg1: integer_t, cb: Callback<number>): void; indexOf(arg0: string_t, arg1: integer_t): number; indexOfP(arg0: string_t, arg1: integer_t): Promise<number>; // public int java.lang.String.indexOf(int,int) indexOfA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; indexOf(arg0: integer_t, arg1: integer_t): number; indexOfP(arg0: integer_t, arg1: integer_t): Promise<number>; // public int java.lang.String.indexOf(java.lang.String) indexOfA(arg0: string_t, cb: Callback<number>): void; indexOf(arg0: string_t): number; indexOfP(arg0: string_t): Promise<number>; // public int java.lang.String.indexOf(int) indexOfA(arg0: integer_t, cb: Callback<number>): void; indexOf(arg0: integer_t): number; indexOfP(arg0: integer_t): Promise<number>; // public native java.lang.String java.lang.String.intern() internA( cb: Callback<string>): void; intern(): string; internP(): Promise<string>; // public boolean java.lang.String.isEmpty() isEmptyA( cb: Callback<boolean>): void; isEmpty(): boolean; isEmptyP(): Promise<boolean>; // public int java.lang.String.lastIndexOf(java.lang.String,int) lastIndexOfA(arg0: string_t, arg1: integer_t, cb: Callback<number>): void; lastIndexOf(arg0: string_t, arg1: integer_t): number; lastIndexOfP(arg0: string_t, arg1: integer_t): Promise<number>; // public int java.lang.String.lastIndexOf(int,int) lastIndexOfA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; lastIndexOf(arg0: integer_t, arg1: integer_t): number; lastIndexOfP(arg0: integer_t, arg1: integer_t): Promise<number>; // public int java.lang.String.lastIndexOf(java.lang.String) lastIndexOfA(arg0: string_t, cb: Callback<number>): void; lastIndexOf(arg0: string_t): number; lastIndexOfP(arg0: string_t): Promise<number>; // public int java.lang.String.lastIndexOf(int) lastIndexOfA(arg0: integer_t, cb: Callback<number>): void; lastIndexOf(arg0: integer_t): number; lastIndexOfP(arg0: integer_t): Promise<number>; // public int java.lang.String.length() lengthA( cb: Callback<number>): void; length(): number; lengthP(): Promise<number>; // public boolean java.lang.String.matches(java.lang.String) matchesA(arg0: string_t, cb: Callback<boolean>): void; matches(arg0: string_t): boolean; matchesP(arg0: string_t): Promise<boolean>; // public final native void java.lang.Object.notify() notifyA( cb: Callback<void>): void; notify(): void; notifyP(): Promise<void>; // public final native void java.lang.Object.notifyAll() notifyAllA( cb: Callback<void>): void; notifyAll(): void; notifyAllP(): Promise<void>; // public int java.lang.String.offsetByCodePoints(int,int) offsetByCodePointsA(arg0: integer_t, arg1: integer_t, cb: Callback<number>): void; offsetByCodePoints(arg0: integer_t, arg1: integer_t): number; offsetByCodePointsP(arg0: integer_t, arg1: integer_t): Promise<number>; // public boolean java.lang.String.regionMatches(boolean,int,java.lang.String,int,int) regionMatchesA(arg0: boolean_t, arg1: integer_t, arg2: string_t, arg3: integer_t, arg4: integer_t, cb: Callback<boolean>): void; regionMatches(arg0: boolean_t, arg1: integer_t, arg2: string_t, arg3: integer_t, arg4: integer_t): boolean; regionMatchesP(arg0: boolean_t, arg1: integer_t, arg2: string_t, arg3: integer_t, arg4: integer_t): Promise<boolean>; // public boolean java.lang.String.regionMatches(int,java.lang.String,int,int) regionMatchesA(arg0: integer_t, arg1: string_t, arg2: integer_t, arg3: integer_t, cb: Callback<boolean>): void; regionMatches(arg0: integer_t, arg1: string_t, arg2: integer_t, arg3: integer_t): boolean; regionMatchesP(arg0: integer_t, arg1: string_t, arg2: integer_t, arg3: integer_t): Promise<boolean>; // public java.lang.String java.lang.String.replace(java.lang.CharSequence,java.lang.CharSequence) replaceA(arg0: object_t, arg1: object_t, cb: Callback<string>): void; replace(arg0: object_t, arg1: object_t): string; replaceP(arg0: object_t, arg1: object_t): Promise<string>; // public java.lang.String java.lang.String.replace(char,char) replaceA(arg0: object_t, arg1: object_t, cb: Callback<string>): void; replace(arg0: object_t, arg1: object_t): string; replaceP(arg0: object_t, arg1: object_t): Promise<string>; // public java.lang.String java.lang.String.replaceAll(java.lang.String,java.lang.String) replaceAllA(arg0: string_t, arg1: string_t, cb: Callback<string>): void; replaceAll(arg0: string_t, arg1: string_t): string; replaceAllP(arg0: string_t, arg1: string_t): Promise<string>; // public java.lang.String java.lang.String.replaceFirst(java.lang.String,java.lang.String) replaceFirstA(arg0: string_t, arg1: string_t, cb: Callback<string>): void; replaceFirst(arg0: string_t, arg1: string_t): string; replaceFirstP(arg0: string_t, arg1: string_t): Promise<string>; // public java.lang.String[] java.lang.String.split(java.lang.String,int) splitA(arg0: string_t, arg1: integer_t, cb: Callback<string[]>): void; split(arg0: string_t, arg1: integer_t): string[]; splitP(arg0: string_t, arg1: integer_t): Promise<string[]>; // public java.lang.String[] java.lang.String.split(java.lang.String) splitA(arg0: string_t, cb: Callback<string[]>): void; split(arg0: string_t): string[]; splitP(arg0: string_t): Promise<string[]>; // public boolean java.lang.String.startsWith(java.lang.String,int) startsWithA(arg0: string_t, arg1: integer_t, cb: Callback<boolean>): void; startsWith(arg0: string_t, arg1: integer_t): boolean; startsWithP(arg0: string_t, arg1: integer_t): Promise<boolean>; // public boolean java.lang.String.startsWith(java.lang.String) startsWithA(arg0: string_t, cb: Callback<boolean>): void; startsWith(arg0: string_t): boolean; startsWithP(arg0: string_t): Promise<boolean>; // public java.lang.CharSequence java.lang.String.subSequence(int,int) subSequenceA(arg0: integer_t, arg1: integer_t, cb: Callback<object_t>): void; subSequence(arg0: integer_t, arg1: integer_t): object_t; subSequenceP(arg0: integer_t, arg1: integer_t): Promise<object_t>; // public java.lang.String java.lang.String.substring(int,int) substringA(arg0: integer_t, arg1: integer_t, cb: Callback<string>): void; substring(arg0: integer_t, arg1: integer_t): string; substringP(arg0: integer_t, arg1: integer_t): Promise<string>; // public java.lang.String java.lang.String.substring(int) substringA(arg0: integer_t, cb: Callback<string>): void; substring(arg0: integer_t): string; substringP(arg0: integer_t): Promise<string>; // public char[] java.lang.String.toCharArray() toCharArrayA( cb: Callback<object_t[]>): void; toCharArray(): object_t[]; toCharArrayP(): Promise<object_t[]>; // public java.lang.String java.lang.String.toLowerCase(java.util.Locale) toLowerCaseA(arg0: object_t, cb: Callback<string>): void; toLowerCase(arg0: object_t): string; toLowerCaseP(arg0: object_t): Promise<string>; // public java.lang.String java.lang.String.toLowerCase() toLowerCaseA( cb: Callback<string>): void; toLowerCase(): string; toLowerCaseP(): Promise<string>; // public java.lang.String java.lang.Object.toString() toStringA( cb: Callback<string>): void; toString(): string; toStringP(): Promise<string>; // public java.lang.String java.lang.String.toUpperCase(java.util.Locale) toUpperCaseA(arg0: object_t, cb: Callback<string>): void; toUpperCase(arg0: object_t): string; toUpperCaseP(arg0: object_t): Promise<string>; // public java.lang.String java.lang.String.toUpperCase() toUpperCaseA( cb: Callback<string>): void; toUpperCase(): string; toUpperCaseP(): Promise<string>; // public java.lang.String java.lang.String.trim() trimA( cb: Callback<string>): void; trim(): string; trimP(): Promise<string>; // public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException waitA(arg0: object_t, arg1: integer_t, cb: Callback<void>): void; wait(arg0: object_t, arg1: integer_t): void; waitP(arg0: object_t, arg1: integer_t): Promise<void>; // public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException waitA(arg0: object_t, cb: Callback<void>): void; wait(arg0: object_t): void; waitP(arg0: object_t): Promise<void>; // public final void java.lang.Object.wait() throws java.lang.InterruptedException waitA( cb: Callback<void>): void; wait(): void; waitP(): Promise<void>; } export module String { export interface Static { CASE_INSENSITIVE_ORDER: object_t; class: Java.Class; new (arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: object_t): java.lang.String; new (arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: string_t): java.lang.String; new (arg0: object_array_t, arg1: integer_t, arg2: integer_t, arg3: integer_t): java.lang.String; new (arg0: array_t<integer_t>, arg1: integer_t, arg2: integer_t): java.lang.String; new (arg0: object_array_t, arg1: integer_t, arg2: integer_t): java.lang.String; new (arg0: object_array_t, arg1: integer_t, arg2: integer_t): java.lang.String; new (arg0: object_array_t, arg1: object_t): java.lang.String; new (arg0: object_array_t, arg1: string_t): java.lang.String; new (arg0: object_array_t, arg1: integer_t): java.lang.String; new (arg0: object_t): java.lang.String; new (arg0: object_t): java.lang.String; new (arg0: string_t): java.lang.String; new (arg0: object_array_t): java.lang.String; new (arg0: object_array_t): java.lang.String; new (): java.lang.String; // public static java.lang.String java.lang.String.copyValueOf(char[],int,int) copyValueOfA(arg0: object_array_t, arg1: integer_t, arg2: integer_t, cb: Callback<string>): void; copyValueOf(arg0: object_array_t, arg1: integer_t, arg2: integer_t): string; copyValueOfP(arg0: object_array_t, arg1: integer_t, arg2: integer_t): Promise<string>; // public static java.lang.String java.lang.String.copyValueOf(char[]) copyValueOfA(arg0: object_array_t, cb: Callback<string>): void; copyValueOf(arg0: object_array_t): string; copyValueOfP(arg0: object_array_t): Promise<string>; // public static java.lang.String java.lang.String.format(java.util.Locale,java.lang.String,java.lang.Object...) formatA(arg0: object_t, arg1: string_t, arg2: object_array_t, cb: Callback<string>): void; format(arg0: object_t, arg1: string_t, ...arg2: object_t[]): string; format(arg0: object_t, arg1: string_t, arg2: object_array_t): string; formatP(arg0: object_t, arg1: string_t, ...arg2: object_t[]): Promise<string>; formatP(arg0: object_t, arg1: string_t, arg2: object_array_t): Promise<string>; // public static java.lang.String java.lang.String.format(java.lang.String,java.lang.Object...) formatA(arg0: string_t, arg1: object_array_t, cb: Callback<string>): void; format(arg0: string_t, ...arg1: object_t[]): string; format(arg0: string_t, arg1: object_array_t): string; formatP(arg0: string_t, ...arg1: object_t[]): Promise<string>; formatP(arg0: string_t, arg1: object_array_t): Promise<string>; // public static java.lang.String java.lang.String.join(java.lang.CharSequence,java.lang.CharSequence...) joinA(arg0: object_t, arg1: object_array_t, cb: Callback<string>): void; join(arg0: object_t, ...arg1: object_t[]): string; join(arg0: object_t, arg1: object_array_t): string; joinP(arg0: object_t, ...arg1: object_t[]): Promise<string>; joinP(arg0: object_t, arg1: object_array_t): Promise<string>; // public static java.lang.String java.lang.String.join(java.lang.CharSequence,java.lang.Iterable<? extends java.lang.CharSequence>) joinA(arg0: object_t, arg1: object_t, cb: Callback<string>): void; join(arg0: object_t, arg1: object_t): string; joinP(arg0: object_t, arg1: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(char[],int,int) valueOfA(arg0: object_array_t, arg1: integer_t, arg2: integer_t, cb: Callback<string>): void; valueOf(arg0: object_array_t, arg1: integer_t, arg2: integer_t): string; valueOfP(arg0: object_array_t, arg1: integer_t, arg2: integer_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(java.lang.Object) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(char[]) valueOfA(arg0: object_array_t, cb: Callback<string>): void; valueOf(arg0: object_array_t): string; valueOfP(arg0: object_array_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(boolean) valueOfA(arg0: boolean_t, cb: Callback<string>): void; valueOf(arg0: boolean_t): string; valueOfP(arg0: boolean_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(long) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(int) valueOfA(arg0: integer_t, cb: Callback<string>): void; valueOf(arg0: integer_t): string; valueOfP(arg0: integer_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(float) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(double) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; // public static java.lang.String java.lang.String.valueOf(char) valueOfA(arg0: object_t, cb: Callback<string>): void; valueOf(arg0: object_t): string; valueOfP(arg0: object_t): Promise<string>; } } } // #### `function smellsLikeJavaObject(e: any)` // Returns true if the obj 'smells' like a Java object. // This is a light-weight test that will return false when `e` is clearly not a Java object, // but it may have false positives. To be certain, use `isJavaObject(e)` or `instanceOf(e, classname)` instead. function smellsLikeJavaObject(e: any): boolean { return _.isObject(e) && !_.isArray(e) ; } // #### `function isJavaObject(e: any)` // Returns true if the obj is a Java object. // Useful for determining the runtime type of object_t returned by many java methods. export function isJavaObject(e: any): boolean { return smellsLikeJavaObject(e) && _java.instanceOf(e, 'java.lang.Object'); } } // module Java
the_stack
import { initializeAndWatchThemeColors } from './theme'; import { debounce } from "debounce"; import { ConfigSetting, IVsCodeApi } from '../../types'; declare function acquireVsCodeApi(): IVsCodeApi; (function () { const vscode = acquireVsCodeApi(); initializeAndWatchThemeColors(); const toast = document.getElementById("saved-config-toast"); const dirty = document.getElementById("dirty-config-toast"); // * TEST const oldState = vscode.getState(); let currentCount: number = (oldState && oldState.count) || 0; if (currentCount) { // Already opened! Get fresh and recent config! vscode.postMessage({ command: "getNewConfig" }); } currentCount = currentCount + 1; vscode.setState({ count: currentCount }); // * SETUP // Global variable config let frontConfig: { [key: string]: any } = {}; let vscodeConfig: { [key: string]: any } = {}; let vscodeFontConfig: { [key: string]: any } = {}; let frontFontConfig: { [key: string]: any } = {}; vscodeConfig = (window as any).leoConfig; // ! PRE SET BY leoSettingsWebview frontConfig = JSON.parse(JSON.stringify(vscodeConfig)); vscodeFontConfig = (window as any).fontConfig; // ! PRE SET BY leoSettingsWebview frontFontConfig = JSON.parse(JSON.stringify(vscodeFontConfig)); // Handle messages sent from the extension to the webview window.addEventListener("message", event => { const message = event.data; // The json data that the extension sent if (message.command) { switch (message.command) { case "test": console.log("got test message"); break; case "newConfig": vscodeConfig = message.config; frontConfig = JSON.parse(JSON.stringify(message.config)); setControls(); break; case "vscodeConfig": dirty!.className = dirty!.className.replace("show", ""); toast!.className = "show"; setTimeout(function () { toast!.className = toast!.className.replace("show", ""); }, 1500); vscodeConfig = message.config; // next changes will be confronted to those settings break; case "newFontConfig": vscodeFontConfig = message.config; frontFontConfig = JSON.parse(JSON.stringify(message.config)); setFontControls(); break; case "vscodeFontConfig": vscodeFontConfig = message.config; // next changes will be confronted to those settings break; case "newEditorPath": const w_element: HTMLElement | null = document.getElementById("leoEditorPath"); if (w_element) { (w_element as HTMLInputElement).value = message.editorPath; onInputChanged(w_element as HTMLInputElement); } break; default: console.log("got message: ", message.command); break; } } else { console.log('got object without command:', message); } }); function listenAll(selector: string, name: string, listener: EventListener) { const els = (document.querySelectorAll(selector) as unknown) as Element[]; for (const el of els) { el.addEventListener(name, listener, false); } } function chooseLeoEditorPath() { vscode.postMessage({ command: "chooseLeoEditorPath" }); } function onBind() { listenAll('input[type=checkbox][data-setting]', 'change', function (this: HTMLInputElement) { return onInputChecked(this); }); listenAll('input[type=text][data-setting], input:not([type])[data-setting]', 'blur', function ( this: HTMLInputElement ) { return onInputBlurred(this); }); listenAll('input[type=text][data-setting], input:not([type])[data-setting]', 'focus', function ( this: HTMLInputElement ) { return onInputFocused(this); }); listenAll('input[type=text][data-setting], input[type=number][data-setting]', 'input', function ( this: HTMLInputElement ) { return onInputChanged(this); }); listenAll('select[data-setting]', 'change', function (this: HTMLSelectElement) { return onDropdownChanged(this); }); listenAll('input[type=number][data-vscode]', 'input', function ( this: HTMLInputElement ) { return onVscodeInputChanged(this); }); } function onDropdownChanged(element: HTMLSelectElement) { if (element) { const w_value = element.options[element.selectedIndex].value; frontConfig[element.id] = w_value; } dirty!.className = "show"; applyChanges(); } function onInputChecked(element: HTMLInputElement) { frontConfig[element.id] = element.checked; setVisibility(frontConfig); dirty!.className = "show"; applyChanges(); } function onInputBlurred(element: HTMLInputElement) { // console.log('onInputBlurred', element); } function onInputFocused(element: HTMLInputElement) { // console.log('onInputFocused', element); } function onInputChanged(element: HTMLInputElement) { if (element.type === 'number' && Number(element.value) < Number(element.max) && Number(element.value) > Number(element.min)) { frontConfig[element.id] = Number(element.value); element.classList.remove("is-invalid"); } else if (element.type === 'number' && (Number(element.value) > Number(element.max) || Number(element.value) < Number(element.min))) { // make red element.classList.add("is-invalid"); } else if (element.type === 'text' && element.value.length <= element.maxLength) { frontConfig[element.id] = element.value; } dirty!.className = "show"; applyChanges(); } function onVscodeInputChanged(element: HTMLInputElement) { if (element.id === "zoomLevel") { frontFontConfig.zoomLevel = element.valueAsNumber; } if (element.id === "editorFontSize") { frontFontConfig.fontSize = element.valueAsNumber; } applyFontChanges(); } function setFontControls(): void { if (frontFontConfig.zoomLevel || frontFontConfig.zoomLevel === 0) { const w_element = document.getElementById("zoomLevel"); (w_element as HTMLInputElement).valueAsNumber = Number(frontFontConfig.zoomLevel); } else { console.log('Error : vscode font setting "zoomLevel" is missing'); } if (frontFontConfig.fontSize) { const w_element = document.getElementById("editorFontSize"); (w_element as HTMLInputElement).valueAsNumber = Number(frontFontConfig.fontSize); } else { console.log('Error : vscode font setting "fontSize" is missing'); } } function setControls(): void { // 1- Set leointeg's own configuration settings for (const key in frontConfig) { if (frontConfig.hasOwnProperty(key)) { const w_element = document.getElementById(key); if (w_element && w_element.getAttribute('type') === 'checkbox') { (w_element as HTMLInputElement).checked = frontConfig[key]; } else if (w_element) { (w_element as HTMLInputElement).value = frontConfig[key]; } else { console.log('ERROR : w_element', key, ' is ', w_element); } } } } function setVisibility(state: { [key: string]: string | boolean }) { for (const el of document.querySelectorAll<HTMLElement>('[data-visibility]')) { el.classList.toggle('hidden', !evaluateStateExpression(el.dataset.visibility!, state)); } } function parseStateExpression(expression: string): [string, string, string | boolean | undefined] { const [lhs, op, rhs] = expression.trim().split(/([=+!])/); return [lhs.trim(), op !== undefined ? op.trim() : '=', rhs !== undefined ? rhs.trim() : rhs]; } function evaluateStateExpression(expression: string, changes: { [key: string]: string | boolean }): boolean { let state = false; for (const expr of expression.trim().split('&')) { const [lhs, op, rhs] = parseStateExpression(expr); switch (op) { case '=': { // Equals let value = changes[lhs]; if (value === undefined) { value = getSettingValue(lhs) || false; } state = rhs !== undefined ? rhs === String(value) : Boolean(value); break; } case '!': { // Not equals let value = changes[lhs]; if (value === undefined) { value = getSettingValue(lhs) || false; } state = rhs !== undefined ? rhs !== String(value) : !value; break; } case '+': { // Contains if (rhs !== undefined) { const setting = getSettingValue(lhs); state = setting !== undefined ? setting.includes(rhs.toString()) : false; } break; } } if (!state) { break; } } return state; } function getSettingValue(p_setting: string): any { return frontConfig[p_setting]; } var applyChanges = debounce(function () { var w_changes: ConfigSetting[] = []; if (frontConfig) { for (var prop in frontConfig) { if (Object.prototype.hasOwnProperty.call(frontConfig, prop)) { // console.log(prop); if (frontConfig[prop] !== vscodeConfig[prop]) { w_changes.push({ code: prop, value: frontConfig[prop] }); } } } } if (w_changes.length) { // ok replace! vscodeConfig = frontConfig; frontConfig = JSON.parse(JSON.stringify(frontConfig)); vscode.postMessage({ command: "config", changes: w_changes }); } else { // Still have to remove 'modified' popup dirty!.className = dirty!.className.replace("show", ""); } }, 1500); var applyFontChanges = debounce(function () { vscode.postMessage({ command: "fontConfig", changes: frontFontConfig }); }, 800); // * START const w_button: HTMLElement | null = document.getElementById('chooseLeoEditorPath'); if (w_button) { w_button.onclick = chooseLeoEditorPath; } setControls(); setFontControls(); setVisibility(frontConfig); onBind(); })();
the_stack
import DisplayObject = etch.drawing.DisplayObject; import {IApp} from './IApp'; import IDisplayContext = etch.drawing.IDisplayContext; import Point = minerva.Point; import {unlockAudioContext, isIOS, hasAudioContextStarted} from './Core/Audio/Utils/Utils'; declare var App: IApp; export class Splash extends DisplayObject{ public XOffset: number; public YOffset: number; public LoadOffset: number; public ButtonOffset: number; private _Scale: number; private _Center: Point; private _Offset: Point; public IOSPause: boolean = false; IsAnimationFinished: boolean = false; IsTransitionFinished: boolean = false; AnimationFinished = new nullstone.Event<{}>(); _hasTouchMoved: boolean = false; Init(drawTo: IDisplayContext): void { super.Init(drawTo); } public Setup() { super.Setup(); this._Offset = new Point(0,0); this.XOffset = 0; this.YOffset = -1; this.LoadOffset = -1; this.ButtonOffset = -1; App.PointerInputManager.MouseDown.on((s: any, e: MouseEvent) => { this.MouseDown(e); }, this); App.PointerInputManager.TouchEnd.on((s: any, e: TouchEvent) => { this.TouchEnd(e); }, this); App.PointerInputManager.TouchMove.on((s: any, e: TouchEvent) => { this._hasTouchMoved = true; }, this); } //------------------------------------------------------------------------------------------- // DRAWING //------------------------------------------------------------------------------------------- public Draw() { super.Draw(); if (this.IsTransitionFinished) { return; } if (this.IsFirstFrame()){ this.TransitionIn(); } var colorful = false; var units = App.Unit; var ctx = this.Ctx; this._Scale = 100 * units; this.Ctx.globalAlpha = 1; // LOADING // if (App.IsLoadingComposition) { var dx = 0; var dy = (App.Height*(this.LoadOffset)); App.FillColor(this.Ctx,App.Palette[0]); this.Ctx.fillRect(dx,dy,App.Width,App.Height); var dx = (App.Width*0.5); var dy = (App.Height*0.5) + (App.Height*this.LoadOffset); App.FillColor(this.Ctx,App.Palette[App.ThemeManager.Txt]); this.Ctx.textAlign = "center"; this.Ctx.font = App.Metrics.TxtHeader; this.Ctx.fillText("LOADING SCENE",dx,dy + (26 * units)); // todo: use l10n //App.AnimationsLayer.Spin(); App.AnimationsLayer.DrawSprite(this.Ctx,'loading',dx, dy - (16 * units),16,true); } //TODO use blocksprites with multiplier argument this._Offset = new Point(0,1); App.FillRGBA(this.Ctx,10,10,10,1); this.CenterRect(); // Convolution this._Center = new Point(-0.5,-0.5); this._Offset = new Point(0,0); App.FillColor(this.Ctx,App.Palette[3]); if (!colorful) {App.FillColor(this.Ctx,App.Palette[2]);} this.CenterRect(); this.Ctx.beginPath(); App.FillColor(this.Ctx,App.Palette[8]); this.DrawMoveTo(-1,-1); this.DrawLineTo(1,-1); this.DrawLineTo(2,0); this.DrawLineTo(0,2); this.DrawLineTo(-1,1); this.Ctx.closePath(); this.Ctx.fill(); this.Ctx.beginPath(); App.FillColor(this.Ctx,App.Palette[4]); this.DrawMoveTo(-1,-1); this.DrawLineTo(0,0); this.DrawLineTo(0,2); this.DrawLineTo(-1,1); this.Ctx.closePath(); this.Ctx.fill(); this.Ctx.beginPath(); App.FillColor(this.Ctx,App.Palette[6]); this.DrawMoveTo(0,0); this.DrawLineTo(1,0); this.DrawLineTo(0,1); this.Ctx.closePath(); this.Ctx.fill(); // gain this._Center = new Point(-0.5,0); this._Offset = new Point(-1,0); App.FillColor(this.Ctx,App.Palette[4]); if (!colorful) {App.FillColor(this.Ctx,App.Palette[0]);} this.CenterRect(); this.Ctx.beginPath(); App.FillColor(this.Ctx,App.Palette[5]); this.DrawMoveTo(-1,0); this.DrawLineTo(0,-1); this.DrawLineTo(2,1); this.DrawLineTo(0,1); this.Ctx.closePath(); this.Ctx.fill(); this.Ctx.beginPath(); App.FillColor(this.Ctx,App.Palette[3]); this.DrawMoveTo(-1,0); this.DrawLineTo(0,0); this.DrawLineTo(1,1); this.DrawLineTo(0,1); this.Ctx.closePath(); this.Ctx.fill(); // noise this._Center = new Point(0,-0.5); this._Offset = new Point(-1,-1); App.FillColor(this.Ctx,App.Palette[5]); if (!colorful) {App.FillColor(this.Ctx,App.Palette[2]);} this.CenterRect(); this.Ctx.beginPath(); App.FillColor(this.Ctx,App.Palette[4]); this.DrawMoveTo(-1,0); this.DrawLineTo(0,-1); this.DrawLineTo(1,-1); this.DrawLineTo(1,0); this.DrawLineTo(-1,2); this.Ctx.closePath(); this.Ctx.fill(); this.Ctx.beginPath(); App.FillColor(this.Ctx,App.Palette[8]); this.DrawMoveTo(-1,0); this.DrawLineTo(0,-1); this.DrawLineTo(1,-1); this.DrawLineTo(0,0); this.Ctx.closePath(); this.Ctx.fill(); // distortion this._Center = new Point(0,-0.5); this._Offset = new Point(0,-1); App.FillColor(this.Ctx,App.Palette[6]); if (!colorful) {App.FillColor(this.Ctx,App.Palette[0]);} this.CenterRect(); this.Ctx.beginPath(); App.FillColor(this.Ctx,App.Palette[7]); this.DrawMoveTo(-1,-1); this.DrawLineTo(1,-1); this.DrawLineTo(1,0); this.DrawLineTo(-1,2); this.Ctx.closePath(); this.Ctx.fill(); this.Ctx.beginPath(); App.FillColor(this.Ctx,App.Palette[9]); this.DrawLineTo(-1,-1); this.DrawLineTo(0,-1); this.DrawLineTo(0,0); this.DrawLineTo(-1,1); this.Ctx.closePath(); this.Ctx.fill(); this._Center = new Point(0,0); this._Offset = new Point(1,-1); App.FillColor(this.Ctx,App.Palette[2]); this.CenterRect(); var dx = (App.Width*0.5) + (this._Center.x*this._Scale) + (App.Width*(this._Offset.x+this.XOffset)); var dy = (App.Height*0.5) + (this._Center.y*this._Scale) + (App.Height*(this._Offset.y+this.YOffset)); var headerType = 100*units; App.FillColor(this.Ctx,App.Palette[App.ThemeManager.Txt]); this.Ctx.textAlign = "center"; this.Ctx.font = "200 " + headerType + "px Dosis"; this.Ctx.fillText("BLOKDUST",dx,dy + (headerType * 0.38)); // IOS BUTTON // var by = App.Height*this.ButtonOffset; App.FillColor(this.Ctx,App.Palette[0]); this.Ctx.fillRect(0,by,App.Width,App.Height); App.FillColor(this.Ctx,App.Palette[7]); ctx.beginPath(); ctx.moveTo((App.Width*0.5) - (this._Scale*0.5),by + (App.Height*0.5) - (this._Scale)); ctx.lineTo((App.Width*0.5) - (this._Scale*0.5),by + (App.Height*0.5) + (this._Scale)); ctx.lineTo((App.Width*0.5) + (this._Scale*0.5),by + (App.Height*0.5)); ctx.fill(); // CHROME RECOMMENDED // var chY = (this.LoadOffset * App.Height); App.FillColor(ctx,App.Palette[App.ThemeManager.Txt]); App.StrokeColor(ctx,App.Palette[App.ThemeManager.Txt]); ctx.font = App.Metrics.TxtLarge; ctx.textAlign = "center"; ctx.fillText('Chrome Recommended', App.Width*0.5, chY + this.DrawTo.Height - (20 * units)); ctx.lineWidth = 2; ctx.beginPath(); ctx.moveTo((App.Width*0.5) - (60*units), chY + this.DrawTo.Height - (27 * units)); ctx.lineTo((App.Width*0.5) - (63.89*units), chY + this.DrawTo.Height - (20 * units)); ctx.lineTo((App.Width*0.5) - (56.11*units), chY + this.DrawTo.Height - (20 * units)); ctx.closePath(); ctx.stroke(); } DrawMoveTo(x, y) { var scale = this._Scale; var dx = (App.Width*0.5) + (this._Center.x*scale) + (App.Width*(this._Offset.x+this.XOffset)); var dy = (App.Height*0.5) + (this._Center.y*scale) + (App.Height*(this._Offset.y+this.YOffset)); this.Ctx.moveTo(dx + (x*scale),dy + (y*scale)); } DrawLineTo(x, y) { var scale = this._Scale; var dx = (App.Width*0.5) + (this._Center.x*scale) + (App.Width*(this._Offset.x+this.XOffset)); var dy = (App.Height*0.5) + (this._Center.y*scale) + (App.Height*(this._Offset.y+this.YOffset)); this.Ctx.lineTo(dx + (x*scale),dy + (y*scale)); } CenterRect() { var dx = (App.Width*(this._Offset.x+this.XOffset)); var dy = (App.Height*(this._Offset.y+this.YOffset)); this.Ctx.fillRect(dx,dy,App.Width,App.Height); } //------------------------------------------------------------------------------------------- // TWEEN //------------------------------------------------------------------------------------------- DelayTo(panel,destination,t,delay,v,s){ var offsetTween = new window.TWEEN.Tween({x: s}); offsetTween.to({x: destination}, t); offsetTween.onUpdate(function () { panel[""+v] = this.x; }); offsetTween.easing(window.TWEEN.Easing.Exponential.InOut); offsetTween.delay(delay); offsetTween.start(this.LastVisualTick); } TransitionIn() { var initDelay = 300; var tweenLength = 250; var viewLength = 350; this.DelayTo(this,0,tweenLength,initDelay,'LoadOffset',-1); // iOS needs a start button // if (isIOS()) { // SHOW BUTTON // this.DelayTo(this,0,tweenLength,initDelay,'ButtonOffset',-1); this.IOSPause = true; } else { // DONT SHOW BUTTON // this.Animate(initDelay,tweenLength,viewLength); } } Animate(initDelay, tweenLength, viewLength) { this.DelayTo(this,0,tweenLength,initDelay,'YOffset',-1); this.DelayTo(this,1,tweenLength,viewLength + tweenLength + initDelay,'XOffset',0); this.DelayTo(this,1,tweenLength,(viewLength*2) + (tweenLength*2) + initDelay,'YOffset',0); this.DelayTo(this,0,tweenLength,(viewLength*3) + (tweenLength*3) + initDelay,'XOffset',1); this.DelayTo(this,-1,tweenLength,(viewLength*4) + (tweenLength*4) + initDelay,'XOffset',0); this.DelayTo(this,2,tweenLength + 200,(viewLength*5) + (tweenLength*5) + initDelay + 200,'YOffset',1); // when pre-roll is finished setTimeout(() => { this.IsAnimationFinished = true; this.AnimationFinished.raise(this, null); },(viewLength*5) + (tweenLength*5) + initDelay + 200); } TransitionOut() { this.DelayTo(this,1,450,300,'LoadOffset',0); // when pre-roll is finished setTimeout(() => { this.IsTransitionFinished = true; },800); } //------------------------------------------------------------------------------------------- // INTERACTION //------------------------------------------------------------------------------------------- MouseDown(e: MouseEvent): void { if (this.IOSPause) { this.StartButtonPressed(); } } TouchEnd(e: any){ // iOS audio wont initialize if there's a touchMove event if (this.IOSPause && !this._hasTouchMoved) { this.StartButtonPressed(); } this._hasTouchMoved = false; } StartButtonPressed() { // Check to see if audio context has started if (hasAudioContextStarted(App.Audio.ctx)){ // START APP // this.StartAppAfterPause(); } else { // UNLOCK AUDIO CONTEXT // unlockAudioContext(App.Audio.ctx, () => { // START APP // this.StartAppAfterPause(); }); } } StartAppAfterPause() { // ANIM // this.IOSPause = false; var initDelay = 300; var tweenLength = 250; var viewLength = 350; this.DelayTo(this,1,tweenLength,initDelay,'ButtonOffset',0); this.Animate(initDelay,tweenLength,viewLength); if (!App.IsLoadingComposition) { App.MainScene.Begin(); } } }
the_stack
import { Observable, combineLatest, Subject } from 'rxjs'; import { switchMap, map, filter, shareReplay, startWith } from 'rxjs/operators'; import { LogicInterface } from '../../../../src/app/logic-interface.interface'; import { Message, UserWithLastMessage, User, AddMessage, UserPair, Search } from '../../../../src/shared/types'; import { DataStore } from '@aws-amplify/datastore'; import { User as AWSUser, Message as AWSMessage } from '../models'; import { unixTimestampToGraphql, graphQLTimestampToUnix } from 'projects/rxdb-pouchdb/src/app/shared'; import { sortByNewestFirst, sortMessagesByDateNewestFirst, doesMessageMapUserPair } from 'src/shared/util-server'; export class Logic implements LogicInterface { public userChanged$: Observable<any>; public messageChanged$: Observable<any>; constructor() { const userChangedSubject$ = new Subject(); DataStore.observe(AWSUser as any).subscribe(user => { userChangedSubject$.next(user); }); this.userChanged$ = userChangedSubject$.asObservable().pipe( startWith(1), shareReplay() ); const messageChangedSubject$ = new Subject(); DataStore.observe(AWSMessage as any).subscribe(user => { messageChangedSubject$.next(user); }); this.messageChanged$ = messageChangedSubject$.asObservable().pipe( startWith(1), shareReplay() ); } getUserByName(userName$: Observable<string>): Observable<User> { return userName$.pipe( switchMap(userName => { return this.userChanged$.pipe( map(() => userName) ); }), switchMap(async (userName) => { const docs: AWSUser[] = await DataStore.query( AWSUser as any, u => (u.userName as any)('eq', userName), { limit: 1 } ); const firstDoc = docs[0]; if (!firstDoc) { return null as any; } return awsUserToNormal(firstDoc); }), filter(doc => !!doc) ); } getSearchResults(search$: Observable<Search>): Observable<UserWithLastMessage[]> { return search$.pipe( switchMap(search => { return this.messageChanged$.pipe( map(() => search) ); }), switchMap(async (search) => { const docs: AWSMessage[] = await DataStore.query( AWSMessage as any, m => m.text('contains', search.searchTerm) ); const messages = docs.map(m => awsMessageToNormal(m)); return { search, messages }; }), switchMap((searchWithMessages) => { const search = searchWithMessages.search; const messages: Message[] = searchWithMessages.messages; return Promise.all( messages.map(async (message) => { let otherUser = message.sender; if (otherUser === search.ownUser.id) { otherUser = message.reciever; } const userDocs: AWSUser[] = await DataStore.query( AWSUser as any, u => u.userName('eq', otherUser), { limit: 1 } ); const user = awsUserToNormal(userDocs[0]); return { user, message }; }) ); }) ); } getUsersWithLastMessages(ownUser$: Observable<User>): Observable<UserWithLastMessage[]> { const usersNotOwn$: Observable<User[]> = ownUser$.pipe( switchMap( ownUser => this.userChanged$.pipe( map(() => ownUser) ) ), switchMap(async (ownUser) => { const docs: AWSUser[] = await DataStore.query( AWSUser as any, u => u.userName('ne', ownUser.id) ); return docs; }), map(docs => docs.map(doc => awsUserToNormal(doc))), shareReplay(1) ); const usersWithLastMessage$: Observable< Observable<UserWithLastMessage>[] > = combineLatest([ ownUser$, usersNotOwn$ ]).pipe( map(([ownUser, usersNotOwn]) => { return usersNotOwn.map(user => { const pair: UserPair = { user1: ownUser, user2: user }; const ret2 = this.getLastMessageOfUserPair(pair).pipe( map(message => { return { user, message: message ? message : undefined }; }), shareReplay(1) ); return ret2; }); }) ); const ret: Observable<UserWithLastMessage[]> = usersWithLastMessage$.pipe( switchMap(usersWithLastMessage => combineLatest(usersWithLastMessage)), map(usersWithLastMessage => sortByNewestFirst(usersWithLastMessage)) ); return ret; } private getLastMessageOfUserPair( userPair: UserPair ): Observable<Message | null> { return this.messageChanged$.pipe( filter(messageEvent => { if (!messageEvent.element) { return true; } const message: Message = messageEvent.element; return doesMessageMapUserPair( userPair.user1.id, userPair.user2.id, message ); }), switchMap(async () => { /** * TODO fix sorting * @link https://github.com/aws-amplify/amplify-js/issues/4652 */ const docs1: AWSMessage[] = await DataStore.query( AWSMessage as any, m => m .sender('eq', userPair.user1.id) .reciever('eq', userPair.user2.id) ); const docs2: AWSMessage[] = await DataStore.query( AWSMessage as any, m => m .reciever('eq', userPair.user1.id) .sender('eq', userPair.user2.id) ); const messages = docs1 .concat(docs2) .map(m => awsMessageToNormal(m)); const newest = sortMessagesByDateNewestFirst(messages); return newest[0]; }) ); } public getMessagesForUserPair( userPair$: Observable<UserPair> ): Observable<Message[]> { return userPair$.pipe( switchMap(userPair => { return this.messageChanged$.pipe( filter(messageEvent => { if (!messageEvent.element) { return true; } const message: Message = messageEvent.element; return doesMessageMapUserPair( userPair.user1.id, userPair.user2.id, message ); }), map(() => userPair) ); }), switchMap(async (userPair) => { const docs1: AWSMessage[] = await DataStore.query( AWSMessage as any, m => m.sender('eq', userPair.user1.id).reciever('eq', userPair.user2.id) ); const docs2: AWSMessage[] = await DataStore.query( AWSMessage as any, m => m.reciever('eq', userPair.user1.id).sender('eq', userPair.user2.id) ); const all: AWSMessage[] = docs1.concat(docs2); const messages = all.map(m => awsMessageToNormal(m)); const sorted = sortMessagesByDateNewestFirst(messages).reverse(); return sorted; }) ); } async addMessage(message: AddMessage): Promise<any> { await DataStore.save( new AWSMessage({ read: false, createdAt: unixTimestampToGraphql(new Date().getTime()), reciever: message.reciever, sender: message.sender, text: message.message.text }) ); } async addUser(user: User): Promise<any> { await DataStore.save( new AWSUser({ userName: user.id, createdAt: unixTimestampToGraphql( user.createdAt ) }) ); }; async hasData(): Promise<boolean> { const userDocs: AWSUser[] = await DataStore.query( AWSUser as any, u => (u.createdAt as any)('gt', 0), { limit: 1 } ); return userDocs.length > 0; } } export function awsUserToNormal(u: AWSUser): User { if (!u) { throw new Error('user missing'); } return { id: u.userName, createdAt: graphQLTimestampToUnix(u.createdAt) }; } export function awsMessageToNormal(m: AWSMessage): Message { if (!m) { throw new Error('message missing'); } return { id: m.id, createdAt: graphQLTimestampToUnix(m.createdAt), read: m.read, reciever: m.reciever, sender: m.sender, text: m.text }; }
the_stack
/// <reference path="SpriterFile.ts" /> module Spriter { export class SpriterXml extends SpriterFile { private _xml: XMLDocument; // ------------------------------------------------------------------------- constructor(xmlData: XMLDocument, options?: IFileOptions) { super(options); this._xml = xmlData; var minimized = xmlData.documentElement.hasAttribute("min"); this.setMinimized(minimized); } // ------------------------------------------------------------------------- public getType(): eFileType { return eFileType.XML; } // ------------------------------------------------------------------------- private parseInt(element: Element, attributeName: string, defaultValue: number = 0): number { var value = element.getAttribute(this.translateAttributeName(attributeName)); return value !== null ? parseInt(value) : defaultValue; } // ------------------------------------------------------------------------- protected parseFloat(element: Element, attributeName: string, defaultValue: number = 0): number { var value = element.getAttribute(this.translateAttributeName(attributeName)); return value !== null ? parseFloat(value) : defaultValue; } // ------------------------------------------------------------------------- protected parseString(element: Element, attributeName: string, defaultValue: string = ""): string { var value = element.getAttribute(this.translateAttributeName(attributeName)); return value !== null ? value : defaultValue; } // ------------------------------------------------------------------------- public getNodes(nodeName: string): ISpriterNodeList { this.setMinDefsToElementName(nodeName); var translatedName = this.translateElementName(nodeName); return new NodeListXml(this, this._xml.documentElement.getElementsByTagName(translatedName)); } // ------------------------------------------------------------------------- public getNodesForElement(element: Element, nodeName: string): ISpriterNodeList { this.setMinDefsToElementName(nodeName); var translatedName = this.translateElementName(nodeName); return new NodeListXml(this, element.getElementsByTagName(translatedName)); } // ------------------------------------------------------------------------- public getFolder(element: Element): Folder { return new Folder( this.parseInt(element, "id"), this.parseString(element, "name")); } // ------------------------------------------------------------------------- public getFile(element: Element): File { if (element.hasAttribute("type") && element.getAttribute("type") === "sound") { return null; } return new File( this.parseInt(element, "id"), this.getFileName(this.parseString(element, "name")), this.parseFloat(element, "pivot_x"), 1 - this.parseFloat(element, "pivot_y")); } // ------------------------------------------------------------------------- public getTag(element: Element): Item { return new Item( this.parseInt(element, "id"), this.parseString(element, "name")); } // ------------------------------------------------------------------------- public getEntity(element: Element): Entity { return new Entity( this.parseInt(element, "id"), this.parseString(element, "name")); } // ------------------------------------------------------------------------- public getObjectInfo(element: Element, index: number): ObjectInfo { return new ObjectInfo( index, this.parseString(element, "name"), Types.getObjectTypeForName(this.parseString(element, "type")), this.parseFloat(element, "w"), this.parseFloat(element, "h"), this.parseFloat(element, "pivot_x"), this.parseFloat(element, "pivot_y")); } // ------------------------------------------------------------------------- public getCharMap(element: Element): CharMap { return new CharMap( this.parseInt(element, "id"), this.parseString(element, "name")); } // ------------------------------------------------------------------------- public getCharMapEntry(element: Element, charMap: CharMap, spriter: Spriter): void { var sourceName = spriter.getFolderById(this.parseInt(element, "folder")). getFileById(this.parseInt(element, "file")).name; var target: File = null; if (element.hasAttribute("target_folder") && element.hasAttribute("target_file")) { target = spriter.getFolderById(this.parseInt(element, "target_folder")). getFileById(this.parseInt(element, "target_file")); } charMap.put(sourceName, target); } // ------------------------------------------------------------------------- public getVariable(element: Element): Variable { var type = Types.getVariableTypeForName(this.parseString(element, "type")); return new Variable( this.parseInt(element, "id"), this.parseString(element, "name"), type, (type === eVariableType.STRING) ? this.parseString(element, "default") : this.parseFloat(element, "default", 0) ); } // ------------------------------------------------------------------------- public getAnimation(element: Element): Animation { return new Animation( this.parseInt(element, "id"), this.parseString(element, "name"), this.parseFloat(element, "length"), this.parseString(element, "looping", "true") === "true" ? eAnimationLooping.LOOPING : eAnimationLooping.NO_LOOPING ); } // ------------------------------------------------------------------------- public getMainlineKey(element: Element): KeyMainline { return new KeyMainline( this.parseInt(element, "id"), this.parseFloat(element, "time") ); } // ------------------------------------------------------------------------- public getRef(element: Element): Ref { return new Ref( this.parseInt(element, "id"), this.parseInt(element, "parent", -1), this.parseInt(element, "timeline"), this.parseInt(element, "key"), this.parseInt(element, "z_index")); } // ------------------------------------------------------------------------- public getTimeline(element: Element): Timeline { return new Timeline( this.parseInt(element, "id"), this.parseString(element, "name"), Types.getObjectTypeForName(this.parseString(element, "object_type", "sprite")), this.parseInt(element, "obj", -1)); } // ------------------------------------------------------------------------- public getBaseline(element: Element): Baseline { return new Baseline( this.parseInt(element, "id"), this.parseString(element, "name", null)); } // ------------------------------------------------------------------------- public getVarline(element: Element): Varline { return new Varline( this.parseInt(element, "id"), this.parseInt(element, "def")); } // ------------------------------------------------------------------------- public getKey(element: Element): Key { return new Key( this.parseInt(element, "id"), this.parseInt(element, "time")); } // ------------------------------------------------------------------------- public getTagKey(element: Element): KeyTag { return new KeyTag( this.parseInt(element, "id"), this.parseInt(element, "time")); } // ------------------------------------------------------------------------- public getVariableKey(element: Element, type: eVariableType): KeyVariable { return new KeyVariable( this.parseInt(element, "id"), this.parseInt(element, "time"), (type === eVariableType.STRING) ? this.parseString(element, "val") : this.parseFloat(element, "val") ); } // ------------------------------------------------------------------------- public getTimelineKey(element: Element, index: number, spriter: Spriter): KeyTimeline { var time = this.parseInt(element, "time"); var spin = this.parseInt(element, "spin", 1); // curve and params var curve = this.parseString(element, "curve_type", "linear"); var c1 = this.parseFloat(element, "c1", 0); var c2 = this.parseFloat(element, "c2", 0); var c3 = this.parseFloat(element, "c3", 0); var c4 = this.parseFloat(element, "c4", 0); // sprite or bone key? var boneTag = this.translateChildElementName("bone"); var objectTag = this.translateChildElementName("object"); var key: KeyTimeline = null; var keyDataElm = <Element>(element.firstElementChild); var sprite: boolean = false; if (keyDataElm.tagName === boneTag) { key = new KeyBone(index, time, spin); this.setMinDefsToElementName("bone"); } else if (keyDataElm.tagName === objectTag) { this.setMinDefsToElementName("object"); key = new KeyObject(index, time, spin); sprite = true; } // other curve than linear? if (curve !== "linear") { key.setCurve(Types.getCurveTypeForName(curve), c1, c2, c3, c4); } // spatial info var info = key.info; info.x = this.parseFloat(keyDataElm, "x"); info.y = -this.parseFloat(keyDataElm, "y"); info.scaleX = this.parseFloat(keyDataElm, "scale_x", 1); info.scaleY = this.parseFloat(keyDataElm, "scale_y", 1); info.angle = 360 - this.parseFloat(keyDataElm, "angle"); info.alpha = this.parseFloat(keyDataElm, "a", 1); if (sprite) { // sprite specific - set file and folder var folderId = this.parseInt(keyDataElm, "folder"); var fileId = this.parseInt(keyDataElm, "file"); (<KeyObject>key).setFolderAndFile(folderId, fileId); // set pivot in spatial info different from default (based on pivot in file) var file = spriter.getFolderById(folderId).getFileById(fileId); info.pivotX = this.parseFloat(keyDataElm, "pivot_x", file.pivotX); // 1 - to flip Y, default anchor is already flipped, so it needs to be flipped back to avoid double flipping info.pivotY = 1 - this.parseFloat(keyDataElm, "pivot_y", 1 - file.pivotY); } this.popMinDefsStack(); return key; } // ------------------------------------------------------------------------- public getTagChange(element: Element): number { return this.parseInt(element, "t"); } } }
the_stack
import { awsResources as specification, awsResourceRefTypes as resourceRefOverride, } from './awsData'; import * as awsData from './awsData'; import clone = require('clone'); import CustomError = require('./util/CustomError'); const mergeOptions = require('merge-options'); export class NoSuchProperty extends CustomError { type: string; propertyName: string; constructor(type: string, propertyName: string) { super(`No such property ${propertyName} on ${type}`); CustomError.fixErrorInheritance(this, NoSuchProperty) this.type = type; this.propertyName = propertyName; } } export class NoSuchResourceType extends CustomError { resourceType: string; constructor(type: string) { super(`No such resource ${type}`); CustomError.fixErrorInheritance(this, NoSuchResourceType) } } export class NoSuchPropertyType extends CustomError { propertyType: string; constructor(type: string) { super(`No such property type ${type}`); CustomError.fixErrorInheritance(this, NoSuchPropertyType) } } export class NoSuchResourceTypeAttribute extends CustomError { resourceType: string; attributeName: string; constructor(type: string, attributeName: string) { super(`No such attribute ${attributeName} on ${type}`); CustomError.fixErrorInheritance(this, NoSuchResourceTypeAttribute) this.resourceType = type; this.attributeName = attributeName; } } /* * Returns the specification of a resource type * @param type An optionally parameterized resource type (e.g. `AWS::S3::Bucket<somethingCool>`) */ export function getResourceType(type: string): awsData.ResourceType { // destructure resource name let typeName = type, typeArgument = ''; if (isParameterizedTypeFormat(type)) { typeName = getParameterizedTypeName(type); //e.g. `AWS::S3::Bucket` typeArgument = getParameterizedTypeArgument(type); //e.g. `somethingCool` } // If the type starts with Custom::, it's a custom resource otherwise it's a normal resource type if(typeName.indexOf('Custom::') == 0){ // return the generic type if there's no such custom type defined if (!specification.ResourceTypes.hasOwnProperty(typeName)) { typeName = 'AWS::CloudFormation::CustomResource'; } } // acquire base resource type specification let spec = specification.ResourceTypes[typeName]; if (!spec){ throw new NoSuchResourceType(typeName); } // specialize parameterized type if (!!typeArgument && hasType(typeArgument)) { spec = mergeOptions(spec, getType(typeArgument)); } return spec as awsData.ResourceType; } export function getResourceTypeAttribute(type: string, attributeName: string): awsData.Attribute { const resourceAttributes = getResourceType(type).Attributes if (!resourceAttributes) { throw new NoSuchResourceTypeAttribute(type, attributeName); } const resourceAttribute = resourceAttributes[attributeName] if (!resourceAttribute) { throw new NoSuchResourceTypeAttribute(type, attributeName); } return resourceAttribute } /* * Returns the specification of a property types * @param type An optionally parameterized property type (e.g. `AWS::S3::Bucket<somethingCool>.BucketEncryption<somethingAwesome>`) */ function getPropertyType(type: string): awsData.ResourcePropertyType { // destructure property name let baseType, baseTypeName = '', baseTypeArgument = ''; baseType = baseTypeName = getPropertyTypeBaseName(type); //e.g. `AWS::S3::Bucket<somethingCool>` if (isParameterizedTypeFormat(baseType)) { baseTypeName = getParameterizedTypeName(baseType); //e.g. `AWS::S3::Bucket` baseTypeArgument = getParameterizedTypeArgument(baseType); //e.g. `somethingCool` } let propertyType, propertyTypeName = '', propertyTypeArgument = ''; propertyType = propertyTypeName = getPropertyTypePropertyName(type); //e.g. `BucketEncryption<somethingAwesome>` if (isParameterizedTypeFormat(propertyType)) { propertyTypeName = getParameterizedTypeName(propertyType); //e.g. `BucketEncryption` propertyTypeArgument = getParameterizedTypeArgument(propertyType); //e.g. `somethingAwesome` } // acquire base property type specification let basePropertyType = `${baseTypeName}.${propertyTypeName}`; let spec = specification.PropertyTypes[basePropertyType]; if (!spec) { throw new NoSuchPropertyType(basePropertyType); } // specialize parameterized type if (!!propertyTypeArgument && hasType(propertyTypeArgument)) { spec = mergeOptions(spec, getType(propertyTypeArgument)); } return spec as awsData.ResourcePropertyType; } /** * Get a Resource or Property type from the specification. */ export function getType(type: string): awsData.Type { if (isPropertyTypeFormat(type)) { return getPropertyType(type); } else { return getResourceType(type); } } /** * Returns an empty resource type specification */ export function makeResourceTypeSpec(): awsData.ResourceType { return clone(awsData.awsResourceTypeTemplate); } /** * Returns an empty property type specification */ export function makePropertyTypeSpec(): awsData.ResourcePropertyType { return clone(awsData.awsResourcePropertyTypeTemplate); } function getParameterizedTypeNameParts(type: any): any { if (isPropertyTypeFormat(type)) { type = getPropertyTypePropertyName(type); } let parts = []; let partsRe = /<.*>$/; if (RegExp(partsRe).test(type)) { parts = type.match(partsRe); } return parts; } /** * Returns if a given type name has type arguments. */ export function isParameterizedTypeFormat(type: string): boolean { if (getParameterizedTypeNameParts(type).length > 0) { return true; } return false; } /** * Get the argument of a parameterized type. */ export function getParameterizedTypeArgument(type: string): string { if (!isParameterizedTypeFormat(type)) { throw new Error(`Invalid parameterized type: ${type}`); } return getParameterizedTypeNameParts(type).shift().slice(1, -1) as string; } /** * Get the name of a parameterized type. */ export function getParameterizedTypeName(type: string): string { let typeArg = getParameterizedTypeArgument(type); return type.replace(`<${typeArg}>`, ''); } /** * Converts a generic type name to parameterized format */ export function parameterizeTypeFormat(type: string, parameter: string, allowSubParameterization: boolean = false): string { if (isParameterizedTypeFormat(type)) { if (allowSubParameterization) { let typeArg = getParameterizedTypeArgument(type); parameter = `${typeArg}<${parameter}>`; type = getParameterizedTypeName(type); } else { throw new Error(`Type is already parameterized: ${type}`); } } return `${type}<${parameter}>`; } /** * Strips type parameterization */ export function stripTypeParameters(input: string): string { let typeParamRe = /(<.*>(?=\.))|(<.*>$)/gm; input = input.replace(typeParamRe, ''); return input; } function getPropertyTypeNameParts(type: any): any { let parts = []; let partsRe = /^([^<>]*(?:<.*>)?)\.([^<>]*(?:<.*>)?)$/; if (RegExp(partsRe).test(type)) { parts = type.match(partsRe).slice(1); } return parts; } /** * Returns the base type name of a property type name */ export function getPropertyTypeBaseName(type: string): string { if (!isPropertyTypeFormat(type)) { throw new Error(`Invalid property type name: ${type}`); } return getPropertyTypeNameParts(type)[0] as string; } /** * Returns the property name of a property type name */ export function getPropertyTypePropertyName(type: string): string { if (!isPropertyTypeFormat(type)) { throw new Error(`Invalid property type name: ${type}`); } return getPropertyTypeNameParts(type)[1] as string; } export function isTypeFormat(type: string): boolean { return (type.indexOf('::') != -1); } export function isPropertyTypeFormat(type: string): boolean { return (getPropertyTypeNameParts(type).length > 0); } export function isResourceTypeFormat(type: string): boolean { return (isTypeFormat(type) && !isPropertyTypeFormat(type)); } export function rebaseTypeFormat(baseType: string, type: string): string { if (isPropertyTypeFormat(type)) { type = getPropertyTypePropertyName(type); } if (isParameterizedTypeFormat(type)) { let typeName = getParameterizedTypeName(type); let typeArgument = getParameterizedTypeArgument(type); // recurse on name typeName = rebaseTypeFormat(baseType, typeName); // recurse on argument typeArgument = rebaseTypeFormat(baseType, typeArgument); return parameterizeTypeFormat(typeName, typeArgument); } if (isPrimitiveType(type) || isAggregateType(type)) { return type; } return `${baseType}.${type}`; } export function isPrimitiveType(type: string) { if (isParameterizedTypeFormat(type)) { type = getParameterizedTypeName(type); } if (!!~awsData.awsPrimitiveTypes.indexOf(type)) { return true; } return false; } export function isAggregateType(type: string) { if (isParameterizedTypeFormat(type)) { type = getParameterizedTypeName(type); } if (!!~awsData.awsAggregateTypes.indexOf(type)) { return true; } return false; } export function getProperty(type: string, propertyName: string) { const spec = getType(type); // destructure parameterized property let propertyArgument: any; if (isParameterizedTypeFormat(propertyName)) { propertyArgument = getParameterizedTypeArgument(propertyName); propertyName = getParameterizedTypeName(propertyName); } // validate property let property = spec.Properties[propertyName]; if (!property) { throw new NoSuchProperty(type, propertyName); } // specialize parameterized property if (!!propertyArgument) { property = makeProperty(propertyArgument) as awsData.Property; } return property; } /** * Returns a specification based on a parameterized property type */ export function makeProperty(propertyType?: string): awsData.PropertyBase | awsData.Property { let property = clone(awsData.awsPropertyTemplate); if (!!propertyType) { let propertyTypeArgument = ''; if (isParameterizedTypeFormat(propertyType)) { propertyTypeArgument = getParameterizedTypeArgument(propertyType); } // make primitive type specification if (isPrimitiveType(propertyType)) { (<awsData.PrimitiveProperty>property)['PrimitiveType'] = propertyType as awsData.AWSPrimitiveType; // make list type specification } else if(propertyType.indexOf('List<') == 0) { (<awsData.ListProperty>property)['Type'] = 'List'; if (isPrimitiveType(propertyTypeArgument)) { (<awsData.ListProperty>property)['PrimitiveItemType'] = propertyTypeArgument as awsData.AWSPrimitiveType; } else { (<awsData.ListProperty>property)['ItemType'] = propertyTypeArgument; } // make map type specification } else if(propertyType.indexOf('Map<') == 0) { (<awsData.MapProperty>property)['Type'] = 'Map'; if (isPrimitiveType(propertyTypeArgument)) { (<awsData.MapProperty>property)['PrimitiveItemType'] = propertyTypeArgument as awsData.AWSPrimitiveType; } else { (<awsData.MapProperty>property)['ItemType'] = propertyTypeArgument; } // make complex type specification } else { (<awsData.ComplexProperty>property)['Type'] = propertyType; } } return property; } export function getRefOverride(resourceType: string){ return resourceRefOverride[resourceType] || null; } /** * Checks a ResourceType or PropertyType for the presence of a propertyName * @param parentPropertyType a ResourceType or PropertyType * @param propertyName name of the property to check against the specification */ export function isValidProperty(parentPropertyType: string, propertyName: string){ return getType(parentPropertyType).Properties.hasOwnProperty(propertyName); } /** * Checks the resource type and returns true if the propertyName is required. */ export function isRequiredProperty(parentPropertyType: string, propertyName: string){ return getProperty(parentPropertyType, propertyName).Required; } export function isArnProperty(propertyName: string){ // Check if the parentPropertyType exists return (propertyName.indexOf('Arn') != -1); } function isSinglePrimitivePropertyType(parentPropertyType: string, propertyName: string){ return Boolean(getProperty(parentPropertyType, propertyName).PrimitiveType); } export { isSinglePrimitivePropertyType as isPrimitiveProperty }; export function isAdditionalPropertiesEnabled(resourceType: string){ return getType(resourceType).AdditionalProperties === true; } export function isPropertyTypeList(type: string, propertyName: string) { const propertyType = getProperty(type, propertyName).Type; if (!!propertyType) { return propertyType.indexOf('List') == 0; } return false; } export function isPropertyTypeMap(type: string, propertyName: string) { const propertyType = getProperty(type, propertyName).Type; if (!!propertyType) { return propertyType.indexOf('Map') == 0; } return false; } function getPropertyTypeApi(baseType: string, propType: string, key: string) { const property = getProperty(propType, key); if (!property.Type) { return undefined } return baseType + '.' + property.Type; } export { getPropertyTypeApi as getPropertyType }; export function getItemType(baseType: string, propType: string, key: string) { const property = getProperty(propType, key); if (!property.ItemType) { return undefined; } else if (isAggregateType(property.ItemType)) { return property.ItemType; } else { return baseType + '.' + property.ItemType; } } export function hasPrimitiveItemType(type: string, propertyName: string) { return Boolean(getProperty(type, propertyName).PrimitiveItemType); } export function getPrimitiveItemType(type: string, key: string): awsData.AWSPrimitiveType | undefined { return getProperty(type, key).PrimitiveItemType; } export function getPrimitiveType(type: string, key: string): awsData.AWSPrimitiveType | undefined { return getProperty(type, key).PrimitiveType; } export function getRequiredProperties(type: string){ let spec = getType(type); let requiredProperties = []; for(let prop in spec['Properties']){ if(spec['Properties'][prop]!['Required'] === true){ requiredProperties.push(prop); } } return requiredProperties; } /** * Allows extending the AWS Resource Specification with custom definitions. */ export function extendSpecification(spec: any){ Object.assign(specification, mergeOptions(specification, spec)); } /** * Allows overriding definitions based on logical name. * Subsequent registrations DO overwrite prior ones. * //TODO: perhaps user defined overrides should take precedence? */ export function registerLogicalNameOverride(name: string, spec: any) { // determine type section let typeSection = 'ResourceTypes'; if (isPropertyTypeFormat(name)) { typeSection = 'PropertyTypes'; } // determine prior specification let oldSpec: any = {}; try { oldSpec = getType(name); } catch(e) {} // override extendSpecification({ [typeSection]: {[name]: mergeOptions(oldSpec, spec)} }); } /** * Allows overriding definitions based on type. * Subsequent registrations DO overwrite prior ones. */ export function registerTypeOverride(name: string, spec: any) { // determine type section let typeSection = 'ResourceTypes'; if (isPropertyTypeFormat(name)) { typeSection = 'PropertyTypes'; } // determine prior specification let oldSpec: any = {}; try { oldSpec = getType(name); } catch(e) {} // override extendSpecification({ [typeSection]: {[name]: mergeOptions(oldSpec, spec)} }); } export function hasType(type: string): boolean { if (isParameterizedTypeFormat(type)) { type = getParameterizedTypeName(type); } let spec: any = specification.ResourceTypes[type]; if (!spec) { spec = specification.PropertyTypes[type]; } return !!spec; } export function hasProperty(type: string, propertyName: string): boolean { let spec: any = {}; try { spec = getProperty(type, propertyName); return true; } catch(e) {} return false; }
the_stack
import * as React from 'react'; import { Table } from 'antd'; import OlStyle from 'ol/style/Style'; import OlStyleFill from 'ol/style/Fill'; import OlStyleCircle from 'ol/style/Circle'; import OlStyleStroke from 'ol/style/Stroke'; import OlMap from 'ol/Map'; import OlFeature from 'ol/Feature'; import OlSourceVector from 'ol/source/Vector'; import OlLayerBase from 'ol/layer/Base'; import OlLayerVector from 'ol/layer/Vector'; import OlGeometry from 'ol/geom/Geometry'; import OlGeometryCollection from 'ol/geom/GeometryCollection'; import OlMapBrowserEvent from 'ol/MapBrowserEvent'; import { getUid } from 'ol'; import _isEqual from 'lodash/isEqual'; import _isFunction from 'lodash/isFunction'; import _kebabCase from 'lodash/kebabCase'; import MapUtil from '@terrestris/ol-util/dist/MapUtil/MapUtil'; import './FeatureGrid.less'; import { ColumnProps, TableProps } from 'antd/lib/table'; interface DefaultProps { /** * The features to show in the grid and the map (if set). */ features: OlFeature<OlGeometry>[]; /** */ attributeBlacklist?: string[]; /** * The default style to apply to the features. */ featureStyle: OlStyle | (() => OlStyle); /** * The highlight style to apply to the features. */ highlightStyle: OlStyle | (() => OlStyle); /** * The select style to apply to the features. */ selectStyle: OlStyle | (() => OlStyle); /** * The name of the vector layer presenting the features in the grid. */ layerName: string; /** * Custom column definitions to apply to the given column (mapping via key). * See https://ant.design/components/table/#Column. */ columnDefs: ColumnProps<any>; /** * A Function that creates the rowkey from the given feature. * Receives the feature as property. * Default is: feature => feature.ol_uid * */ keyFunction: (feature: OlFeature<OlGeometry>) => string; /** * Whether the map should center on the current feature's extent on init or * not. */ zoomToExtent: boolean; /** * Whether rows and features should be selectable or not. */ selectable: boolean; } export interface BaseProps { /** * A CSS class which should be added to the table. */ className?: string; /** * A CSS class to add to each table row or a function that * is evaluated for each record. */ rowClassName?: string | ((record: any) => string); /** * The map the features should be rendered on. If not given, the features * will be rendered in the table only. */ map?: OlMap; /** * Callback function, that will be called on rowclick. */ onRowClick?: (row: any, feature: OlFeature<OlGeometry>) => void; /** * Callback function, that will be called on rowmouseover. */ onRowMouseOver?: (row: any, feature: OlFeature<OlGeometry>) => void; /** * Callback function, that will be called on rowmouseout. */ onRowMouseOut?: (row: any, feature: OlFeature<OlGeometry>) => void; /** * Callback function, that will be called if the selection changes. */ onRowSelectionChange?: (selectedRowKeys: Array<number | string>, selectedFeatures: OlFeature<OlGeometry>[]) => void; } interface FeatureGridState { selectedRowKeys: string[]; } export type FeatureGridProps = BaseProps & Partial<DefaultProps> & TableProps<any>; /** * The FeatureGrid. * * @class The FeatureGrid * @extends React.Component */ export class FeatureGrid extends React.Component<FeatureGridProps, FeatureGridState> { /** * The default properties. */ static defaultProps: DefaultProps = { features: [], attributeBlacklist: [], featureStyle: new OlStyle({ fill: new OlStyleFill({ color: 'rgba(255, 255, 255, 0.5)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 1 }), image: new OlStyleCircle({ radius: 6, fill: new OlStyleFill({ color: 'rgba(255, 255, 255, 0.5)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 1 }) }) }), highlightStyle: new OlStyle({ fill: new OlStyleFill({ color: 'rgba(230, 247, 255, 0.8)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 1 }), image: new OlStyleCircle({ radius: 6, fill: new OlStyleFill({ color: 'rgba(230, 247, 255, 0.8)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 1 }) }) }), selectStyle: new OlStyle({ fill: new OlStyleFill({ color: 'rgba(230, 247, 255, 0.8)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 2 }), image: new OlStyleCircle({ radius: 6, fill: new OlStyleFill({ color: 'rgba(230, 247, 255, 0.8)' }), stroke: new OlStyleStroke({ color: 'rgba(73, 139, 170, 0.9)', width: 2 }) }) }), layerName: 'react-geo-feature-grid-layer', columnDefs: {}, keyFunction: getUid, zoomToExtent: false, selectable: false }; /** * The class name to add to this component. * @private */ _className = 'react-geo-feature-grid'; /** * The class name to add to each table row. * @private */ _rowClassName = 'react-geo-feature-grid-row'; /** * The prefix to use for each table row class. * @private */ _rowKeyClassNamePrefix = 'row-key-'; /** * The hover class name. * @private */ _rowHoverClassName = 'row-hover'; /** * The source holding the features of the grid. * @private */ _source: OlSourceVector<OlGeometry> = null; /** * The layer representing the features of the grid. * @private */ _layer: OlLayerVector<OlSourceVector<OlGeometry>> = null; /** * The constructor. */ constructor(props: FeatureGridProps) { super(props); this.state = { selectedRowKeys: [] }; } /** * Called on lifecycle phase componentDidMount. */ componentDidMount() { const { map, features, zoomToExtent } = this.props; this.initVectorLayer(map); this.initMapEventHandlers(map); if (zoomToExtent) { this.zoomToFeatures(features); } } /** * Invoked immediately after updating occurs. This method is not called for * the initial render. * * @param prevProps The previous props. */ componentDidUpdate(prevProps: FeatureGridProps) { const { map, features, selectable, zoomToExtent } = this.props; if (!(_isEqual(prevProps.map, map))) { this.initVectorLayer(map); this.initMapEventHandlers(map); } if (!(_isEqual(prevProps.features, features))) { if (this._source) { this._source.clear(); this._source.addFeatures(features); } if (zoomToExtent) { this.zoomToFeatures(features); } } if (!(_isEqual(prevProps.selectable, selectable))) { if (selectable && map) { map.on('singleclick', this.onMapSingleClick); } else { this.setState({ selectedRowKeys: [] }, () => { if (map) { map.un('singleclick', this.onMapSingleClick); } }); } } } /** * Called on lifecycle phase componentWillUnmount. */ componentWillUnmount() { this.deinitVectorLayer(); this.deinitMapEventHandlers(); } /** * Initialized the vector layer that will be used to draw the input features * on and adds it to the map (if any). * * @param map The map to add the layer to. */ initVectorLayer = (map: OlMap) => { const { features, featureStyle, layerName } = this.props; if (!(map instanceof OlMap)) { return; } if (MapUtil.getLayerByName(map, layerName)) { return; } const source = new OlSourceVector({ features: features }); const layer = new OlLayerVector({ properties: { name: layerName }, source: source, style: featureStyle }); map.addLayer(layer); this._source = source; this._layer = layer; }; /** * Adds map event callbacks to highlight and select features in the map (if * given) on pointermove and singleclick. Hovered and selected features will * be highlighted and selected in the grid as well. * * @param map The map to register the handlers to. */ initMapEventHandlers = (map: OlMap) => { const { selectable } = this.props; if (!(map instanceof OlMap)) { return; } map.on('pointermove', this.onMapPointerMove); if (selectable) { map.on('singleclick', this.onMapSingleClick); } }; /** * Highlights the feature beneath the cursor on the map and in the grid. * * @param olEvt The ol event. */ onMapPointerMove = (olEvt: OlMapBrowserEvent<MouseEvent>) => { const { map, features, highlightStyle, selectStyle } = this.props; const { selectedRowKeys } = this.state; const selectedFeatures = map.getFeaturesAtPixel(olEvt.pixel, { layerFilter: (layerCand: OlLayerBase) => layerCand === this._layer }) || []; features.forEach(feature => { const key = _kebabCase(this.props.keyFunction(feature)); const sel = `.${this._rowClassName}.${this._rowKeyClassNamePrefix}${key}`; const el = document.querySelectorAll(sel)[0]; if (el) { el.classList.remove(this._rowHoverClassName); } if (selectedRowKeys.includes(key)) { feature.setStyle(selectStyle); } else { feature.setStyle(null); } }); selectedFeatures.forEach((feature: OlFeature<OlGeometry>) => { const key = _kebabCase(this.props.keyFunction(feature)); const sel = `.${this._rowClassName}.${this._rowKeyClassNamePrefix}${key}`; const el = document.querySelectorAll(sel)[0]; if (el) { el.classList.add(this._rowHoverClassName); } feature.setStyle(highlightStyle); }); }; /** * Selects the selected feature in the map and in the grid. * * @param olEvt The ol event. */ onMapSingleClick = (olEvt: OlMapBrowserEvent<MouseEvent>) => { const { map, selectStyle } = this.props; const { selectedRowKeys } = this.state; const selectedFeatures = (map.getFeaturesAtPixel(olEvt.pixel, { layerFilter: (layerCand: OlLayerBase) => layerCand === this._layer }) || []) as OlFeature<OlGeometry>[]; let rowKeys = [...selectedRowKeys]; selectedFeatures.forEach(selectedFeature => { const key = this.props.keyFunction(selectedFeature); if (rowKeys.includes(key)) { rowKeys = rowKeys.filter(rowKey => rowKey !== key); selectedFeature.setStyle(null); } else { rowKeys.push(key); selectedFeature.setStyle(selectStyle); } }); this.setState({ selectedRowKeys: rowKeys }); }; /** * Removes the vector layer from the given map (if any). */ deinitVectorLayer = () => { const { map } = this.props; if (!(map instanceof OlMap)) { return; } map.removeLayer(this._layer); }; /** * Unbinds the pointermove and click event handlers from the map (if given). */ deinitMapEventHandlers = () => { const { map, selectable } = this.props; if (!(map instanceof OlMap)) { return; } map.un('pointermove', this.onMapPointerMove); if (selectable) { map.un('singleclick', this.onMapSingleClick); } }; /** * Returns the column definitions out of the attributes of the first * given feature. * * @return The column definitions. */ getColumnDefs = () => { const { attributeBlacklist, features, columnDefs } = this.props; const columns = []; const feature = features[0]; if (!(feature instanceof OlFeature)) { return columns; } const props = feature.getProperties(); Object.keys(props).forEach(key => { if (attributeBlacklist.includes(key)) { return; } if (props[key] instanceof OlGeometry) { return; } columns.push({ title: key, dataIndex: key, key: key, ...columnDefs[key] }); }); return columns; }; /** * Returns the table row data from all of the given features. * * @return The table data. */ getTableData = () => { const { features } = this.props; const data = []; features.forEach(feature => { const properties = feature.getProperties(); const filtered = Object.keys(properties) .filter(key => !(properties[key] instanceof OlGeometry)) .reduce((obj, key) => { obj[key] = properties[key]; return obj; }, {}); data.push({ key: this.props.keyFunction(feature), ...filtered }); }); return data; }; /** * Returns the correspondig feature for the given table row key. * * @param key The row key to obtain the feature from. * @return The feature candidate. */ getFeatureFromRowKey = (key: number | string): OlFeature<OlGeometry> => { const { features, keyFunction } = this.props; const feature = features.filter(f => keyFunction(f) === key); return feature[0]; }; /** * Called on row click and zooms the the corresponding feature's extent. * * @param row The clicked row. */ onRowClick = (row: any) => { const { onRowClick } = this.props; const feature = this.getFeatureFromRowKey(row.key); if (_isFunction(onRowClick)) { onRowClick(row, feature); } this.zoomToFeatures([feature]); }; /** * Called on row mouseover and hightlights the corresponding feature's * geometry. * * @param row The highlighted row. */ onRowMouseOver = (row: any) => { const { onRowMouseOver } = this.props; const feature = this.getFeatureFromRowKey(row.key); if (_isFunction(onRowMouseOver)) { onRowMouseOver(row, feature); } this.highlightFeatures([feature]); }; /** * Called on mouseout and unhightlights any highlighted feature. * * @param row The unhighlighted row. */ onRowMouseOut = (row: any) => { const { onRowMouseOut } = this.props; const feature = this.getFeatureFromRowKey(row.key); if (_isFunction(onRowMouseOut)) { onRowMouseOut(row, feature); } this.unhighlightFeatures([feature]); }; /** * Fits the map's view to the extent of the passed features. * * @param features The features to zoom to. */ zoomToFeatures = (features: OlFeature<OlGeometry>[]) => { const { map } = this.props; if (!(map instanceof OlMap)) { return; } const featGeometries = []; features.forEach(feature => { featGeometries.push(feature.getGeometry()); }); if (featGeometries.length > 0) { const geomCollection = new OlGeometryCollection(featGeometries); map.getView().fit(geomCollection.getExtent()); } }; /** * Highlights the given features in the map. * * @param highlightFeatures The features to highlight. */ highlightFeatures = (highlightFeatures: OlFeature<OlGeometry>[]) => { const { map, highlightStyle } = this.props; if (!(map instanceof OlMap)) { return; } highlightFeatures.forEach(feature => feature.setStyle(highlightStyle)); }; /** * Unhighlights the given features in the map. * * @param unhighlightFeatures The features to unhighlight. */ unhighlightFeatures = (unhighlightFeatures: OlFeature<OlGeometry>[]) => { const { map, selectStyle } = this.props; const { selectedRowKeys } = this.state; if (!(map instanceof OlMap)) { return; } unhighlightFeatures.forEach(feature => { const key = this.props.keyFunction(feature); if (selectedRowKeys.includes(key)) { feature.setStyle(selectStyle); } else { feature.setStyle(null); } }); }; /** * Sets the select style to the given features in the map. * * @param features The features to select. */ selectFeatures = (features: OlFeature<OlGeometry>[]) => { const { map, selectStyle } = this.props; if (!(map instanceof OlMap)) { return; } features.forEach(feature => feature.setStyle(selectStyle)); }; /** * Resets the style of all features. */ resetFeatureStyles = () => { const { map, features } = this.props; if (!(map instanceof OlMap)) { return; } features.forEach(feature => feature.setStyle(null)); }; /** * Called if the selection changes. * * @param selectedRowKeys The list of currently selected row keys. */ onSelectChange = (selectedRowKeys: string[]) => { const { onRowSelectionChange } = this.props; const selectedFeatures = selectedRowKeys.map(key => this.getFeatureFromRowKey(key)); if (_isFunction(onRowSelectionChange)) { onRowSelectionChange(selectedRowKeys, selectedFeatures); } this.resetFeatureStyles(); this.selectFeatures(selectedFeatures); this.setState({ selectedRowKeys }); }; /** * The render method. */ render() { const { className, rowClassName, features, map, attributeBlacklist, onRowClick, onRowMouseOver, onRowMouseOut, zoomToExtent, selectable, featureStyle, highlightStyle, selectStyle, layerName, columnDefs, children, ...passThroughProps } = this.props; const { selectedRowKeys } = this.state; const rowSelection = { selectedRowKeys, onChange: this.onSelectChange }; const finalClassName = className ? `${className} ${this._className}` : this._className; let rowClassNameFn: (record: any) => string; if (_isFunction(rowClassName)) { rowClassNameFn = record => `${this._rowClassName} ${(rowClassName as ((r: any) => string))(record)}`; } else { const finalRowClassName = rowClassName ? `${rowClassName} ${this._rowClassName}` : this._rowClassName; rowClassNameFn = record => `${finalRowClassName} ${this._rowKeyClassNamePrefix}${_kebabCase(record.key)}`; } return ( <Table className={finalClassName} columns={this.getColumnDefs()} dataSource={this.getTableData()} onRow={record => ({ onClick: () => this.onRowClick(record), onMouseOver: () => this.onRowMouseOver(record), onMouseOut: () => this.onRowMouseOut(record) })} rowClassName={rowClassNameFn} rowSelection={selectable ? rowSelection : null} {...passThroughProps} > {children} </Table> ); } } export default FeatureGrid;
the_stack
import { PdfColorSpace } from './../enum'; import { PdfColor } from './../pdf-color'; import { PdfBrush } from './pdf-brush'; import { PointF, RectangleF } from './../../drawing/pdf-drawing'; import { PdfDictionary} from '../../primitives/pdf-dictionary'; import { DictionaryProperties } from './../../input-output/pdf-dictionary-properties'; import { PdfBoolean } from '../../primitives/pdf-boolean'; import { PdfArray } from './../../primitives/pdf-array'; import { PdfNumber } from './../../primitives/pdf-number'; import { PdfColorBlend } from './pdf-color-blend'; import { PdfBlend } from './pdf-blend'; import { PdfGradientBrush } from './pdf-gradient-brush'; import { PdfExtend , ShadingType} from './enum'; /** * `PdfRadialGradientBrush` Represent radial gradient brush. * @private */ export class PdfRadialGradientBrush extends PdfGradientBrush { //Fields /** * Local varaible to store the point start. * @private */ private mPointStart: PointF; /** * Local varaible to store the radius start. * @private */ private mRadiusStart: number; /** * Local varaible to store the point End. * @private */ private mPointEnd: PointF; /** * Local varaible to store the radius End. * @private */ private mRadiusEnd: number; /** * Local varaible to store the colours. * @private */ private mColour: PdfColor[]; /** * Local varaible to store the colour blend. * @private */ private mColourBlends: PdfColorBlend; /** * Local varaible to store the blend. * @private */ private mBlend: PdfBlend; /** * Local varaible to store the boundaries. * @private */ private mBoundaries: RectangleF; /** * Local varaible to store the dictionary properties. */ private mDictionaryProperties : DictionaryProperties = new DictionaryProperties(); //Constructor /** * Initializes a new instance of the `PdfRadialGradientBrush` class. * @public */ /* tslint:disable-next-line:max-line-length */ public constructor(centerStart: PointF, radiusStart: number, centerEnd: PointF, radiusEnd: number, colorStart: PdfColor, colorEnd: PdfColor) { super(new PdfDictionary()); this.initialize(colorStart, colorEnd); if (radiusStart < 0) { throw new Error('ArgumentOutOfRangeException : radiusStart - The radius cannot be less then zero.'); } if (radiusEnd < 0) { throw new Error('ArgumentOutOfRangeException : radiusEnd - The radius cannpt be less then zero.'); } this.mPointEnd = centerEnd; this.mPointStart = centerStart; this.mRadiusStart = radiusStart; this.mRadiusEnd = radiusEnd; this.setPoints(this.mPointStart, this.mPointEnd, this.mRadiusStart, this.mRadiusEnd); } /** * Initializes a new instance of the `PdfRadialGradientBrush` class. * @param color1 The color1. * @param color2 The color2. */ private initialize(color1: PdfColor, color2: PdfColor) : void { this.mColour = [ color1, color2]; this.mColourBlends = new PdfColorBlend(2); this.mColourBlends.positions = [ 0, 1]; this.mColourBlends.colors = this.mColour; this.initShading(); } //Properties /** * Gets or sets a PdfBlend that specifies positions and factors that define a custom falloff for the gradient. * @public */ public get blend(): PdfBlend { return this.mBlend; } public set blend(value: PdfBlend) { if ((value == null)) { throw new Error('ArgumentNullException : Blend'); } if ((this.mColour == null && typeof this.mColour === 'undefined')) { throw new Error('NotSupportedException : There is no starting and ending colours specified.'); } this.mBlend = value; this.mColourBlends = this.mBlend.generateColorBlend(this.mColour, this.colorSpace); this.resetFunction(); } /** * Gets or sets a ColorBlend that defines a multicolor radial gradient. * @public */ public get interpolationColors(): PdfColorBlend { return this.mColourBlends; } public set interpolationColors(value: PdfColorBlend) { if (value == null) { throw new Error('ArgumentNullException : InterpolationColors'); } this.mBlend = null; this.mColour = null; this.mColourBlends = value; this.resetFunction(); } /** * Gets or sets the starting and ending colors of the radial gradient. * @public */ public get linearColors(): PdfColor[] { return this.mColour; } public set linearColors(value: PdfColor[]) { if ((value == null)) { throw new Error('ArgumentNullException : radial LinearColors'); } if ((value.length < 2)) { throw new Error('ArgumentException : The array is too small LinearColors'); } if ((this.mColour == null && typeof this.mColour === 'undefined')) { this.mColour = [value[0], value[1]]; } else { this.mColour[0] = value[0]; this.mColour[1] = value[1]; } if ((this.mBlend == null && typeof this.mBlend === 'undefined')) { // Set correct colour blend. this.mColourBlends = new PdfColorBlend(2); this.mColourBlends.colors = this.mColour; this.mColourBlends.positions = [0, 1]; } else { this.mColourBlends = this.mBlend.generateColorBlend(this.mColour, this.colorSpace); } this.resetFunction(); } /** * Gets or sets the rectangle. * @public */ public get rectangle(): RectangleF { return this.mBoundaries; } public set rectangle(value: RectangleF) { this.mBoundaries = value; this.bBox = PdfArray.fromRectangle(value); } /** * Gets or sets the value indicating whether the gradient * should extend starting and ending points. * @public */ public get extend(): PdfExtend { let result1 : PdfExtend = PdfExtend.None; let extend1 : PdfArray = (<PdfArray>(this.shading.items.getValue(this.mDictionaryProperties.extend))); if (extend1 !== null && typeof extend1 !== 'undefined') { let extStart : PdfBoolean = (<PdfBoolean>(extend1.items(0))); let extEnd : PdfBoolean = (<PdfBoolean>(extend1.items(1))); if (extStart.value) { result1 = (result1 | PdfExtend.Start); } if (extEnd.value) { result1 = (result1 | PdfExtend.End); } } return result1; } public set extend(value: PdfExtend) { let extend : PdfArray = (<PdfArray>(this.shading.items.getValue(this.mDictionaryProperties.extend))); let extStart : PdfBoolean; let extEnd1 : PdfBoolean; if (extend == null && typeof extend === 'undefined') { extStart = new PdfBoolean(false); extEnd1 = new PdfBoolean(false); extend = new PdfArray(); extend.add(extStart); extend.add(extEnd1); this.shading.items.setValue(this.mDictionaryProperties.extend, extend); } else { extStart = (<PdfBoolean>(extend.items(0))); extEnd1 = (<PdfBoolean>(extend.items(1))); } } //Implementation /** * Sets the points. * @param pointStart The point start. * @param pointEnd The point end. * @param radiusStart The radius start. * @param radiusEnd The radius end. */ private setPoints(pointStart: PointF, pointEnd: PointF, radiusStart: number, radiusEnd: number) : void { let points: PdfArray = new PdfArray(); points.add(new PdfNumber(pointStart.x)); points.add(new PdfNumber(this.updateY(pointStart.y))); points.add(new PdfNumber(radiusStart)); points.add(new PdfNumber(pointEnd.x)); points.add(new PdfNumber(this.updateY(pointEnd.y))); if ((radiusStart !== radiusEnd)) { points.add(new PdfNumber(radiusEnd)); } else { points.add(new PdfNumber(0)); } this.shading.items.setValue(this.mDictionaryProperties.coords, points); } /** * Update y co-ordinate. * @param y Y co-ordinate. */ private updateY(y: number): number { if (y !== 0) { return -y; } else { return y; } } /** * Initializess the shading dictionary. * @private */ private initShading(): void { this.colorSpace = PdfColorSpace.Rgb; this.function = this.mColourBlends.getFunction(this.colorSpace); this.shading.items.setValue(this.mDictionaryProperties.shadingType, new PdfNumber((<number>(ShadingType.Radial)))); } //Overrides /** * Creates a new copy of a brush. * @public */ public clone(): PdfBrush { let rBrush: PdfRadialGradientBrush = this; rBrush.resetPatternDictionary(new PdfDictionary(this.patternDictionary)); rBrush.shading = new PdfDictionary(); rBrush.initShading(); rBrush.setPoints(this.mPointStart, this.mPointEnd, this.mRadiusStart, this.mRadiusEnd); if ( rBrush instanceof PdfRadialGradientBrush) { if ((this.matrix !== null && typeof this.matrix !== 'undefined')) { rBrush.matrix = this.matrix.clone(); } } if ((this.mColour !== null && typeof this.mColour !== 'undefined')) { rBrush.mColour = (<PdfColor[]>(this.mColour)); } if ((this.blend !== null && typeof this.blend !== 'undefined')) { rBrush.blend = this.blend.clonePdfBlend(); } else if ((this.interpolationColors !== null && typeof this.interpolationColors !== 'undefined')) { rBrush.interpolationColors = this.interpolationColors.cloneColorBlend(); } rBrush.extend = this.extend; this.cloneBackgroundValue(rBrush); this.cloneAntiAliasingValue(rBrush); return rBrush; } /** * Resets the function. * @public */ public resetFunction() : void { this.function = this.mColourBlends.getFunction(this.colorSpace); } }
the_stack
import { RequestFile } from './models'; import { DomainCdnConfig } from './domainCdnConfig'; import { DomainSetupInfo } from './domainSetupInfo'; export class Domain { 'portalId': number; 'id': number; 'created': number; 'updated': number; 'domain': string; 'primaryLandingPage': boolean; 'primaryEmail': boolean; 'primaryBlog': boolean; 'primaryBlogPost': boolean; 'primarySitePage': boolean; 'primaryKnowledge': boolean; 'primaryLegacyPage': boolean; 'primaryClickTracking': boolean; 'fullCategoryKey': string; 'secondaryToDomain': string; 'isResolving': boolean; 'isDnsCorrect': boolean; 'manuallyMarkedAsResolving': boolean; 'consecutiveNonResolvingCount': number; 'sslCname': string; 'isSslEnabled': boolean; 'isSslOnly': boolean; 'certificateId': number; 'sslRequestId': number; 'isUsedForBlogPost': boolean; 'isUsedForSitePage': boolean; 'isUsedForLandingPage': boolean; 'isUsedForEmail': boolean; 'isUsedForKnowledge': boolean; 'setupTaskId': number; 'isSetupComplete': boolean; 'setUpLanguage': string; 'teamIds': Array<number>; 'actualCname': string; 'correctCname': string; 'actualIp': string; 'apexResolutionStatus': Domain.ApexResolutionStatusEnum; 'apexDomain': string; 'publicSuffix': string; 'apexIpAddresses': Array<string>; 'siteId': number; 'brandId': number; 'deletable': boolean; 'domainCdnConfig': DomainCdnConfig; 'setupInfo': DomainSetupInfo; 'derivedBrandName': string; 'createdById': number; 'updatedById': number; 'label': string; 'isAnyPrimary': boolean; 'isLegacyDomain': boolean; 'isInternalDomain': boolean; 'isResolvingInternalProperty': boolean; 'isResolvingIgnoringManuallyMarkedAsResolving': boolean; 'isUsedForAnyContentType': boolean; 'isLegacy': boolean; 'authorAt': number; 'cosObjectType': Domain.CosObjectTypeEnum; 'cdnPurgeEmbargoTime': number; 'isStagingDomain': boolean; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "portalId", "baseName": "portalId", "type": "number" }, { "name": "id", "baseName": "id", "type": "number" }, { "name": "created", "baseName": "created", "type": "number" }, { "name": "updated", "baseName": "updated", "type": "number" }, { "name": "domain", "baseName": "domain", "type": "string" }, { "name": "primaryLandingPage", "baseName": "primaryLandingPage", "type": "boolean" }, { "name": "primaryEmail", "baseName": "primaryEmail", "type": "boolean" }, { "name": "primaryBlog", "baseName": "primaryBlog", "type": "boolean" }, { "name": "primaryBlogPost", "baseName": "primaryBlogPost", "type": "boolean" }, { "name": "primarySitePage", "baseName": "primarySitePage", "type": "boolean" }, { "name": "primaryKnowledge", "baseName": "primaryKnowledge", "type": "boolean" }, { "name": "primaryLegacyPage", "baseName": "primaryLegacyPage", "type": "boolean" }, { "name": "primaryClickTracking", "baseName": "primaryClickTracking", "type": "boolean" }, { "name": "fullCategoryKey", "baseName": "fullCategoryKey", "type": "string" }, { "name": "secondaryToDomain", "baseName": "secondaryToDomain", "type": "string" }, { "name": "isResolving", "baseName": "isResolving", "type": "boolean" }, { "name": "isDnsCorrect", "baseName": "isDnsCorrect", "type": "boolean" }, { "name": "manuallyMarkedAsResolving", "baseName": "manuallyMarkedAsResolving", "type": "boolean" }, { "name": "consecutiveNonResolvingCount", "baseName": "consecutiveNonResolvingCount", "type": "number" }, { "name": "sslCname", "baseName": "sslCname", "type": "string" }, { "name": "isSslEnabled", "baseName": "isSslEnabled", "type": "boolean" }, { "name": "isSslOnly", "baseName": "isSslOnly", "type": "boolean" }, { "name": "certificateId", "baseName": "certificateId", "type": "number" }, { "name": "sslRequestId", "baseName": "sslRequestId", "type": "number" }, { "name": "isUsedForBlogPost", "baseName": "isUsedForBlogPost", "type": "boolean" }, { "name": "isUsedForSitePage", "baseName": "isUsedForSitePage", "type": "boolean" }, { "name": "isUsedForLandingPage", "baseName": "isUsedForLandingPage", "type": "boolean" }, { "name": "isUsedForEmail", "baseName": "isUsedForEmail", "type": "boolean" }, { "name": "isUsedForKnowledge", "baseName": "isUsedForKnowledge", "type": "boolean" }, { "name": "setupTaskId", "baseName": "setupTaskId", "type": "number" }, { "name": "isSetupComplete", "baseName": "isSetupComplete", "type": "boolean" }, { "name": "setUpLanguage", "baseName": "setUpLanguage", "type": "string" }, { "name": "teamIds", "baseName": "teamIds", "type": "Array<number>" }, { "name": "actualCname", "baseName": "actualCname", "type": "string" }, { "name": "correctCname", "baseName": "correctCname", "type": "string" }, { "name": "actualIp", "baseName": "actualIp", "type": "string" }, { "name": "apexResolutionStatus", "baseName": "apexResolutionStatus", "type": "Domain.ApexResolutionStatusEnum" }, { "name": "apexDomain", "baseName": "apexDomain", "type": "string" }, { "name": "publicSuffix", "baseName": "publicSuffix", "type": "string" }, { "name": "apexIpAddresses", "baseName": "apexIpAddresses", "type": "Array<string>" }, { "name": "siteId", "baseName": "siteId", "type": "number" }, { "name": "brandId", "baseName": "brandId", "type": "number" }, { "name": "deletable", "baseName": "deletable", "type": "boolean" }, { "name": "domainCdnConfig", "baseName": "domainCdnConfig", "type": "DomainCdnConfig" }, { "name": "setupInfo", "baseName": "setupInfo", "type": "DomainSetupInfo" }, { "name": "derivedBrandName", "baseName": "derivedBrandName", "type": "string" }, { "name": "createdById", "baseName": "createdById", "type": "number" }, { "name": "updatedById", "baseName": "updatedById", "type": "number" }, { "name": "label", "baseName": "label", "type": "string" }, { "name": "isAnyPrimary", "baseName": "isAnyPrimary", "type": "boolean" }, { "name": "isLegacyDomain", "baseName": "isLegacyDomain", "type": "boolean" }, { "name": "isInternalDomain", "baseName": "isInternalDomain", "type": "boolean" }, { "name": "isResolvingInternalProperty", "baseName": "isResolvingInternalProperty", "type": "boolean" }, { "name": "isResolvingIgnoringManuallyMarkedAsResolving", "baseName": "isResolvingIgnoringManuallyMarkedAsResolving", "type": "boolean" }, { "name": "isUsedForAnyContentType", "baseName": "isUsedForAnyContentType", "type": "boolean" }, { "name": "isLegacy", "baseName": "isLegacy", "type": "boolean" }, { "name": "authorAt", "baseName": "authorAt", "type": "number" }, { "name": "cosObjectType", "baseName": "cosObjectType", "type": "Domain.CosObjectTypeEnum" }, { "name": "cdnPurgeEmbargoTime", "baseName": "cdnPurgeEmbargoTime", "type": "number" }, { "name": "isStagingDomain", "baseName": "isStagingDomain", "type": "boolean" } ]; static getAttributeTypeMap() { return Domain.attributeTypeMap; } } export namespace Domain { export enum ApexResolutionStatusEnum { Ineligible = <any> 'INELIGIBLE', SuggestResolving = <any> 'SUGGEST_RESOLVING', AlreadyResolving = <any> 'ALREADY_RESOLVING', Error = <any> 'ERROR' } export enum CosObjectTypeEnum { Content = <any> 'CONTENT', ExtensionResource = <any> 'EXTENSION_RESOURCE', Layout = <any> 'LAYOUT', CustomWidget = <any> 'CUSTOM_WIDGET', Widget = <any> 'WIDGET', Form = <any> 'FORM', Placement = <any> 'PLACEMENT', Image = <any> 'IMAGE', DomainSettings = <any> 'DOMAIN_SETTINGS', SiteSettings = <any> 'SITE_SETTINGS', EmailAddress = <any> 'EMAIL_ADDRESS', Workflow = <any> 'WORKFLOW', HubdbTable = <any> 'HUBDB_TABLE', RedirectUrl = <any> 'REDIRECT_URL', DesignFolder = <any> 'DESIGN_FOLDER', SiteMap = <any> 'SITE_MAP', Domain = <any> 'DOMAIN', Blog = <any> 'BLOG', File = <any> 'FILE', Folder = <any> 'FOLDER', SiteMenu = <any> 'SITE_MENU', Theme = <any> 'THEME', ContentGroup = <any> 'CONTENT_GROUP', FollowMe = <any> 'FOLLOW_ME', KnowledgeBase = <any> 'KNOWLEDGE_BASE', ListMembership = <any> 'LIST_MEMBERSHIP', ContactMembership = <any> 'CONTACT_MEMBERSHIP', PasswordProtected = <any> 'PASSWORD_PROTECTED', UnrestrictedAccess = <any> 'UNRESTRICTED_ACCESS', MarketplaceListing = <any> 'MARKETPLACE_LISTING', LayoutSection = <any> 'LAYOUT_SECTION', ThemeSettings = <any> 'THEME_SETTINGS', VideoPlayer = <any> 'VIDEO_PLAYER', UrlMapping = <any> 'URL_MAPPING', KnowledgeCategory = <any> 'KNOWLEDGE_CATEGORY', KnowledgeHomepageCategory = <any> 'KNOWLEDGE_HOMEPAGE_CATEGORY', RawAsset = <any> 'RAW_ASSET', GlobalContent = <any> 'GLOBAL_CONTENT', HubdbTableRow = <any> 'HUBDB_TABLE_ROW', BlogAuthor = <any> 'BLOG_AUTHOR', ServerlessFunction = <any> 'SERVERLESS_FUNCTION', KnowledgeCategoryTranslation = <any> 'KNOWLEDGE_CATEGORY_TRANSLATION' } }
the_stack
import { getPathsRelativeToCwd, IOpticTaskRunnerConfig, parseRule, readApiConfig, } from '@useoptic/cli-config'; import express from 'express'; import bodyParser from 'body-parser'; import path from 'path'; import fs from 'fs-extra'; import Bottleneck from 'bottleneck'; import sortBy from 'lodash.sortby'; import { DefaultIdGenerator, developerDebugLogger } from '@useoptic/cli-shared'; import { makeRouter as makeCaptureRouter } from './capture-router'; import { LocalCaptureInteractionPointerConverter } from '@useoptic/cli-shared/build/captures/avro/file-system/interaction-iterator'; import { IgnoreFileHelper } from '@useoptic/cli-config/build/helpers/ignore-file-interface'; import { SessionsManager } from '../sessions'; import { patchInitialTaskOpticYaml } from '@useoptic/cli-config/build/helpers/patch-optic-config'; import { getSpecEventsFrom } from '@useoptic/cli-config/build/helpers/read-specification-json'; import { makeSpectacle } from '@useoptic/spectacle'; import { graphqlHTTP } from 'express-graphql'; import { LocalCliOpticContextBuilder } from '../spectacle'; type CaptureId = string; type Iso8601Timestamp = string; export type InvalidCaptureState = { captureId: CaptureId; status: 'unknown'; }; export function isValidCaptureState(x: CaptureState): x is ValidCaptureState { return x.status === 'started' || x.status === 'completed'; } export type ValidCaptureState = { captureId: CaptureId; status: 'started' | 'completed'; metadata: { taskConfig: IOpticTaskRunnerConfig; startedAt: Iso8601Timestamp; lastInteraction: { count: number; observedAt: Iso8601Timestamp; } | null; }; }; export type CaptureState = InvalidCaptureState | ValidCaptureState; const captureStateFileName = 'optic-capture-state.json'; export class CapturesHelpers { constructor(private basePath: string) {} async validateCaptureId( req: express.Request, res: express.Response, next: express.NextFunction ) { const { captureId } = req.params; const captureDirectoryPath = this.captureDirectory(captureId); const exists = await fs.pathExists(captureDirectoryPath); if (exists) { return next(); } else { return res.sendStatus(404); } } async listCaptureIds(): Promise<CaptureId[]> { const captureIds = await fs.readdir(this.basePath); return captureIds; } async loadCaptureState(captureId: CaptureId): Promise<CaptureState> { const stateFilePath = this.stateFile(captureId); const stateFileExists = await fs.pathExists(stateFilePath); if (!stateFileExists) { return { captureId, status: 'unknown', }; } const state = await fs.readJson(stateFilePath); return state; } async updateCaptureState(state: CaptureState): Promise<void> { await fs.ensureDir(this.captureDirectory(state.captureId)); const stateFilePath = this.stateFile(state.captureId); await fs.writeJson(stateFilePath, state); } async listCapturesState(): Promise<CaptureState[]> { const captureIds = await this.listCaptureIds(); const promises = captureIds.map((captureId) => { return this.loadCaptureState(captureId); }); const capturesState = await Promise.all(promises); return capturesState.filter((x) => x !== null); } async loadCaptureSummary(captureId: CaptureId) { const captureDirectory = this.captureDirectory(captureId); const files = await fs.readdir(captureDirectory); const interactions = files.filter((x) => x.startsWith('interactions-')); const promises = interactions.map((x) => { return fs.readJson(path.join(captureDirectory, x)); }); const summaries = await Promise.all(promises); const summary = summaries.reduce( (acc, value) => { acc.diffsCount = acc.diffsCount + value.diffsCount; acc.interactionsCount = acc.interactionsCount + value.interactionsCount; return acc; }, { diffsCount: 0, interactionsCount: 0 } ); return summary; } stateFile(captureId: CaptureId): string { return path.join(this.captureDirectory(captureId), captureStateFileName); } baseDirectory(): string { return this.basePath; } captureDirectory(captureId: CaptureId): string { return path.join(this.basePath, captureId); } } export class ExampleRequestsHelpers { constructor(private basePath: string) {} exampleFile(requestId: string) { return path.join(this.basePath, requestId, 'examples.json'); } async getExampleRequests(requestId: string): Promise<any> { const exampleFilePath = this.exampleFile(requestId); const currentFileContents = await (async () => { const exists = await fs.pathExists(exampleFilePath); if (exists) { try { const contents = await fs.readJson(exampleFilePath); return contents; } catch (e) { return []; } } return []; })(); return currentFileContents; } async saveExampleRequest(requestId: string, example: any) { const exampleFilePath = this.exampleFile(requestId); const currentFileContents = await this.getExampleRequests(requestId); currentFileContents.push(example); await fs.ensureFile(exampleFilePath); await fs.writeJson(exampleFilePath, currentFileContents, { spaces: 2 }); } } export async function makeRouter( sessions: SessionsManager, fileReadBottleneck: Bottleneck ) { async function ensureValidSpecId( req: express.Request, res: express.Response, next: express.NextFunction ) { const { specId } = req.params; developerDebugLogger({ specId, sessions }); const session = sessions.findById(specId); if (!session) { res.sendStatus(404); return; } try { const paths = await getPathsRelativeToCwd(session.path); const { configPath, opticIgnorePath, capturesPath, exampleRequestsPath, } = paths; const config = await readApiConfig(configPath); const ignoreHelper = new IgnoreFileHelper(opticIgnorePath, configPath); const capturesHelpers = new CapturesHelpers(capturesPath); const exampleRequestsHelpers = new ExampleRequestsHelpers( exampleRequestsPath ); async function specLoader(): Promise<any[]> { const events = await getSpecEventsFrom(paths.specStorePath); return events; } req.optic = { config, paths, ignoreHelper, capturesHelpers, exampleRequestsHelpers, session, specLoader, }; next(); } catch (e) { res.status(500).json({ message: e.message, }); } } const router = express.Router({ mergeParams: true }); router.use(ensureValidSpecId); // events router router.get('/events', async (req, res) => { try { const events = await req.optic.specLoader(); res.json(events); } catch (e) { res.json([]); } }); const instances: Map<string, any> = new Map(); router.use(bodyParser.json({ limit: '10mb' })); router.use('/spectacle', async (req, res) => { let handler = instances.get(req.optic.session.id); if (!handler) { console.count('LocalCliOpticContextBuilder.fromDirectory'); const opticContext = await LocalCliOpticContextBuilder.fromDirectory( req.optic.paths, req.optic.capturesHelpers ); const spectacle = await makeSpectacle(opticContext); const instance = graphqlHTTP({ //@ts-ignore schema: spectacle.executableSchema, graphiql: true, context: { spectacleContext: spectacle.graphqlContext, }, }); //@GOTCHA see if someone sneaky updated it while we weren't looking handler = instances.get(req.optic.session.id); if (!handler) { instances.set(req.optic.session.id, instance); handler = instance; } } handler(req, res); }); // captures router. cli picks captureId and writes to whatever persistence method and provides capture id to ui. api spec just shows spec? router.get('/captures', async (req, res) => { const captures = await req.optic.capturesHelpers.listCapturesState(); const validCaptures: ValidCaptureState[] = captures.filter((x) => isValidCaptureState(x) ) as ValidCaptureState[]; res.json({ captures: sortBy(validCaptures, (i) => i.metadata.startedAt) .reverse() .map((i) => ({ captureId: i.captureId, startedAt: i.metadata.startedAt, status: i.status, lastUpdate: i.metadata.lastInteraction ? i.metadata.lastInteraction.observedAt : i.metadata.startedAt, links: [ { rel: 'status', href: `${req.baseUrl}/captures/${i.captureId}/status`, }, ], })), }); }); router.get('/config', async (req, res) => { const rules = await req.optic.ignoreHelper.getCurrentIgnoreRules(); const configRaw = ( await fs.readFile(req.optic.paths.configPath) ).toString(); res.json({ config: { ...req.optic.config, ignoreRequests: rules.allRules }, configRaw, }); }); router.post( '/config/initial-task', bodyParser.json({ limit: '100kb' }), async (req, res) => { const { task } = req.body; const { name, definition } = task; const newContents = patchInitialTaskOpticYaml( req.optic.config, definition, name ); await fs.writeFile(req.optic.paths.configPath, newContents); res.sendStatus(200); } ); router.post( '/config/raw', bodyParser.json({ limit: '100kb' }), async (req, res) => { const { raw } = req.body; await fs.writeFile(req.optic.paths.configPath, raw); res.json({}); } ); router.get('/ignores', async (req, res) => { const rules = await req.optic.ignoreHelper.getCurrentIgnoreRules(); res.json({ rules, }); }); router.patch( '/ignores', bodyParser.json({ limit: '100kb' }), async (req, res) => { const { rule } = req.body; if (typeof rule === 'string' && Boolean(parseRule(rule))) { await req.optic.ignoreHelper.appendRule(rule); res.json({}); } else { res.status(400).json({ message: 'Invalid ignore rule' }); } } ); const captureRouter = makeCaptureRouter({ idGenerator: new DefaultIdGenerator(), interactionPointerConverterFactory: (config: { captureId: CaptureId; captureBaseDirectory: string; }) => new LocalCaptureInteractionPointerConverter(config), fileReadBottleneck: fileReadBottleneck, }); router.use('/captures/:captureId', captureRouter); return router; }
the_stack
import { TypeAssertion, ValidationContext } from '../types'; import { validate, getType } from '../validator'; import { compile } from '../compiler'; import { serialize, deserialize } from '../serializer'; describe("compiler-3", function() { it("compiler-op-intersection-1", function() { const schemas = [compile(` interface A { a: string; } interface B extends A { b: number; } interface C { c: boolean; } type D = B & C; `), compile(` type D = B & C; interface C { c: boolean; } interface B extends A { b: number; } interface A { a: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'A', 'B', 'C', 'D', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'D', 'C', 'B', 'A', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'D', typeName: 'D', kind: 'object', members: [ ['b', { name: 'b', kind: 'primitive', primitiveName: 'number', }], ['a', { name: 'a', kind: 'primitive', primitiveName: 'string', }], ['c', { name: 'c', kind: 'primitive', primitiveName: 'boolean', }], ], }; // const ty = getType(schema, 'D'); for (const ty of [getType(deserialize(serialize(schema)), 'D'), getType(schema, 'D')]) { expect(ty).toEqual(rhs); { const v = { a: '', b: 0, c: false, }; expect(validate<any>(v, ty, {schema})).toEqual({value: v}); } } } } }); it("compiler-op-subtract+omit-1", function() { const schemas = [compile(` interface A { a: string; } interface B extends A { b: number; } interface C { b: bigint; c: boolean; } type D = B - C; `), compile(` type D = B - C; interface C { b: bigint; c: boolean; } interface B extends A { b: number; } interface A { a: string; } `), compile(` type D = Omit<B, 'b' | 'c'>; interface C { b: bigint; c: boolean; } interface B extends A { b: number; } interface A { a: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'A', 'B', 'C', 'D', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'D', 'C', 'B', 'A', ]); expect(Array.from(schemas[2].keys())).toEqual([ 'D', 'C', 'B', 'A', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'D', typeName: 'D', kind: 'object', members: [ ['a', { name: 'a', kind: 'primitive', primitiveName: 'string', }], ], }; // const ty = getType(schema, 'D'); for (const ty of [getType(deserialize(serialize(schema)), 'D'), getType(schema, 'D')]) { expect(ty).toEqual(rhs); { const v = { a: '', }; expect(validate<any>(v, ty, {schema, noAdditionalProps: true})).toEqual({value: v}); } { const ctx: Partial<ValidationContext> = { checkAll: true, noAdditionalProps: true, schema, }; const v = { a: '', b: 0, c: false, }; expect(validate<any>(v, ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"b, c" of "D" are not matched to additional property patterns.', dataPath: 'D', constraints: {}, }]); } } } } }); it("compiler-op-pick-1", function() { const schemas = [compile(` interface A { a: string; b: number; } interface B extends A { c: boolean; d: bigint; } type C = Pick<B, 'a' | 'c'>; `), compile(` type C = Pick<B, 'a' | 'c'>; interface B extends A { c: boolean; d: bigint; } interface A { a: string; b: number; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'A', 'B', 'C', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'C', 'B', 'A', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [ ['a', { name: 'a', kind: 'primitive', primitiveName: 'string', }], ['c', { name: 'c', kind: 'primitive', primitiveName: 'boolean', }], ], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); { const v = { a: '', c: false, }; expect(validate<any>(v, ty, {schema, noAdditionalProps: true})).toEqual({value: v}); } { const ctx: Partial<ValidationContext> = { checkAll: true, noAdditionalProps: true, schema, }; const v = { a: '', b: 0, c: false, d: BigInt(5), }; expect(validate<any>(v, ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"b, d" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } } } } }); it("compiler-op-partial-1", function() { const schemas = [compile(` interface A { a: string; b: number; } interface B extends A { c: boolean; d: bigint; } type C = Partial<B>; `), compile(` type C = Partial<B>; interface B extends A { c: boolean; d: bigint; } interface A { a: string; b: number; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'A', 'B', 'C', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'C', 'B', 'A', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [ ['c', { name: 'c', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'boolean', }, }], ['d', { name: 'd', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'bigint', }, }], ['a', { name: 'a', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'string', }, }], ['b', { name: 'b', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'number', }, }], ], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); { const v = { a: '', c: false, }; expect(validate<any>(v, ty, {schema, noAdditionalProps: true})).toEqual({value: v}); } { const v = { a: '', b: 0, c: false, d: BigInt(5), }; expect(validate<any>(v, ty, {schema, noAdditionalProps: true})).toEqual({value: v}); } } } } }); it("compiler-enum-1", function() { const schema = compile(` enum Foo { AAA, BBB, CCC, DDD, EEE, } `); { expect(Array.from(schema.keys())).toEqual([ 'Foo', ]); } { const rhs: TypeAssertion = { name: 'Foo', typeName: 'Foo', kind: 'enum', values: [ ['AAA', 0], ['BBB', 1], ['CCC', 2], ['DDD', 3], ['EEE', 4], ], }; // const ty = getType(schema, 'Foo'); for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) { expect(ty).toEqual(rhs); expect(validate<number>(-1, ty)).toEqual(null); expect(validate<number>(0, ty)).toEqual({value: 0}); expect(validate<number>(1, ty)).toEqual({value: 1}); expect(validate<number>(2, ty)).toEqual({value: 2}); expect(validate<number>(3, ty)).toEqual({value: 3}); expect(validate<number>(4, ty)).toEqual({value: 4}); expect(validate<number>(5, ty)).toEqual(null); } } }); it("compiler-enum-2", function() { const schema = compile(` enum Foo { AAA = 2, BBB, CCC = 10, DDD, EEE, } `); { expect(Array.from(schema.keys())).toEqual([ 'Foo', ]); } { const rhs: TypeAssertion = { name: 'Foo', typeName: 'Foo', kind: 'enum', values: [ ['AAA', 2], ['BBB', 3], ['CCC', 10], ['DDD', 11], ['EEE', 12], ], }; // const ty = getType(schema, 'Foo'); for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) { expect(ty).toEqual(rhs); expect(validate<number>(-1, ty)).toEqual(null); expect(validate<number>(0, ty)).toEqual(null); expect(validate<number>(1, ty)).toEqual(null); expect(validate<number>(2, ty)).toEqual({value: 2}); expect(validate<number>(3, ty)).toEqual({value: 3}); expect(validate<number>(4, ty)).toEqual(null); expect(validate<number>(9, ty)).toEqual(null); expect(validate<number>(10, ty)).toEqual({value: 10}); expect(validate<number>(11, ty)).toEqual({value: 11}); expect(validate<number>(12, ty)).toEqual({value: 12}); expect(validate<number>(13, ty)).toEqual(null); } } }); it("compiler-enum-3", function() { const schema = compile(` enum Foo { AAA = 'XA', BBB = 'XB', CCC = 'XC', DDD = 'XD', EEE = 'XE', } `); { expect(Array.from(schema.keys())).toEqual([ 'Foo', ]); } { const rhs: TypeAssertion = { name: 'Foo', typeName: 'Foo', kind: 'enum', values: [ ['AAA', 'XA'], ['BBB', 'XB'], ['CCC', 'XC'], ['DDD', 'XD'], ['EEE', 'XE'], ], }; // const ty = getType(schema, 'Foo'); for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) { expect(ty).toEqual(rhs); expect(validate<number>(-1, ty)).toEqual(null); expect(validate<number>(0, ty)).toEqual(null); expect(validate<number>(1, ty)).toEqual(null); expect(validate<string>('XA', ty)).toEqual({value: 'XA'}); expect(validate<string>('XB', ty)).toEqual({value: 'XB'}); expect(validate<string>('XC', ty)).toEqual({value: 'XC'}); expect(validate<string>('XD', ty)).toEqual({value: 'XD'}); expect(validate<string>('XE', ty)).toEqual({value: 'XE'}); expect(validate<number>('AAA', ty)).toEqual(null); expect(validate<number>('AA', ty)).toEqual(null); expect(validate<number>('', ty)).toEqual(null); } } }); it("compiler-enum-4", function() { const schema = compile(` enum Foo { AAA = 'XA', BBB, CCC, DDD = 10, EEE, FFF = 'XF', } `); { expect(Array.from(schema.keys())).toEqual([ 'Foo', ]); } { const rhs: TypeAssertion = { name: 'Foo', typeName: 'Foo', kind: 'enum', values: [ ['AAA', 'XA'], ['BBB', 0], ['CCC', 1], ['DDD', 10], ['EEE', 11], ['FFF', 'XF'], ], }; // const ty = getType(schema, 'Foo'); for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) { expect(ty).toEqual(rhs); expect(validate<number>(-1, ty)).toEqual(null); expect(validate<number>(0, ty)).toEqual({value: 0}); expect(validate<number>(1, ty)).toEqual({value: 1}); expect(validate<number>(2, ty)).toEqual(null); expect(validate<number>(9, ty)).toEqual(null); expect(validate<number>(10, ty)).toEqual({value: 10}); expect(validate<number>(11, ty)).toEqual({value: 11}); expect(validate<number>(12, ty)).toEqual(null); expect(validate<string>('XA', ty)).toEqual({value: 'XA'}); expect(validate<number>('XB', ty)).toEqual(null); expect(validate<number>('XC', ty)).toEqual(null); expect(validate<number>('XD', ty)).toEqual(null); expect(validate<number>('XE', ty)).toEqual(null); expect(validate<string>('XF', ty)).toEqual({value: 'XF'}); expect(validate<number>('AAA', ty)).toEqual(null); expect(validate<number>('AA', ty)).toEqual(null); expect(validate<number>('', ty)).toEqual(null); } } }); it("compiler-enum-4b", function() { const schema = compile(` const enum Foo { AAA = 'XA', BBB, CCC, DDD = 10, EEE, FFF = 'XF', } `); { expect(Array.from(schema.keys())).toEqual([ 'Foo', ]); } { const rhs: TypeAssertion = { name: 'Foo', typeName: 'Foo', kind: 'enum', values: [ ['AAA', 'XA'], ['BBB', 0], ['CCC', 1], ['DDD', 10], ['EEE', 11], ['FFF', 'XF'], ], isConst: true, }; // const ty = getType(schema, 'Foo'); for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) { expect(ty).toEqual(rhs); expect(validate<number>(-1, ty)).toEqual(null); expect(validate<number>(0, ty)).toEqual({value: 0}); expect(validate<number>(1, ty)).toEqual({value: 1}); expect(validate<number>(2, ty)).toEqual(null); expect(validate<number>(9, ty)).toEqual(null); expect(validate<number>(10, ty)).toEqual({value: 10}); expect(validate<number>(11, ty)).toEqual({value: 11}); expect(validate<number>(12, ty)).toEqual(null); expect(validate<string>('XA', ty)).toEqual({value: 'XA'}); expect(validate<number>('XB', ty)).toEqual(null); expect(validate<number>('XC', ty)).toEqual(null); expect(validate<number>('XD', ty)).toEqual(null); expect(validate<number>('XE', ty)).toEqual(null); expect(validate<string>('XF', ty)).toEqual({value: 'XF'}); expect(validate<number>('AAA', ty)).toEqual(null); expect(validate<number>('AA', ty)).toEqual(null); expect(validate<number>('', ty)).toEqual(null); } } }); it("compiler-enum-5", function() { const schema = compile(` enum Foo { AAA = 'XA', BBB, CCC, DDD = 'XD', EEE, FFF = 'XF', } `); { expect(Array.from(schema.keys())).toEqual([ 'Foo', ]); } { const rhs: TypeAssertion = { name: 'Foo', typeName: 'Foo', kind: 'enum', values: [ ['AAA', 'XA'], ['BBB', 0], ['CCC', 1], ['DDD', 'XD'], ['EEE', 2], ['FFF', 'XF'], ], }; // const ty = getType(schema, 'Foo'); for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) { expect(ty).toEqual(rhs); expect(validate<number>(-1, ty)).toEqual(null); expect(validate<number>(0, ty)).toEqual({value: 0}); expect(validate<number>(1, ty)).toEqual({value: 1}); expect(validate<number>(2, ty)).toEqual({value: 2}); expect(validate<number>(3, ty)).toEqual(null); expect(validate<string>('XA', ty)).toEqual({value: 'XA'}); expect(validate<number>('XB', ty)).toEqual(null); expect(validate<number>('XC', ty)).toEqual(null); expect(validate<string>('XD', ty)).toEqual({value: 'XD'}); expect(validate<number>('XE', ty)).toEqual(null); expect(validate<string>('XF', ty)).toEqual({value: 'XF'}); expect(validate<number>('AAA', ty)).toEqual(null); expect(validate<number>('AA', ty)).toEqual(null); expect(validate<number>('', ty)).toEqual(null); } } }); it("compiler-enum-5b", function() { const schema = compile(` export const enum Foo { AAA = 'XA', BBB, CCC, DDD = 'XD', EEE, FFF = 'XF', } `); { expect(Array.from(schema.keys())).toEqual([ 'Foo', ]); } { const rhs: TypeAssertion = { name: 'Foo', typeName: 'Foo', kind: 'enum', values: [ ['AAA', 'XA'], ['BBB', 0], ['CCC', 1], ['DDD', 'XD'], ['EEE', 2], ['FFF', 'XF'], ], isConst: true, }; // const ty = getType(schema, 'Foo'); for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) { expect(ty).toEqual(rhs); expect(validate<number>(-1, ty)).toEqual(null); expect(validate<number>(0, ty)).toEqual({value: 0}); expect(validate<number>(1, ty)).toEqual({value: 1}); expect(validate<number>(2, ty)).toEqual({value: 2}); expect(validate<number>(3, ty)).toEqual(null); expect(validate<string>('XA', ty)).toEqual({value: 'XA'}); expect(validate<number>('XB', ty)).toEqual(null); expect(validate<number>('XC', ty)).toEqual(null); expect(validate<string>('XD', ty)).toEqual({value: 'XD'}); expect(validate<number>('XE', ty)).toEqual(null); expect(validate<string>('XF', ty)).toEqual({value: 'XF'}); expect(validate<number>('AAA', ty)).toEqual(null); expect(validate<number>('AA', ty)).toEqual(null); expect(validate<number>('', ty)).toEqual(null); } } }); it("compiler-additional-props-1", function() { const schemas = [compile(` interface A { [propNames1: /^A+$/]: string; [propNames2: /^B+$/]: string; } interface C extends A { [propNames3: /^C+$/]: number; [propNames4: /^D+$/]: number; } `), compile(` interface C extends A { [propNames3: /^C+$/]: number; [propNames4: /^D+$/]: number; } interface A { [propNames1: /^A+$/]: string; [propNames2: /^B+$/]: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'A', 'C', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'C', 'A', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [], additionalProps: [ [[/^A+$/], {kind: 'primitive', primitiveName: 'string'}, true], [[/^B+$/], {kind: 'primitive', primitiveName: 'string'}, true], [[/^C+$/], {kind: 'primitive', primitiveName: 'number'}], [[/^D+$/], {kind: 'primitive', primitiveName: 'number'}], ], baseTypes: [{ name: 'A', typeName: 'A', kind: 'object', members: [], additionalProps: [ [[/^A+$/], {kind: 'primitive', primitiveName: 'string'}], [[/^B+$/], {kind: 'primitive', primitiveName: 'string'}], ], }], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); expect(validate<any>({}, ty)).toEqual({value: {}}); expect(validate<any>({'A': ''}, ty)).toEqual({value: {'A': ''}}); expect(validate<any>({'A': 0}, ty)).toEqual(null); expect(validate<any>({'B': ''}, ty)).toEqual({value: {'B': ''}}); expect(validate<any>({'B': 0}, ty)).toEqual(null); expect(validate<any>({'C': ''}, ty)).toEqual(null); expect(validate<any>({'C': 0}, ty)).toEqual({value: {'C': 0}}); { const ctx: Partial<ValidationContext> = {}; expect(validate<any>({'D': ''}, ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'TypeUnmatched', message: '"D" of "C" should be type "number".', dataPath: 'C:D', constraints: {}, value: '', }]); } { const ctx: Partial<ValidationContext> = {}; expect(validate<any>({'D': 0}, ty, ctx)).toEqual({value: {'D': 0}}); } { const ctx: Partial<ValidationContext> = {}; expect(validate<any>({'E': ''}, ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"E" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } { const ctx: Partial<ValidationContext> = {}; expect(validate<any>({'E': 0}, ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"E" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } { const ctx: Partial<ValidationContext> = {}; expect(validate<any>({0: ''}, ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"0" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } { const ctx: Partial<ValidationContext> = { noAdditionalProps: true, }; expect(validate<any>({0: ''}, ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"0" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } { const ctx: Partial<ValidationContext> = {}; expect(validate<any>({0: 0}, ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"0" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } { const ctx: Partial<ValidationContext> = { noAdditionalProps: true, }; expect(validate<any>({0: 0}, ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"0" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } { const ctx: Partial<ValidationContext> = {}; expect(validate<any>([], ty, ctx)).toEqual({value: []}); } { const ctx: Partial<ValidationContext> = { noAdditionalProps: true, }; expect(validate<any>([], ty, ctx)).toEqual({value: []}); } { const ctx: Partial<ValidationContext> = {}; expect(validate<any>([''], ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"0" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } { const ctx: Partial<ValidationContext> = { noAdditionalProps: true, }; expect(validate<any>([''], ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"[number]" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } { const ctx: Partial<ValidationContext> = {}; expect(validate<any>([0], ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"0" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } { const ctx: Partial<ValidationContext> = { noAdditionalProps: true, }; expect(validate<any>([0], ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"[number]" of "C" are not matched to additional property patterns.', dataPath: 'C', constraints: {}, }]); } } } } }); it("compiler-additional-props-1z", function() { const schemas = [compile(` interface A { } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'A', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'A', typeName: 'A', kind: 'object', members: [], }; // const ty = getType(schema, 'A'); for (const ty of [getType(deserialize(serialize(schema)), 'A'), getType(schema, 'A')]) { expect(ty).toEqual(rhs); { const ctx: Partial<ValidationContext> = { noAdditionalProps: true, }; expect(validate<any>([], ty, ctx)).toEqual({value: []}); } { const ctx: Partial<ValidationContext> = { noAdditionalProps: true, }; expect(validate<any>([''], ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"[number]" of "A" are not matched to additional property patterns.', dataPath: 'A', constraints: {}, }]); } { const ctx: Partial<ValidationContext> = { noAdditionalProps: true, }; expect(validate<any>([0], ty, ctx)).toEqual(null); expect(ctx.errors).toEqual([{ code: 'AdditionalPropUnmatched', message: '"[number]" of "A" are not matched to additional property patterns.', dataPath: 'A', constraints: {}, }]); } } } } }); it("compiler-additional-props-2", function() { const schemas = [compile(` interface A { [propNames1: /^A+$/]: string; [propNames2: /^B+$/]: string; } interface C extends A { [propNames3: /^C+$/]: number; [propNames4: /^C+$/]: string; } `), compile(` interface C extends A { [propNames3: /^C+$/]: number; [propNames4: /^C+$/]: string; } interface A { [propNames1: /^A+$/]: string; [propNames2: /^B+$/]: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'A', 'C', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'C', 'A', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [], additionalProps: [ [[/^A+$/], {kind: 'primitive', primitiveName: 'string'}, true], [[/^B+$/], {kind: 'primitive', primitiveName: 'string'}, true], [[/^C+$/], {kind: 'primitive', primitiveName: 'number'}], [[/^C+$/], {kind: 'primitive', primitiveName: 'string'}], ], baseTypes: [{ name: 'A', typeName: 'A', kind: 'object', members: [], additionalProps: [ [[/^A+$/], {kind: 'primitive', primitiveName: 'string'}], [[/^B+$/], {kind: 'primitive', primitiveName: 'string'}], ], }], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); expect(validate<any>({}, ty)).toEqual({value: {}}); expect(validate<any>({'A': ''}, ty)).toEqual({value: {'A': ''}}); expect(validate<any>({'A': 0}, ty)).toEqual(null); expect(validate<any>({'B': ''}, ty)).toEqual({value: {'B': ''}}); expect(validate<any>({'B': 0}, ty)).toEqual(null); expect(validate<any>({'C': ''}, ty)).toEqual({value: {'C': ''}}); expect(validate<any>({'C': 0}, ty)).toEqual({value: {'C': 0}}); expect(validate<any>({'D': ''}, ty)).toEqual(null); expect(validate<any>({'D': 0}, ty)).toEqual(null); expect(validate<any>({'E': ''}, ty)).toEqual(null); expect(validate<any>({'E': 0}, ty)).toEqual(null); expect(validate<any>({0: ''}, ty)).toEqual(null); expect(validate<any>({0: 0}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([0], ty)).toEqual(null); } } } }); it("compiler-additional-props-3", function() { const schemas = [compile(` interface A { [propNames1: /^A+$/]: string; [propNames2: number | /^B+$/]: string; } interface C extends A { [propNames3: /^C+$/]: number; [propNames4: /^D+$/ | number]: number; } `), compile(` interface C extends A { [propNames3: /^C+$/]: number; [propNames4: /^D+$/ | number]: number; } interface A { [propNames1: /^A+$/]: string; [propNames2: number | /^B+$/]: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'A', 'C', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'C', 'A', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [], additionalProps: [ [[/^A+$/], {kind: 'primitive', primitiveName: 'string'}, true], [['number', /^B+$/], {kind: 'primitive', primitiveName: 'string'}, true], [[/^C+$/], {kind: 'primitive', primitiveName: 'number'}], [[/^D+$/, 'number'], {kind: 'primitive', primitiveName: 'number'}], ], baseTypes: [{ name: 'A', typeName: 'A', kind: 'object', members: [], additionalProps: [ [[/^A+$/], {kind: 'primitive', primitiveName: 'string'}], [['number', /^B+$/], {kind: 'primitive', primitiveName: 'string'}], ], }], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); expect(validate<any>({}, ty)).toEqual({value: {}}); expect(validate<any>({'A': ''}, ty)).toEqual({value: {'A': ''}}); expect(validate<any>({'A': 0}, ty)).toEqual(null); expect(validate<any>({'B': ''}, ty)).toEqual({value: {'B': ''}}); expect(validate<any>({'B': 0}, ty)).toEqual(null); expect(validate<any>({'C': ''}, ty)).toEqual(null); expect(validate<any>({'C': 0}, ty)).toEqual({value: {'C': 0}}); expect(validate<any>({'D': ''}, ty)).toEqual(null); expect(validate<any>({'D': 0}, ty)).toEqual({value: {'D': 0}}); expect(validate<any>({'E': ''}, ty)).toEqual(null); expect(validate<any>({'E': 0}, ty)).toEqual(null); expect(validate<any>({0: ''}, ty)).toEqual({value: {'0': ''}}); expect(validate<any>({0: 0}, ty)).toEqual({value: {'0': 0}}); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([''], ty)).toEqual({value: ['']}); expect(validate<any>([0], ty)).toEqual({value: [0]}); } } } }); it("compiler-additional-props-4", function() { const schemas = [compile(` interface A { [propNames1: /^A+$/]: string; [propNames2: /^B+$/]?: string; } interface C extends A { [propNames3: /^C+$/]: number; [propNames4: /^D+$/]: number; } `), compile(` interface C extends A { [propNames3: /^C+$/]: number; [propNames4: /^D+$/]: number; } interface A { [propNames1: /^A+$/]: string; [propNames2: /^B+$/]?: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'A', 'C', ]); expect(Array.from(schemas[1].keys())).toEqual([ 'C', 'A', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [], additionalProps: [ [[/^A+$/], {kind: 'primitive', primitiveName: 'string'}, true], [[/^B+$/], {kind: 'optional', optional: {kind: 'primitive', primitiveName: 'string'}}, true], [[/^C+$/], {kind: 'primitive', primitiveName: 'number'}], [[/^D+$/], {kind: 'primitive', primitiveName: 'number'}], ], baseTypes: [{ name: 'A', typeName: 'A', kind: 'object', members: [], additionalProps: [ [[/^A+$/], {kind: 'primitive', primitiveName: 'string'}], [[/^B+$/], {kind: 'optional', optional: {kind: 'primitive', primitiveName: 'string'}}], ], }], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); expect(validate<any>({}, ty)).toEqual({value: {}}); expect(validate<any>({'A': ''}, ty)).toEqual({value: {'A': ''}}); expect(validate<any>({'A': 0}, ty)).toEqual(null); expect(validate<any>({'B': ''}, ty)).toEqual({value: {'B': ''}}); expect(validate<any>({'B': 0}, ty)).toEqual(null); expect(validate<any>({'C': ''}, ty)).toEqual(null); expect(validate<any>({'C': 0}, ty)).toEqual({value: {'C': 0}}); expect(validate<any>({'D': ''}, ty)).toEqual(null); expect(validate<any>({'D': 0}, ty)).toEqual({value: {'D': 0}}); expect(validate<any>({'E': ''}, ty)).toEqual({value: {'E': ''}}); expect(validate<any>({'E': 0}, ty)).toEqual({value: {'E': 0}}); expect(validate<any>({0: ''}, ty)).toEqual({value: {'0': ''}}); expect(validate<any>({0: 0}, ty)).toEqual({value: {'0': 0}}); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([''], ty)).toEqual({value: ['']}); expect(validate<any>([0], ty)).toEqual({value: [0]}); } } } }); it("compiler-additional-props-5a", function() { const schemas = [compile(` interface C { [propNames3: string]: number; [propNames4: number]: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'C', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [], additionalProps: [ [['string'], {kind: 'primitive', primitiveName: 'number'}], [['number'], {kind: 'primitive', primitiveName: 'string'}], ], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); expect(validate<any>({}, ty)).toEqual({value: {}}); expect(validate<any>({'A': ''}, ty)).toEqual(null); expect(validate<any>({'A': 0}, ty)).toEqual({value: {'A': 0}}); expect(validate<any>({'B': ''}, ty)).toEqual(null); expect(validate<any>({'B': 0}, ty)).toEqual({value: {'B': 0}}); expect(validate<any>({'C': ''}, ty)).toEqual(null); expect(validate<any>({'C': 0}, ty)).toEqual({value: {'C': 0}}); expect(validate<any>({0: ''}, ty)).toEqual({value: {'0': ''}}); // expect(validate<any>({0: 0}, ty)).toEqual(null); // TODO: expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([''], ty)).toEqual({value: ['']}); // expect(validate<any>([0], ty)).toEqual(null); // TODO: } } } }); it("compiler-additional-props-5b", function() { const schemas = [compile(` interface C { [propNames4: number]: string; [propNames3: string]: number; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'C', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [], additionalProps: [ [['number'], {kind: 'primitive', primitiveName: 'string'}], [['string'], {kind: 'primitive', primitiveName: 'number'}], ], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); expect(validate<any>({}, ty)).toEqual({value: {}}); expect(validate<any>({'A': ''}, ty)).toEqual(null); expect(validate<any>({'A': 0}, ty)).toEqual({value: {'A': 0}}); expect(validate<any>({'B': ''}, ty)).toEqual(null); expect(validate<any>({'B': 0}, ty)).toEqual({value: {'B': 0}}); expect(validate<any>({'C': ''}, ty)).toEqual(null); expect(validate<any>({'C': 0}, ty)).toEqual({value: {'C': 0}}); expect(validate<any>({0: ''}, ty)).toEqual({value: {'0': ''}}); // expect(validate<any>({0: 0}, ty)).toEqual(null); // TODO: expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([''], ty)).toEqual({value: ['']}); // expect(validate<any>([0], ty)).toEqual(null); // TODO: } } } }); it("compiler-additional-props-5c", function() { const schemas = [compile(` interface C { [propNames4: number]: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'C', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [], additionalProps: [ [['number'], {kind: 'primitive', primitiveName: 'string'}], ], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); expect(validate<any>({}, ty)).toEqual({value: {}}); expect(validate<any>({'A': ''}, ty)).toEqual(null); expect(validate<any>({'A': 0}, ty)).toEqual(null); expect(validate<any>({'B': ''}, ty)).toEqual(null); expect(validate<any>({'B': 0}, ty)).toEqual(null); expect(validate<any>({'C': ''}, ty)).toEqual(null); expect(validate<any>({'C': 0}, ty)).toEqual(null); expect(validate<any>({0: ''}, ty)).toEqual({value: {0: ''}}); expect(validate<any>({0: 0}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([''], ty)).toEqual({value: ['']}); expect(validate<any>([0], ty)).toEqual(null); } } } }); it("compiler-additional-props-5d", function() { const schemas = [compile(` interface C { [propNames4: number | string]: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'C', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [], additionalProps: [ [['number', 'string'], {kind: 'primitive', primitiveName: 'string'}], ], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); expect(validate<any>({}, ty)).toEqual({value: {}}); expect(validate<any>({'A': ''}, ty)).toEqual({value: {'A': ''}}); expect(validate<any>({'A': 0}, ty)).toEqual(null); expect(validate<any>({'B': ''}, ty)).toEqual({value: {'B': ''}}); expect(validate<any>({'B': 0}, ty)).toEqual(null); expect(validate<any>({'C': ''}, ty)).toEqual({value: {'C': ''}}); expect(validate<any>({'C': 0}, ty)).toEqual(null); expect(validate<any>({0: ''}, ty)).toEqual({value: {0: ''}}); expect(validate<any>({0: 0}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([''], ty)).toEqual({value: ['']}); expect(validate<any>([0], ty)).toEqual(null); } } } }); it("compiler-additional-props-6", function() { const schemas = [compile(` interface C { a?: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'C', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [ ['a', { name: 'a', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'string', }, }], ], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); expect(validate<any>({}, ty)).toEqual({value: {}}); expect(validate<any>({'a': ''}, ty)).toEqual({value: {'a': ''}}); expect(validate<any>({'a': 0}, ty)).toEqual(null); expect(validate<any>({'A': ''}, ty)).toEqual({value: {'A': ''}}); expect(validate<any>({'A': 0}, ty)).toEqual({value: {'A': 0}}); expect(validate<any>({'B': ''}, ty)).toEqual({value: {'B': ''}}); expect(validate<any>({'B': 0}, ty)).toEqual({value: {'B': 0}}); expect(validate<any>({'C': ''}, ty)).toEqual({value: {'C': ''}}); expect(validate<any>({'C': 0}, ty)).toEqual({value: {'C': 0}}); expect(validate<any>({0: ''}, ty)).toEqual({value: {0: ''}}); expect(validate<any>({0: 0}, ty)).toEqual({value: {0: 0}}); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([''], ty)).toEqual({value: ['']}); expect(validate<any>([0], ty)).toEqual({value: [0]}); } } } }); it("compiler-additional-props-6b", function() { const schemas = [compile(` interface C { a?: string; } `)]; { expect(Array.from(schemas[0].keys())).toEqual([ 'C', ]); } for (const schema of schemas) { { const rhs: TypeAssertion = { name: 'C', typeName: 'C', kind: 'object', members: [ ['a', { name: 'a', kind: 'optional', optional: { kind: 'primitive', primitiveName: 'string', }, }], ], }; // const ty = getType(schema, 'C'); for (const ty of [getType(deserialize(serialize(schema)), 'C'), getType(schema, 'C')]) { expect(ty).toEqual(rhs); expect(validate<any>({}, ty, {noAdditionalProps: true})).toEqual({value: {}}); expect(validate<any>({'a': ''}, ty, {noAdditionalProps: true})).toEqual({value: {'a': ''}}); expect(validate<any>({'a': 0}, ty, {noAdditionalProps: true})).toEqual(null); expect(validate<any>({'A': ''}, ty, {noAdditionalProps: true})).toEqual(null); expect(validate<any>({'A': 0}, ty, {noAdditionalProps: true})).toEqual(null); expect(validate<any>({'B': ''}, ty, {noAdditionalProps: true})).toEqual(null); expect(validate<any>({'B': 0}, ty, {noAdditionalProps: true})).toEqual(null); expect(validate<any>({'C': ''}, ty, {noAdditionalProps: true})).toEqual(null); expect(validate<any>({'C': 0}, ty, {noAdditionalProps: true})).toEqual(null); expect(validate<any>({0: ''}, ty, {noAdditionalProps: true})).toEqual(null); expect(validate<any>({0: 0}, ty, {noAdditionalProps: true})).toEqual(null); expect(validate<any>([], ty, {noAdditionalProps: true})).toEqual({value: []}); expect(validate<any>([''], ty, {noAdditionalProps: true})).toEqual(null); expect(validate<any>([0], ty, {noAdditionalProps: true})).toEqual(null); } } } }); });
the_stack
'use strict'; /** * Test Suite: AccessControl * @author Onur Yıldırım <onur@cutepilot.com> */ import { AccessControl } from '../src'; import { IQueryInfo, AccessControlError } from '../src/core'; import { utils, RESERVED_KEYWORDS } from '../src/utils'; // test helper import { helper } from './helper'; describe('Test Suite: AccessControl', () => { // grant list fetched from DB (to be converted to a valid grants object) let grantList: any[] = [ { role: 'admin', resource: 'video', action: 'create:any', attributes: ['*'] }, { role: 'admin', resource: 'video', action: 'read:any', attributes: ['*'] }, { role: 'admin', resource: 'video', action: 'update:any', attributes: ['*'] }, { role: 'admin', resource: 'video', action: 'delete:any', attributes: ['*'] }, { role: 'user', resource: 'video', action: 'create:own', attributes: '*, !id' }, // comma-separated attrs { role: 'user', resource: 'video', action: 'read:any', attributes: '*; !id' }, // semi-colon separated attrs { role: 'user', resource: 'video', action: 'update:own', attributes: ['*', '!id'] }, // Array attrs { role: 'user', resource: 'video', action: 'delete:own', attributes: ['*'] } ]; // valid grants object let grantsObject: any = { admin: { video: { 'create:any': ['*'], 'read:any': ['*'], 'update:any': ['*'], 'delete:any': ['*'] } }, user: { video: { 'create:own': ['*'], 'read:own': ['*'], 'update:own': ['*'], 'delete:own': ['*'] } } }; // let ac; // beforeEach (() => { // ac = new AccessControl(); // }); // --------------------------- // TESTS // --------------------------- test('throw on invalid grants object', () => { const ac = new AccessControl(); // `undefined` does/should not throw due to default value let invalid: any = [null, undefined, true, false, '', NaN, new Date(), () => { }]; invalid.forEach(o => { helper.expectACError(() => new AccessControl(o)); helper.expectACError(() => ac.setGrants(o)); }); // omitting is allowed (results in empty grants object: {}) expect(() => new AccessControl()).not.toThrow(); // empty object is allowed expect(() => new AccessControl({})).not.toThrow(); expect(new AccessControl({}).getGrants()).toEqual({}); // explicit undefined is not allowed helper.expectACError(() => new AccessControl(undefined)); // Initial Grants as an Object // ---------------------------- // reserved keywords helper.expectACError(() => ac.setGrants({ '$': {} })); helper.expectACError(() => ac.setGrants({ '$extend': {} })); // if $extend is set to an array of strings or empty array, it's valid // (contains inherited roles) expect(() => ac.setGrants({ 'admin': { '$extend': [] } })).not.toThrow(); // empty string in the $extend array is not allowed helper.expectACError(() => ac.setGrants({ 'admin': { '$extend': [''] } })); // role definition must be an object invalid = [[], undefined, null, true, new Date]; invalid.forEach(o => { helper.expectACError(() => ac.setGrants({ role: invalid })); }); // resource definition must be an object invalid.forEach(o => { helper.expectACError(() => ac.setGrants({ role: { resource: invalid } })); }); // actions should be one of Action enumeration (with or without possession) helper.expectACError(() => ac.setGrants({ role: { resource: { 'invalid': [] } } })); helper.expectACError(() => ac.setGrants({ role: { resource: { 'remove:any': [] } } })); // missing colon helper.expectACError(() => ac.setGrants({ role: { resource: { 'createany': [] } } })); // action/possession is ok but value is invalid invalid = [undefined, null, true, new Date, {}]; invalid.forEach(o => { helper.expectACError(() => ac.setGrants({ role: { resource: { 'create:any': invalid } } })); }); // Initial Grants as an Array // ---------------------------- // empty array is allowed. a flat list will be converted to inner grants // object. empty array results in {}. expect(() => new AccessControl([])).not.toThrow(); expect(new AccessControl([]).getGrants()).toEqual({}); // array should be an array of objects helper.expectACError(() => ac.setGrants([[]])); // no empty grant items helper.expectACError(() => ac.setGrants([{}])); // e.g. $extend is not allowed for role or resource names. it's a reserved keyword. RESERVED_KEYWORDS.forEach(name => { helper.expectACError(() => ac.setGrants([{ role: name, resource: 'video', action: 'create:any' }])); helper.expectACError(() => ac.setGrants([{ role: 'admin', resource: name, action: 'create:any' }])); helper.expectACError(() => ac.setGrants([{ role: 'admin', resource: 'video', action: name }])); }); // attributes property can be omitted expect(() => ac.setGrants([{ role: 'admin', resource: 'video', action: 'create:any' }])).not.toThrow(); // role, resource or action properties cannot be omitted helper.expectACError(() => ac.setGrants([{ resource: 'video', action: 'create:any' }])); helper.expectACError(() => ac.setGrants([{ role: 'admin', resource: 'video' }])); helper.expectACError(() => ac.setGrants([{ role: 'admin', action: 'create:any' }])); }); test('construct with grants array or object, output a grants object', () => { let ac = new AccessControl(grantList); let grants = ac.getGrants(); expect(utils.type(grants)).toEqual('object'); expect(utils.type(grants.admin)).toEqual('object'); expect(grants.admin.video['create:any']).toEqual(expect.any(Array)); // console.log(grants); ac = new AccessControl(grantsObject); grants = ac.getGrants(); expect(utils.type(grants)).toEqual('object'); expect(utils.type(grants.admin)).toEqual('object'); expect(grants.admin.video['create:any']).toEqual(expect.any(Array)); grants = { 'user': { 'account': { 'read:own': ['*'] } }, 'admin': { '$extend': ['user'] } }; ac = new AccessControl(grants); expect(utils.type(grants)).toEqual('object'); expect(ac.can('user').readOwn('account').granted).toBe(true); expect(ac.can('user').readOwn('account').attributes).toEqual(['*']); expect(ac.can('admin').readOwn('account').granted).toBe(true); expect(ac.can('admin').readOwn('account').attributes).toEqual(['*']); }); test('reset grants with #reset() only', () => { let ac = new AccessControl(grantsObject); expect(ac.getRoles().length).toBeGreaterThan(0); // make sure not empty helper.expectACError(() => (ac as any).setGrants()); helper.expectACError(() => ac.setGrants(null)); helper.expectACError(() => ac.setGrants(undefined)); expect(ac.reset().getGrants()).toEqual({}); expect(ac.setGrants({}).getGrants()).toEqual({}); }); test('add grants from flat list (db), check/remove roles and resources', () => { const ac = new AccessControl(); expect((ac as any).hasRole()).toEqual(false); expect(ac.hasRole(null)).toEqual(false); expect(ac.hasRole(undefined)).toEqual(false); expect(ac.hasRole('')).toEqual(false); expect((ac as any).hasResource()).toEqual(false); expect(ac.hasResource(null)).toEqual(false); expect(ac.hasResource(undefined)).toEqual(false); expect(ac.hasResource('')).toEqual(false); ac.setGrants(grantList.concat()); // console.log('grants', ac.getGrants()); // console.log('resources', ac.getResources()); // console.log('roles', ac.getRoles()); // comma/semi-colon separated should be turned into string arrays let attrs1 = ac.can('user').createOwn('video').attributes; let attrs2 = ac.can('user').readAny('video').attributes; let attrs3 = ac.query('user').updateOwn('video').attributes; // `query` » alias of `can` // console.log(attrs1); expect(attrs1.length).toEqual(2); expect(attrs2.length).toEqual(2); expect(attrs3.length).toEqual(2); // check roles & resources expect(ac.getRoles().length).toEqual(2); expect(ac.getResources().length).toEqual(1); expect(ac.hasRole('admin')).toEqual(true); expect(ac.hasRole('user')).toEqual(true); expect(ac.hasRole(['user', 'admin'])).toEqual(true); expect(ac.hasRole(['user', 'moderator'])).toEqual(false); expect(ac.hasRole('moderator')).toEqual(false); expect(ac.hasResource('video')).toEqual(true); expect(ac.hasResource(['video', 'photo'])).toEqual(false); ac.grant('admin').create('image'); expect(ac.hasResource(['video', 'image'])).toEqual(true); // removeRoles should also accept a string ac.removeRoles('admin'); expect(ac.hasRole('admin')).toEqual(false); // throw on nonexisting role helper.expectACError(() => ac.removeRoles([])); helper.expectACError(() => ac.removeRoles([''])); helper.expectACError(() => ac.removeRoles(['none'])); // no role named moderator helper.expectACError(() => ac.removeRoles(['user', 'moderator'])); expect(ac.getRoles().length).toEqual(0); // removeRoles should accept a string or array ac.removeResources(['video']); expect(ac.getResources().length).toEqual(0); expect(ac.hasResource('video')).toEqual(false); }); test('#removeResources(), #_removePermission()', () => { const ac = new AccessControl(); function grantAll() { ac.grant(['user', 'admin']).create('photo').createOwn('photo'); expect(ac.can('admin').createAny('photo').granted).toEqual(true); expect(ac.can('user').createAny('photo').granted).toEqual(true); expect(ac.can('admin').createOwn('photo').granted).toEqual(true); expect(ac.can('user').createOwn('photo').granted).toEqual(true); } grantAll(); // removeResources() is like an alias without the third argument of _removePermission(). (ac as any).removeResources('photo', 'user'); expect(ac.can('admin').createAny('photo').granted).toEqual(true); expect(ac.can('user').createAny('photo').granted).toEqual(false); expect(ac.can('user').createOwn('photo').granted).toEqual(false); expect(ac.getGrants().user.photo).toBeUndefined(); helper.expectACError(() => (ac as any)._removePermission(null)); helper.expectACError(() => (ac as any)._removePermission('')); helper.expectACError(() => (ac as any)._removePermission([])); helper.expectACError(() => (ac as any)._removePermission([''])); grantAll(); helper.expectACError(() => (ac as any)._removePermission('photo', '')); helper.expectACError(() => (ac as any)._removePermission(['photo'], null)); helper.expectACError(() => (ac as any)._removePermission('photo', [])); helper.expectACError(() => (ac as any)._removePermission('photo', [''])); // passing the third argument (actionPossession) grantAll(); (ac as any)._removePermission('photo', 'user', 'create'); expect(ac.can('admin').createAny('photo').granted).toEqual(true); expect(ac.can('user').createAny('photo').granted).toEqual(false); expect(ac.can('user').createOwn('photo').granted).toEqual(true); expect(ac.getGrants().user.photo).toBeDefined(); }); test('grant/deny access and check permissions', () => { const ac = new AccessControl(), attrs = ['*', '!size']; ac.grant('user').createAny('photo', attrs); expect(ac.getGrants().user.photo['create:any']).toEqual(attrs); expect(ac.can('user').createAny('photo').attributes).toEqual(attrs); ac.deny('user').createAny('photo', attrs); // <- denied even with attrs expect(ac.can('user').createAny('photo').granted).toEqual(false); expect(ac.can('user').createAny('photo').attributes).toEqual([]); ac.grant('user').createOwn('photo', attrs); // console.log('ac.getGrants()', ac.getGrants()); expect(ac.getGrants().user.photo['create:own']).toEqual(attrs); expect(ac.can('user').createOwn('photo').attributes).toEqual(attrs); // grant multiple roles the same permission for the same resource ac.grant(['user', 'admin']).readAny('photo', attrs); expect(ac.can('user').readAny('photo').granted).toEqual(true); expect(ac.can('admin').readAny('photo').granted).toEqual(true); // deny multiple roles (comma-separated) the same permission for the same resource ac.deny('user, admin').readAny('photo'); expect(ac.can('user').readAny('photo').granted).toEqual(false); expect(ac.can('admin').readAny('photo').granted).toEqual(false); ac.grant('user').updateAny('photo', attrs); expect(ac.getGrants().user.photo['update:any']).toEqual(attrs); expect(ac.can('user').updateAny('photo').attributes).toEqual(attrs); ac.grant('user').updateOwn('photo', attrs); expect(ac.getGrants().user.photo['update:own']).toEqual(attrs); expect(ac.can('user').updateOwn('photo').attributes).toEqual(attrs); ac.grant('user').deleteAny('photo', attrs); expect(ac.getGrants().user.photo['delete:any']).toEqual(attrs); expect(ac.can('user').deleteAny('photo').attributes).toEqual(attrs); ac.grant('user').deleteOwn('photo', attrs); expect(ac.getGrants().user.photo['delete:own']).toEqual(attrs); expect(ac.can('user').deleteOwn('photo').attributes).toEqual(attrs); // `query` » alias of `can` expect(ac.query('user').updateAny('photo').attributes).toEqual(attrs); expect(ac.query('user').deleteAny('photo').attributes).toEqual(attrs); expect(ac.query('user').deleteOwn('photo').attributes).toEqual(attrs); }); test('explicit undefined', () => { const ac = new AccessControl(); helper.expectACError(() => (ac as any).grant(undefined)); helper.expectACError(() => (ac as any).deny(undefined)); helper.expectACError(() => (ac as any).can(undefined)); helper.expectACError(() => (ac as any).query(undefined)); }); test('aliases: #allow(), #reject(), #query()', () => { const ac = new AccessControl(); ac.grant(['user', 'admin']).createAny('photo'); expect(ac.can('user').createAny('photo').granted).toBe(true); ac.reset(); // allow » alias of grant ac.allow(['user', 'admin']).createAny('photo'); // query » alias of can expect(ac.query('user').createAny('photo').granted).toBe(true); // reject » alias of deny ac.reject('user').createAny('photo'); expect(ac.query('user').createAny('photo').granted).toBe(false); expect(ac.can('user').createAny('photo').granted).toBe(false); }); test('#permission()', () => { const ac = new AccessControl(grantsObject); expect(ac.can('admin').createAny('video').granted).toBe(true); let queryInfo: IQueryInfo = { role: 'admin', resource: 'video', action: 'create:any' }; expect(ac.permission(queryInfo).granted).toBe(true); queryInfo.role = 'user'; expect(ac.permission(queryInfo).granted).toBe(false); queryInfo.action = 'create:own'; expect(ac.permission(queryInfo).granted).toBe(true); }); test('chain grant methods and check permissions', () => { const ac = new AccessControl(), attrs = ['*']; ac.grant('superadmin') .createAny('profile', attrs) .readAny('profile', attrs) .createAny('video', []) // no attributes allowed .createAny('photo'); // all attributes allowed expect(ac.can('superadmin').createAny('profile').granted).toEqual(true); expect(ac.can('superadmin').readAny('profile').granted).toEqual(true); expect(ac.can('superadmin').createAny('video').granted).toEqual(false); expect(ac.can('superadmin').createAny('photo').granted).toEqual(true); }); test('grant/deny access via object and check permissions', () => { const ac = new AccessControl(), attrs = ['*']; let o1 = { role: 'moderator', resource: 'post', action: 'create:any', // action:possession attributes: ['*'] // grant only }; let o2 = { role: 'moderator', resource: 'news', action: 'read', // separate action possession: 'own', // separate possession attributes: ['*'] // grant only }; let o3 = { role: 'moderator', resource: 'book', // no action/possession set attributes: ['*'] // grant only }; ac.grant(o1).grant(o2); ac.grant(o3).updateAny(); expect(ac.can('moderator').createAny('post').granted).toEqual(true); expect(ac.can('moderator').readOwn('news').granted).toEqual(true); expect(ac.can('moderator').updateAny('book').granted).toEqual(true); ac.deny(o1).deny(o2); ac.deny(o3).updateAny(); expect(ac.can('moderator').createAny('post').granted).toEqual(false); expect(ac.can('moderator').readOwn('news').granted).toEqual(false); expect(ac.can('moderator').updateAny('book').granted).toEqual(false); // should overwrite already defined action/possession in o1 object ac.grant(o1).readOwn(); expect(ac.can('moderator').readOwn('post').granted).toEqual(true); ac.deny(o1).readOwn(); expect(ac.can('moderator').readOwn('post').granted).toEqual(false); // non-set action (update:own) expect(ac.can('moderator').updateOwn('news').granted).toEqual(false); // non-existent resource expect(ac.can('moderator').createAny('foo').granted).toEqual(false); }); test('grant/deny access (variation, chained)', () => { const ac = new AccessControl(); ac.setGrants(grantsObject); expect(ac.can('admin').createAny('video').granted).toEqual(true); ac.deny('admin').create('video'); expect(ac.can('admin').createAny('video').granted).toEqual(false); ac.grant('foo').createOwn('bar'); expect(ac.can('foo').createAny('bar').granted).toEqual(false); expect(ac.can('foo').createOwn('bar').granted).toEqual(true); ac.grant('foo').create('baz', []); // no attributes, actually denied instead of granted expect(ac.can('foo').create('baz').granted).toEqual(false); ac.grant('qux') .createOwn('resource1') .updateOwn('resource2') .readAny('resource1') .deleteAny('resource1', []); expect(ac.can('qux').createOwn('resource1').granted).toEqual(true); expect(ac.can('qux').updateOwn('resource2').granted).toEqual(true); expect(ac.can('qux').readAny('resource1').granted).toEqual(true); expect(ac.can('qux').deleteAny('resource1').granted).toEqual(false); ac.deny('qux') .createOwn('resource1') .updateOwn('resource2') .readAny('resource1') .deleteAny('resource1', []); expect(ac.can('qux').createOwn('resource1').granted).toEqual(false); expect(ac.can('qux').updateOwn('resource2').granted).toEqual(false); expect(ac.can('qux').readAny('resource1').granted).toEqual(false); expect(ac.can('qux').deleteAny('resource1').granted).toEqual(false); ac.grant('editor').resource('file1').updateAny(); ac.grant().role('editor').updateAny('file2'); ac.grant().role('editor').resource('file3').updateAny(); expect(ac.can('editor').updateAny('file1').granted).toEqual(true); expect(ac.can('editor').updateAny('file2').granted).toEqual(true); expect(ac.can('editor').updateAny('file3').granted).toEqual(true); ac.deny('editor').resource('file1').updateAny(); ac.deny().role('editor').updateAny('file2'); ac.deny().role('editor').resource('file3').updateAny(); expect(ac.can('editor').updateAny('file1').granted).toEqual(false); expect(ac.can('editor').updateAny('file2').granted).toEqual(false); expect(ac.can('editor').updateAny('file3').granted).toEqual(false); ac.grant('editor') .resource('fileX').readAny().createOwn() .resource('fileY').updateOwn().deleteOwn(); expect(ac.can('editor').readAny('fileX').granted).toEqual(true); expect(ac.can('editor').createOwn('fileX').granted).toEqual(true); expect(ac.can('editor').updateOwn('fileY').granted).toEqual(true); expect(ac.can('editor').deleteOwn('fileY').granted).toEqual(true); ac.deny('editor') .resource('fileX').readAny().createOwn() .resource('fileY').updateOwn().deleteOwn(); expect(ac.can('editor').readAny('fileX').granted).toEqual(false); expect(ac.can('editor').createOwn('fileX').granted).toEqual(false); expect(ac.can('editor').updateOwn('fileY').granted).toEqual(false); expect(ac.can('editor').deleteOwn('fileY').granted).toEqual(false); }); test('switch-chain grant/deny roles', () => { const ac = new AccessControl(); ac.grant('r1') .createOwn('a') .grant('r2') .createOwn('b') .readAny('b') .deny('r1') .deleteAny('b') .grant('r1') .updateAny('c') .deny('r2') .readAny('c'); expect(ac.can('r1').createOwn('a').granted).toEqual(true); expect(ac.can('r1').deleteAny('b').granted).toEqual(false); expect(ac.can('r1').updateAny('c').granted).toEqual(true); expect(ac.can('r2').createOwn('b').granted).toEqual(true); expect(ac.can('r2').readAny('b').granted).toEqual(true); expect(ac.can('r2').readAny('c').granted).toEqual(false); // console.log(JSON.stringify(ac.getGrants(), null, ' ')); }); test('Access#deny() should set attributes to []', () => { const ac = new AccessControl(); ac.deny('user').createAny('book', ['*']); expect(ac.getGrants().user.book['create:any']).toEqual([]); }); test('grant comma/semi-colon separated roles', () => { const ac = new AccessControl(); // also supporting comma/semi-colon separated roles ac.grant('role2; role3, editor; viewer, agent').createOwn('book'); expect(ac.hasRole('role3')).toEqual(true); expect(ac.hasRole('editor')).toEqual(true); expect(ac.hasRole('agent')).toEqual(true); }); test('Permission#roles, Permission#resource', () => { const ac = new AccessControl(); // also supporting comma/semi-colon separated roles ac.grant('foo, bar').createOwn('baz'); expect(ac.can('bar').createAny('baz').granted).toEqual(false); expect(ac.can('bar').createOwn('baz').granted).toEqual(true); // returned permission should provide queried role(s) as array expect(ac.can('foo').create('baz').roles).toContain('foo'); // returned permission should provide queried resource expect(ac.can('foo').create('baz').resource).toEqual('baz'); // create is createAny. but above only returns the queried value, not the result. }); test('#extendRole(), #removeRoles(), Access#extend()', () => { const ac = new AccessControl(); ac.grant('admin').createOwn('book'); // role "onur" is not found expect(() => ac.extendRole('onur', 'admin')).toThrow(); ac.grant('onur').extend('admin'); expect(ac.getGrants().onur.$extend.length).toEqual(1); expect(ac.getGrants().onur.$extend[0]).toEqual('admin'); ac.grant('role2, role3, editor, viewer, agent').createOwn('book'); ac.extendRole('onur', ['role2', 'role3']); expect(ac.getGrants().onur.$extend).toEqual(['admin', 'role2', 'role3']); ac.grant('admin').extend('editor'); expect(ac.getGrants().admin.$extend).toEqual(['editor']); ac.grant('admin').extend(['viewer', 'editor', 'agent']).readAny('video'); expect(ac.getGrants().admin.$extend).toContain('editor'); expect(ac.getGrants().admin.$extend).toEqual(['editor', 'viewer', 'agent']); ac.grant(['editor', 'agent']).extend(['role2', 'role3']).updateOwn('photo'); expect(ac.getGrants().editor.$extend).toEqual(['role2', 'role3']); expect(ac.getGrants().agent.$extend).toEqual(['role2', 'role3']); ac.removeRoles(['editor', 'agent']); expect(ac.getGrants().editor).toBeUndefined(); expect(ac.getGrants().agent).toBeUndefined(); expect(ac.getGrants().admin.$extend).not.toContain('editor'); expect(ac.getGrants().admin.$extend).not.toContain('agent'); expect(() => ac.grant('roleX').extend('roleX')).toThrow(); expect(() => ac.grant(['admin2', 'roleX']).extend(['roleX', 'admin3'])).toThrow(); // console.log(JSON.stringify(ac.getGrants(), null, ' ')); }); test('extend before or after resource permissions are granted', () => { let ac; function init() { ac = new AccessControl(); // create the roles ac.grant(['user', 'admin']); expect(ac.getRoles().length).toEqual(2); } // case #1 init(); ac.grant('admin').extend('user') // assuming user role already exists .grant('user').createOwn('video'); expect(ac.can('admin').createOwn('video').granted).toEqual(true); // case #2 init(); ac.grant('user').createOwn('video') .grant('admin').extend('user'); expect(ac.can('admin').createOwn('video').granted).toEqual(true); }); test('extend multi-level (deep) roles', () => { let ac = new AccessControl(); ac.grant('viewer').readAny('devices'); ac.grant('ops').extend('viewer').updateAny('devices', ['*', '!id']); ac.grant('admin').extend('ops').deleteAny('devices'); ac.grant('superadmin').extend(['admin', 'ops']).createAny('devices'); // just re-extending already extended roles. this should pass. expect(() => ac.extendRole(['ops', 'admin'], 'viewer')).not.toThrow(); expect(ac.can('ops').readAny('devices').granted).toEqual(true); expect(ac.can('admin').readAny('devices').granted).toEqual(true); expect(ac.can('admin').updateAny('devices').granted).toEqual(true); expect(ac.can('superadmin').readAny('devices').granted).toEqual(true); expect(ac.can('superadmin').updateAny('devices').attributes).toEqual(['*', '!id']); ac.grant('superadmin').updateAny('devices', ['*']); expect(ac.can('superadmin').updateAny('devices').attributes).toEqual(['*']); expect(ac.getInheritedRolesOf('viewer')).toEqual([]) expect(ac.getInheritedRolesOf('ops')).toEqual(['viewer']) expect(ac.getInheritedRolesOf('admin')).toEqual(['ops', 'viewer']) expect(ac.getInheritedRolesOf('superadmin')).toEqual(['admin', 'ops', 'viewer']) // console.log(JSON.stringify(ac.getGrants(), null, ' ')); }); test('throw if target role or inherited role does not exit', () => { const ac = new AccessControl(); helper.expectACError(() => ac.grant().createOwn()); ac.setGrants(grantsObject); helper.expectACError(() => ac.can('invalid-role').createOwn('video'), 'Role not found'); helper.expectACError(() => ac.grant('user').extend('invalid-role')); helper.expectACError(() => ac.grant('user').extend(['invalid1', 'invalid2'])); }); test('throw on invalid or reserved names', () => { const ac = new AccessControl(); RESERVED_KEYWORDS.forEach(name => { helper.expectACError(() => ac.grant(name)); helper.expectACError(() => ac.deny(name)); helper.expectACError(() => ac.grant().role(name)); helper.expectACError(() => ac.grant('role').resource(name)); }); expect(() => ac.grant()).not.toThrow(); // omitted. helper.expectACError(() => ac.grant(undefined)); // explicit undefined helper.expectACError(() => ac.grant(null)); helper.expectACError(() => ac.grant('')); helper.expectACError(() => (ac as any).grant(1)); helper.expectACError(() => (ac as any).grant(true)); helper.expectACError(() => (ac as any).grant(false)); helper.expectACError(() => (ac as any).grant([])); helper.expectACError(() => (ac as any).grant({})); helper.expectACError(() => new AccessControl({ $: [] })); helper.expectACError(() => new AccessControl({ $extend: {} })); }); test('init with grants object with $extend (issue #22)', () => { // tslint:disable const grants = { "viewer": { "account": { "read:own": ["*"] } }, "user": { "$extend": ["viewer"], "account": { "update:own": ['*'] } }, "admin": { "$extend": ["user"], "account": { "create:any": ["*"], "delete:any": ["*"] } } }; // tslint:enable expect(() => new AccessControl(grants)).not.toThrow(); let ac = new AccessControl(); expect(() => ac.setGrants(grants)).not.toThrow(); // store grants (1) to a constant. const grants1 = ac.getGrants(); // ensure to reset grants ac.reset(); expect(ac.getGrants()).toEqual({}); // now build the same grants via chained methods... ac.grant('viewer').readOwn('account') .grant('user').extend('viewer').updateOwn('account') .grant('admin').extend('user').create('account').delete('account'); const grants2 = ac.getGrants(); // and compare... expect(grants1).toEqual(grants2); }); test('throw if a role attempts to extend itself', () => { let ac = new AccessControl(); helper.expectACError(() => ac.grant('user').extend('user')); const grants = { 'user': { '$extend': ['user'] } }; helper.expectACError(() => new AccessControl(grants)); ac = new AccessControl(); helper.expectACError(() => ac.setGrants(grants)); }); test('throw on cross-role inheritance', () => { // test with chained methods let ac = new AccessControl(); ac.grant(['user', 'admin']).createOwn('video'); // make sure roles are created expect(ac.getRoles().length).toEqual(2); // direct cross-inheritance test ac.grant('admin').extend('user'); helper.expectACError(() => ac.grant('user').extend('admin')); // deeper cross-inheritance test ac.grant(['editor', 'viewer', 'sa']).createOwn('image'); ac.grant('sa').extend('editor'); ac.grant('editor').extend('viewer'); helper.expectACError(() => ac.grant('viewer').extend('sa')); // test with initial grants object // direct cross-inheritance test // user » admin » user let grants: any = { 'user': { '$extend': ['admin'] }, 'admin': { '$extend': ['user'] } }; helper.expectACError(() => new AccessControl(grants)); ac = new AccessControl(); helper.expectACError(() => ac.setGrants(grants)); // deeper cross-inheritance test // user » sa » editor » viewer » user grants = { 'user': { '$extend': ['sa'] }, 'sa': { '$extend': ['editor'] }, 'editor': { '$extend': ['viewer'] }, 'viewer': { '$extend': ['user'] } }; helper.expectACError(() => new AccessControl(grants)); ac = new AccessControl(); helper.expectACError(() => ac.setGrants(grants)); // viewer » editor » user » sa » editor grants = { 'user': { '$extend': ['sa'] }, 'sa': { '$extend': ['editor'] }, 'editor': { '$extend': ['user'] }, 'viewer': { '$extend': ['editor'] } }; helper.expectACError(() => new AccessControl(grants)); ac = new AccessControl(); helper.expectACError(() => ac.setGrants(grants)); }); test('throw if grant or deny objects are invalid', () => { const ac = new AccessControl(); let o; o = { role: '', // invalid role, should be non-empty string or array resource: 'post', action: 'create:any', attributes: ['*'] // grant only }; expect(() => ac.grant(o)).toThrow(); expect(() => ac.deny(o)).toThrow(); o = { role: 'moderator', resource: null, // invalid resource, should be non-empty string action: 'create:any', attributes: ['*'] // grant only }; expect(() => ac.grant(o)).toThrow(); expect(() => ac.deny(o)).toThrow(); o = { role: 'admin', resource: 'post', action: 'put:any', // invalid action, should be create|read|update|delete attributes: ['*'] // grant only }; expect(() => ac.grant(o)).toThrow(); expect(() => ac.deny(o)).toThrow(); o = { role: 'admin', resource: 'post', action: null, // invalid action, should be create|read|update|delete attributes: ['*'] // grant only }; expect(() => ac.grant(o)).toThrow(); expect(() => ac.deny(o)).toThrow(); o = { role: 'admin', resource: 'post', action: 'create:all', // invalid possession, should be any|own or omitted attributes: ['*'] // grant only }; expect(() => ac.grant(o)).toThrow(); expect(() => ac.deny(o)).toThrow(); o = { role: 'admin2', resource: 'post', action: 'create', // possession omitted, will be set to any attributes: ['*'] // grant only }; expect(() => ac.grant(o)).not.toThrow(); expect(ac.can('admin2').createAny('post').granted).toEqual(true); // possession "any" will also return granted=true for "own" expect(ac.can('admin2').createOwn('post').granted).toEqual(true); expect(() => ac.deny(o)).not.toThrow(); }); test('Check with multiple roles changes grant list (issue #2)', () => { const ac = new AccessControl(); ac.grant('admin').updateAny('video') .grant(['user', 'admin']).updateOwn('video'); // Admin can update any video expect(ac.can(['admin']).updateAny('video').granted).toEqual(true); // console.log('grants before', JSON.stringify(ac.getGrants(), null, ' ')); // This check actually changes the underlying grants ac.can(['user', 'admin']).updateOwn('video'); // console.log('grants after', JSON.stringify(ac.getGrants(), null, ' ')); // Admin can update any or own video expect(ac.can(['admin']).updateAny('video').granted).toEqual(true); expect(ac.can(['admin']).updateOwn('video').granted).toEqual(true); }); test('grant/deny multiple roles and multiple resources', () => { const ac = new AccessControl(); ac.grant('admin, user').createAny('profile, video'); expect(ac.can('admin').createAny('profile').granted).toEqual(true); expect(ac.can('admin').createAny('video').granted).toEqual(true); expect(ac.can('user').createAny('profile').granted).toEqual(true); expect(ac.can('user').createAny('video').granted).toEqual(true); ac.grant('admin, user').createAny('profile, video', '*,!id'); expect(ac.can('admin').createAny('profile').attributes).toEqual(['*', '!id']); expect(ac.can('admin').createAny('video').attributes).toEqual(['*', '!id']); expect(ac.can('user').createAny('profile').attributes).toEqual(['*', '!id']); expect(ac.can('user').createAny('video').attributes).toEqual(['*', '!id']); ac.deny('admin, user').readAny('photo, book', '*,!id'); expect(ac.can('admin').readAny('photo').attributes).toEqual([]); expect(ac.can('admin').readAny('book').attributes).toEqual([]); expect(ac.can('user').readAny('photo').attributes).toEqual([]); expect(ac.can('user').readAny('book').attributes).toEqual([]); expect(ac.can('user').createAny('non-existent').granted).toEqual(false); // console.log(JSON.stringify(ac.getGrants(), null, ' ')); }); test('Permission#filter()', () => { let ac = new AccessControl(); let attrs = ['*', '!account.balance.credit', '!account.id', '!secret']; let data: any = { name: 'Company, LTD.', address: { city: 'istanbul', country: 'TR' }, account: { id: 33, taxNo: 12345, balance: { credit: 100, deposit: 0 } }, secret: { value: 'hidden' } }; ac.grant('user').createOwn('company', attrs); let permission = ac.can('user').createOwn('company'); expect(permission.granted).toEqual(true); let filtered = permission.filter(data); expect(filtered.name).toEqual(expect.any(String)); expect(filtered.address).toEqual(expect.any(Object)); expect(filtered.address.city).toEqual('istanbul'); expect(filtered.account).toBeDefined(); expect(filtered.account.id).toBeUndefined(); expect(filtered.account.balance).toBeDefined(); expect(filtered.account.credit).toBeUndefined(); expect(filtered.secret).toBeUndefined(); ac.deny('user').createOwn('company'); permission = ac.can('user').createOwn('company'); expect(permission.granted).toEqual(false); filtered = permission.filter(data); expect(filtered).toEqual({}); // filtering array of objects ac = new AccessControl(); attrs = ['*', '!id']; data = [ { id: 1, name: 'x', age: 30 }, { id: 2, name: 'y', age: 31 }, { id: 3, name: 'z', age: 32 } ]; ac.grant('user') .createOwn('account', ['*']) .updateOwn('account', attrs); permission = ac.can('user').updateOwn('account'); filtered = permission.filter(data); expect(filtered).toEqual(expect.any(Array)); expect(filtered.length).toEqual(data.length); }); test('union granted attributes for extended roles, on query', () => { const ac = new AccessControl(); const restrictedAttrs = ['*', '!id', '!pwd']; // grant user restricted attrs ac.grant('user').updateAny('video', restrictedAttrs) // extend admin with user as is (same attributes) .grant('admin').extend('user'); // admin should have the same restricted attributes expect(ac.can('admin').updateAny('video').attributes).toEqual(restrictedAttrs); // grant admin unrestricted attrs (['*']) ac.grant('admin').updateAny('video'); // union'ed attributes should be ['*'] expect(ac.can('admin').updateAny('video').attributes).toEqual(['*']); ac.grant('editor').updateAny('video', ['*', '!pwd', 'title']).extend('user'); // 'title' is redundant since we have '*'. // '!pwd' exists in both attribute lists, so it should exist in union. expect(ac.can('editor').updateAny('video').attributes).toEqual(['*', '!pwd']); ac.grant('role1').createOwn('photo', ['image', 'name']) .grant('role2').createOwn('photo', ['name', '!location']) // '!location' is redundant here .grant('role3').createOwn('photo', ['*', '!location']) .grant('role4').extend(['role1', 'role2']) .grant('role5').extend(['role1', 'role2', 'role3']); // console.log(ac.can('role4').createOwn('photo').attributes); // expect(ac.can('role4').createOwn('photo').attributes).toEqual(['image', 'name']); expect(ac.can('role5').createOwn('photo').attributes).toEqual(['*', '!location']); }); test('AccessControl.filter()', () => { let o = { name: 'John', age: 30, account: { id: 1, country: 'US' } }; let x = AccessControl.filter(o, ['*', '!account.id', '!age']); expect(x.name).toEqual('John'); expect(x.account.id).toBeUndefined(); expect(x.account.country).toEqual('US'); expect(o.account.id).toEqual(1); expect(o).not.toEqual(x); }); test('AccessControl#lock(), Access#lock()', () => { let ac; function _inoperative() { helper.expectACError(() => ac.setGrants({})); helper.expectACError(() => ac.reset()); helper.expectACError(() => ac.grant('editor')); helper.expectACError(() => ac.deny('admin')); helper.expectACError(() => ac.extendRole('admin', 'user')); helper.expectACError(() => ac.removeRoles(['admin'])); helper.expectACError(() => ac.removeResources(['video'])); expect(() => (ac as any)._grants.hacker = { 'account': { 'read:any': ['*'] } }).toThrow(); expect(ac.hasRole('hacker')).toBe(false); } function _operative() { expect(ac.getRoles()).toContain('user'); expect(ac.getRoles()).toContain('admin'); expect(ac.getResources()).toContain('video'); expect(ac.getExtendedRolesOf('admin')).not.toContain('user'); } function _test() { _inoperative(); _operative(); } // locking with Access#lock ac = new AccessControl(); ac.grant('user').createAny('video') .grant('admin').createAny('photo') .lock(); _test(); // locking with AccessControl#lock ac = new AccessControl(); ac.grant('user').createAny('video') .grant('admin').createAny('photo'); ac.lock(); _test(); // locking when grants not specified ac = new AccessControl(); helper.expectACError(() => ac.lock()); // cannot lock empty grants ac.setGrants({ 'admin': { 'account': { } } }).lock(); _inoperative(); // locking when grants are _isLocked is altered ac = new AccessControl(); ac.setGrants({ 'admin': { 'account': {} } }); ac._isLocked = true; ac.lock(); _inoperative(); // locking when grants are shallow frozen ac = new AccessControl({ 'admin': { 'account': {} } }); Object.freeze((ac as any)._grants); ac.lock(); helper.expectACError(() => ac.removeResources(['account'])); _inoperative(); // locking when grants are shallow frozen and _isLocked is altered ac = new AccessControl({ 'admin': { 'account': {} } }); ac._isLocked = true; Object.freeze((ac as any)._grants); ac.lock(); helper.expectACError(() => ac.removeResources(['account'])); _inoperative(); }); test('Action / Possession enumerations', () => { expect(AccessControl.Action).toEqual(expect.any(Object)); expect(AccessControl.Possession).toEqual(expect.any(Object)); expect(AccessControl.Possession.ANY).toBe('any'); expect(AccessControl.Possession.OWN).toBe('own'); }); test('AccessControlError', () => { helper.expectACError(() => { throw new AccessControl.Error(); }); helper.expectACError(() => { throw new AccessControlError(); }); expect(new AccessControlError().message).toEqual(''); }); });
the_stack
import { HttpClient } from '@angular/common/http'; import { Store } from '@ngrx/store'; import { compare, Operation } from 'fast-json-patch'; import { Observable, of as observableOf } from 'rxjs'; import { NotificationsService } from '../../shared/notifications/notifications.service'; import { followLink } from '../../shared/utils/follow-link-config.model'; import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; import { SortDirection, SortOptions } from '../cache/models/sort-options.model'; import { ObjectCacheService } from '../cache/object-cache.service'; import { CoreState } from '../core.reducers'; import { DSpaceObject } from '../shared/dspace-object.model'; import { HALEndpointService } from '../shared/hal-endpoint.service'; import { Item } from '../shared/item.model'; import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; import { ChangeAnalyzer } from './change-analyzer'; import { DataService } from './data.service'; import { FindListOptions, PatchRequest } from './request.models'; import { RequestService } from './request.service'; import { getMockRequestService } from '../../shared/mocks/request.service.mock'; import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service.stub'; import { RequestParam } from '../cache/models/request-param.model'; import { getMockRemoteDataBuildService } from '../../shared/mocks/remote-data-build.service.mock'; import { TestScheduler } from 'rxjs/testing'; import { RemoteData } from './remote-data'; import { RequestEntryState } from './request.reducer'; const endpoint = 'https://rest.api/core'; /* tslint:disable:max-classes-per-file */ class TestService extends DataService<any> { constructor( protected requestService: RequestService, protected rdbService: RemoteDataBuildService, protected store: Store<CoreState>, protected linkPath: string, protected halService: HALEndpointService, protected objectCache: ObjectCacheService, protected notificationsService: NotificationsService, protected http: HttpClient, protected comparator: ChangeAnalyzer<Item> ) { super(); } public getBrowseEndpoint(options: FindListOptions = {}, linkPath: string = this.linkPath): Observable<string> { return observableOf(endpoint); } } class DummyChangeAnalyzer implements ChangeAnalyzer<Item> { diff(object1: Item, object2: Item): Operation[] { return compare((object1 as any).metadata, (object2 as any).metadata); } } describe('DataService', () => { let service: TestService; let options: FindListOptions; let requestService; let halService; let rdbService; let notificationsService; let http; let comparator; let objectCache; let store; let selfLink; let linksToFollow; let testScheduler; let remoteDataMocks; function initTestService(): TestService { requestService = getMockRequestService(); halService = new HALEndpointServiceStub('url') as any; rdbService = getMockRemoteDataBuildService(); notificationsService = {} as NotificationsService; http = {} as HttpClient; comparator = new DummyChangeAnalyzer() as any; objectCache = { addPatch: () => { /* empty */ }, getObjectBySelfLink: () => { /* empty */ } } as any; store = {} as Store<CoreState>; selfLink = 'https://rest.api/endpoint/1698f1d3-be98-4c51-9fd8-6bfedcbd59b7'; linksToFollow = [ followLink('a'), followLink('b') ]; testScheduler = new TestScheduler((actual, expected) => { // asserting the two objects are equal // e.g. using chai. expect(actual).toEqual(expected); }); const timeStamp = new Date().getTime(); const msToLive = 15 * 60 * 1000; const payload = { foo: 'bar' }; const statusCodeSuccess = 200; const statusCodeError = 404; const errorMessage = 'not found'; remoteDataMocks = { RequestPending: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.RequestPending, undefined, undefined, undefined), ResponsePending: new RemoteData(undefined, msToLive, timeStamp, RequestEntryState.ResponsePending, undefined, undefined, undefined), Success: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.Success, undefined, payload, statusCodeSuccess), SuccessStale: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.SuccessStale, undefined, payload, statusCodeSuccess), Error: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.Error, errorMessage, undefined, statusCodeError), ErrorStale: new RemoteData(timeStamp, msToLive, timeStamp, RequestEntryState.ErrorStale, errorMessage, undefined, statusCodeError), }; return new TestService( requestService, rdbService, store, endpoint, halService, objectCache, notificationsService, http, comparator, ); } beforeEach(() => { service = initTestService(); }); describe('getFindAllHref', () => { it('should return an observable with the endpoint', () => { options = {}; (service as any).getFindAllHref(options).subscribe((value) => { expect(value).toBe(endpoint); } ); }); it('should include page in href if currentPage provided in options', () => { options = { currentPage: 2 }; const expected = `${endpoint}?page=${options.currentPage - 1}`; (service as any).getFindAllHref(options).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include size in href if elementsPerPage provided in options', () => { options = { elementsPerPage: 5 }; const expected = `${endpoint}?size=${options.elementsPerPage}`; (service as any).getFindAllHref(options).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include sort href if SortOptions provided in options', () => { const sortOptions = new SortOptions('field1', SortDirection.ASC); options = { sort: sortOptions }; const expected = `${endpoint}?sort=${sortOptions.field},${sortOptions.direction}`; (service as any).getFindAllHref(options).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include startsWith in href if startsWith provided in options', () => { options = { startsWith: 'ab' }; const expected = `${endpoint}?startsWith=${options.startsWith}`; (service as any).getFindAllHref(options).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include all provided options in href', () => { const sortOptions = new SortOptions('field1', SortDirection.DESC); options = { currentPage: 6, elementsPerPage: 10, sort: sortOptions, startsWith: 'ab', }; const expected = `${endpoint}?page=${options.currentPage - 1}&size=${options.elementsPerPage}` + `&sort=${sortOptions.field},${sortOptions.direction}&startsWith=${options.startsWith}`; (service as any).getFindAllHref(options).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include all searchParams in href if any provided in options', () => { options = { searchParams: [ new RequestParam('param1', 'test'), new RequestParam('param2', 'test2'), ] }; const expected = `${endpoint}?param1=test&param2=test2`; (service as any).getFindAllHref(options).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include linkPath in href if any provided', () => { const expected = `${endpoint}/test/entries`; (service as any).getFindAllHref({}, 'test/entries').subscribe((value) => { expect(value).toBe(expected); }); }); it('should include single linksToFollow as embed', () => { const expected = `${endpoint}?embed=bundles`; (service as any).getFindAllHref({}, null, followLink('bundles')).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include single linksToFollow as embed and its size', () => { const expected = `${endpoint}?embed.size=bundles=5&embed=bundles`; const config: FindListOptions = Object.assign(new FindListOptions(), { elementsPerPage: 5 }); (service as any).getFindAllHref({}, null, followLink('bundles', { findListOptions: config })).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include multiple linksToFollow as embed', () => { const expected = `${endpoint}?embed=bundles&embed=owningCollection&embed=templateItemOf`; (service as any).getFindAllHref({}, null, followLink('bundles'), followLink('owningCollection'), followLink('templateItemOf')).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include multiple linksToFollow as embed and its sizes if given', () => { const expected = `${endpoint}?embed=bundles&embed.size=owningCollection=2&embed=owningCollection&embed=templateItemOf`; const config: FindListOptions = Object.assign(new FindListOptions(), { elementsPerPage: 2 }); (service as any).getFindAllHref({}, null, followLink('bundles'), followLink('owningCollection', { findListOptions: config }), followLink('templateItemOf')).subscribe((value) => { expect(value).toBe(expected); }); }); it('should not include linksToFollow with shouldEmbed = false', () => { const expected = `${endpoint}?embed=templateItemOf`; (service as any).getFindAllHref( {}, null, followLink('bundles', { shouldEmbed: false }), followLink('owningCollection', { shouldEmbed: false }), followLink('templateItemOf') ).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include nested linksToFollow 3lvl', () => { const expected = `${endpoint}?embed=owningCollection/itemtemplate/relationships`; (service as any).getFindAllHref({}, null, followLink('owningCollection', {}, followLink('itemtemplate', {}, followLink('relationships')))).subscribe((value) => { expect(value).toBe(expected); }); }); it('should include nested linksToFollow 2lvl and nested embed\'s size', () => { const expected = `${endpoint}?embed.size=owningCollection/itemtemplate=4&embed=owningCollection/itemtemplate`; const config: FindListOptions = Object.assign(new FindListOptions(), { elementsPerPage: 4 }); (service as any).getFindAllHref({}, null, followLink('owningCollection', {}, followLink('itemtemplate', { findListOptions: config }))).subscribe((value) => { expect(value).toBe(expected); }); }); }); describe('getIDHref', () => { const endpointMock = 'https://dspace7-internal.atmire.com/server/api/core/items'; const resourceIdMock = '003c99b4-d4fe-44b0-a945-e12182a7ca89'; it('should return endpoint', () => { const result = (service as any).getIDHref(endpointMock, resourceIdMock); expect(result).toEqual(endpointMock + '/' + resourceIdMock); }); it('should include single linksToFollow as embed', () => { const expected = `${endpointMock}/${resourceIdMock}?embed=bundles`; const result = (service as any).getIDHref(endpointMock, resourceIdMock, followLink('bundles')); expect(result).toEqual(expected); }); it('should include multiple linksToFollow as embed', () => { const expected = `${endpointMock}/${resourceIdMock}?embed=bundles&embed=owningCollection&embed=templateItemOf`; const result = (service as any).getIDHref(endpointMock, resourceIdMock, followLink('bundles'), followLink('owningCollection'), followLink('templateItemOf')); expect(result).toEqual(expected); }); it('should not include linksToFollow with shouldEmbed = false', () => { const expected = `${endpointMock}/${resourceIdMock}?embed=templateItemOf`; const result = (service as any).getIDHref( endpointMock, resourceIdMock, followLink('bundles', { shouldEmbed: false }), followLink('owningCollection', { shouldEmbed: false }), followLink('templateItemOf') ); expect(result).toEqual(expected); }); it('should include nested linksToFollow 3lvl', () => { const expected = `${endpointMock}/${resourceIdMock}?embed=owningCollection/itemtemplate/relationships`; const result = (service as any).getIDHref(endpointMock, resourceIdMock, followLink('owningCollection', {}, followLink('itemtemplate', {}, followLink('relationships')))); expect(result).toEqual(expected); }); }); describe('patch', () => { const dso = { uuid: 'dso-uuid' }; const operations = [ Object.assign({ op: 'move', from: '/1', path: '/5' }) as Operation ]; beforeEach(() => { service.patch(dso, operations); }); it('should send a PatchRequest', () => { expect(requestService.send).toHaveBeenCalledWith(jasmine.any(PatchRequest)); }); }); describe('update', () => { let operations; let dso; let dso2; const name1 = 'random string'; const name2 = 'another random string'; beforeEach(() => { operations = [{ op: 'replace', path: '/0/value', value: name2 } as Operation]; dso = Object.assign(new DSpaceObject(), { _links: { self: { href: selfLink } }, metadata: [{ key: 'dc.title', value: name1 }] }); dso2 = Object.assign(new DSpaceObject(), { _links: { self: { href: selfLink } }, metadata: [{ key: 'dc.title', value: name2 }] }); spyOn(service, 'findByHref').and.returnValue(createSuccessfulRemoteDataObject$(dso)); spyOn(objectCache, 'addPatch'); }); it('should call addPatch on the object cache with the right parameters when there are differences', () => { service.update(dso2).subscribe(); expect(objectCache.addPatch).toHaveBeenCalledWith(selfLink, operations); }); it('should not call addPatch on the object cache with the right parameters when there are no differences', () => { service.update(dso).subscribe(); expect(objectCache.addPatch).not.toHaveBeenCalled(); }); }); describe(`reRequestStaleRemoteData`, () => { let callback: jasmine.Spy<jasmine.Func>; beforeEach(() => { callback = jasmine.createSpy(); }); describe(`when shouldReRequest is false`, () => { it(`shouldn't do anything`, () => { testScheduler.run(({ cold, expectObservable, flush }) => { const expected = 'a-b-c-d-e-f'; const values = { a: remoteDataMocks.RequestPending, b: remoteDataMocks.ResponsePending, c: remoteDataMocks.Success, d: remoteDataMocks.SuccessStale, e: remoteDataMocks.Error, f: remoteDataMocks.ErrorStale, }; expectObservable((service as any).reRequestStaleRemoteData(false, callback)(cold(expected, values))).toBe(expected, values); // since the callback happens in a tap(), flush to ensure it has been executed flush(); expect(callback).not.toHaveBeenCalled(); }); }); }); describe(`when shouldReRequest is true`, () => { it(`should call the callback for stale RemoteData objects, but still pass the source observable unmodified`, () => { testScheduler.run(({ cold, expectObservable, flush }) => { const expected = 'a-b'; const values = { a: remoteDataMocks.SuccessStale, b: remoteDataMocks.ErrorStale, }; expectObservable((service as any).reRequestStaleRemoteData(true, callback)(cold(expected, values))).toBe(expected, values); // since the callback happens in a tap(), flush to ensure it has been executed flush(); expect(callback).toHaveBeenCalledTimes(2); }); }); it(`should only call the callback for stale RemoteData objects if something is subscribed to it`, (done) => { testScheduler.run(({ cold, expectObservable }) => { const expected = 'a'; const values = { a: remoteDataMocks.SuccessStale, }; const result$ = (service as any).reRequestStaleRemoteData(true, callback)(cold(expected, values)); expectObservable(result$).toBe(expected, values); expect(callback).not.toHaveBeenCalled(); result$.subscribe(() => { expect(callback).toHaveBeenCalled(); done(); }); }); }); it(`shouldn't do anything for RemoteData objects that aren't stale`, () => { testScheduler.run(({ cold, expectObservable, flush }) => { const expected = 'a-b-c-d'; const values = { a: remoteDataMocks.RequestPending, b: remoteDataMocks.ResponsePending, c: remoteDataMocks.Success, d: remoteDataMocks.Error, }; expectObservable((service as any).reRequestStaleRemoteData(true, callback)(cold(expected, values))).toBe(expected, values); // since the callback happens in a tap(), flush to ensure it has been executed flush(); expect(callback).not.toHaveBeenCalled(); }); }); }); }); describe(`findByHref`, () => { beforeEach(() => { spyOn(service as any, 'createAndSendGetRequest').and.callFake((href$) => { href$.subscribe().unsubscribe(); }); }); it(`should call buildHrefFromFindOptions with href and linksToFollow`, () => { testScheduler.run(({ cold }) => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue(selfLink); spyOn(rdbService, 'buildSingle').and.returnValue(cold('a', { a: remoteDataMocks.Success })); spyOn(service as any, 'reRequestStaleRemoteData').and.returnValue(() => cold('a', { a: remoteDataMocks.Success })); service.findByHref(selfLink, true, true, ...linksToFollow); expect(service.buildHrefFromFindOptions).toHaveBeenCalledWith(selfLink, {}, [], ...linksToFollow); }); }); it(`should call createAndSendGetRequest with the result from buildHrefFromFindOptions and useCachedVersionIfAvailable`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue('bingo!'); spyOn(rdbService, 'buildSingle').and.returnValue(cold('a', { a: remoteDataMocks.Success })); spyOn(service as any, 'reRequestStaleRemoteData').and.returnValue(() => cold('a', { a: remoteDataMocks.Success })); service.findByHref(selfLink, true, true, ...linksToFollow); expect((service as any).createAndSendGetRequest).toHaveBeenCalledWith(jasmine.anything(), true); expectObservable(rdbService.buildSingle.calls.argsFor(0)[0]).toBe('(a|)', { a: 'bingo!' }); service.findByHref(selfLink, false, true, ...linksToFollow); expect((service as any).createAndSendGetRequest).toHaveBeenCalledWith(jasmine.anything(), false); expectObservable(rdbService.buildSingle.calls.argsFor(1)[0]).toBe('(a|)', { a: 'bingo!' }); }); }); it(`should call rdbService.buildSingle with the result from buildHrefFromFindOptions and linksToFollow`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue('bingo!'); spyOn(rdbService, 'buildSingle').and.returnValue(cold('a', { a: remoteDataMocks.Success })); spyOn(service as any, 'reRequestStaleRemoteData').and.returnValue(() => cold('a', { a: remoteDataMocks.Success })); service.findByHref(selfLink, true, true, ...linksToFollow); expect(rdbService.buildSingle).toHaveBeenCalledWith(jasmine.anything() as any, ...linksToFollow); expectObservable(rdbService.buildSingle.calls.argsFor(0)[0]).toBe('(a|)', { a: 'bingo!' }); }); }); it(`should return a the output from reRequestStaleRemoteData`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue(selfLink); spyOn(rdbService, 'buildSingle').and.returnValue(cold('a', { a: remoteDataMocks.Success })); spyOn(service as any, 'reRequestStaleRemoteData').and.returnValue(() => cold('a', { a: 'bingo!' })); const expected = 'a'; const values = { a: 'bingo!', }; expectObservable(service.findByHref(selfLink, true, true, ...linksToFollow)).toBe(expected, values); }); }); it(`should call reRequestStaleRemoteData with reRequestOnStale and the exact same findByHref call as a callback`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue(selfLink); spyOn(rdbService, 'buildSingle').and.returnValue(cold('a', { a: remoteDataMocks.SuccessStale })); spyOn(service as any, 'reRequestStaleRemoteData').and.returnValue(() => cold('a', { a: remoteDataMocks.SuccessStale })); service.findByHref(selfLink, true, true, ...linksToFollow); expect((service as any).reRequestStaleRemoteData.calls.argsFor(0)[0]).toBeTrue(); spyOn(service, 'findByHref').and.returnValue(cold('a', { a: remoteDataMocks.SuccessStale })); // prove that the spy we just added hasn't been called yet expect(service.findByHref).not.toHaveBeenCalled(); // call the callback passed to reRequestStaleRemoteData (service as any).reRequestStaleRemoteData.calls.argsFor(0)[1](); // verify that findByHref _has_ been called now, with the same params as the original call expect(service.findByHref).toHaveBeenCalledWith(jasmine.anything(), true, true, ...linksToFollow); // ... except for selflink, which will have been turned in to an observable. expectObservable((service.findByHref as jasmine.Spy).calls.argsFor(0)[0]).toBe('(a|)', { a: selfLink }); }); }); describe(`when useCachedVersionIfAvailable is true`, () => { beforeEach(() => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue(selfLink); spyOn(service as any, 'reRequestStaleRemoteData').and.callFake(() => (source) => source); }); it(`should emit a cached completed RemoteData immediately, and keep emitting if it gets rerequested`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d-e', { a: remoteDataMocks.Success, b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, })); const expected = 'a-b-c-d-e'; const values = { a: remoteDataMocks.Success, b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, }; expectObservable(service.findByHref(selfLink, true, true, ...linksToFollow)).toBe(expected, values); }); }); it(`should not emit a cached stale RemoteData, but only start emitting after the state first changes to RequestPending`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d-e', { a: remoteDataMocks.SuccessStale, b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, })); const expected = '--b-c-d-e'; const values = { b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, }; expectObservable(service.findByHref(selfLink, true, true, ...linksToFollow)).toBe(expected, values); }); }); }); describe(`when useCachedVersionIfAvailable is false`, () => { beforeEach(() => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue(selfLink); spyOn(service as any, 'reRequestStaleRemoteData').and.callFake(() => (source) => source); }); it(`should not emit a cached completed RemoteData, but only start emitting after the state first changes to RequestPending`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d-e', { a: remoteDataMocks.Success, b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, })); const expected = '--b-c-d-e'; const values = { b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, }; expectObservable(service.findByHref(selfLink, false, true, ...linksToFollow)).toBe(expected, values); }); }); it(`should not emit a cached stale RemoteData, but only start emitting after the state first changes to RequestPending`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(rdbService, 'buildSingle').and.returnValue(cold('a-b-c-d-e', { a: remoteDataMocks.SuccessStale, b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, })); const expected = '--b-c-d-e'; const values = { b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, }; expectObservable(service.findByHref(selfLink, false, true, ...linksToFollow)).toBe(expected, values); }); }); }); }); describe(`findAllByHref`, () => { let findListOptions; beforeEach(() => { findListOptions = { currentPage: 5 }; spyOn(service as any, 'createAndSendGetRequest').and.callFake((href$) => { href$.subscribe().unsubscribe(); }); }); it(`should call buildHrefFromFindOptions with href and linksToFollow`, () => { testScheduler.run(({ cold }) => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue(selfLink); spyOn(rdbService, 'buildList').and.returnValue(cold('a', { a: remoteDataMocks.Success })); spyOn(service as any, 'reRequestStaleRemoteData').and.returnValue(() => cold('a', { a: remoteDataMocks.Success })); service.findAllByHref(selfLink, findListOptions, true, true, ...linksToFollow); expect(service.buildHrefFromFindOptions).toHaveBeenCalledWith(selfLink, findListOptions, [], ...linksToFollow); }); }); it(`should call createAndSendGetRequest with the result from buildHrefFromFindOptions and useCachedVersionIfAvailable`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue('bingo!'); spyOn(rdbService, 'buildList').and.returnValue(cold('a', { a: remoteDataMocks.Success })); spyOn(service as any, 'reRequestStaleRemoteData').and.returnValue(() => cold('a', { a: remoteDataMocks.Success })); service.findAllByHref(selfLink, findListOptions, true, true, ...linksToFollow); expect((service as any).createAndSendGetRequest).toHaveBeenCalledWith(jasmine.anything(), true); expectObservable(rdbService.buildList.calls.argsFor(0)[0]).toBe('(a|)', { a: 'bingo!' }); service.findAllByHref(selfLink, findListOptions, false, true, ...linksToFollow); expect((service as any).createAndSendGetRequest).toHaveBeenCalledWith(jasmine.anything(), false); expectObservable(rdbService.buildList.calls.argsFor(1)[0]).toBe('(a|)', { a: 'bingo!' }); }); }); it(`should call rdbService.buildList with the result from buildHrefFromFindOptions and linksToFollow`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue('bingo!'); spyOn(rdbService, 'buildList').and.returnValue(cold('a', { a: remoteDataMocks.Success })); spyOn(service as any, 'reRequestStaleRemoteData').and.returnValue(() => cold('a', { a: remoteDataMocks.Success })); service.findAllByHref(selfLink, findListOptions, true, true, ...linksToFollow); expect(rdbService.buildList).toHaveBeenCalledWith(jasmine.anything() as any, ...linksToFollow); expectObservable(rdbService.buildList.calls.argsFor(0)[0]).toBe('(a|)', { a: 'bingo!' }); }); }); it(`should call reRequestStaleRemoteData with reRequestOnStale and the exact same findAllByHref call as a callback`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue('bingo!'); spyOn(rdbService, 'buildList').and.returnValue(cold('a', { a: remoteDataMocks.SuccessStale })); spyOn(service as any, 'reRequestStaleRemoteData').and.returnValue(() => cold('a', { a: remoteDataMocks.SuccessStale })); service.findAllByHref(selfLink, findListOptions, true, true, ...linksToFollow); expect((service as any).reRequestStaleRemoteData.calls.argsFor(0)[0]).toBeTrue(); spyOn(service, 'findAllByHref').and.returnValue(cold('a', { a: remoteDataMocks.SuccessStale })); // prove that the spy we just added hasn't been called yet expect(service.findAllByHref).not.toHaveBeenCalled(); // call the callback passed to reRequestStaleRemoteData (service as any).reRequestStaleRemoteData.calls.argsFor(0)[1](); // verify that findAllByHref _has_ been called now, with the same params as the original call expect(service.findAllByHref).toHaveBeenCalledWith(jasmine.anything(), findListOptions, true, true, ...linksToFollow); // ... except for selflink, which will have been turned in to an observable. expectObservable((service.findAllByHref as jasmine.Spy).calls.argsFor(0)[0]).toBe('(a|)', { a: selfLink }); }); }); it(`should return a the output from reRequestStaleRemoteData`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue(selfLink); spyOn(rdbService, 'buildList').and.returnValue(cold('a', { a: remoteDataMocks.Success })); spyOn(service as any, 'reRequestStaleRemoteData').and.returnValue(() => cold('a', { a: 'bingo!' })); const expected = 'a'; const values = { a: 'bingo!', }; expectObservable(service.findAllByHref(selfLink, findListOptions, true, true, ...linksToFollow)).toBe(expected, values); }); }); describe(`when useCachedVersionIfAvailable is true`, () => { beforeEach(() => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue(selfLink); spyOn(service as any, 'reRequestStaleRemoteData').and.callFake(() => (source) => source); }); it(`should emit a cached completed RemoteData immediately, and keep emitting if it gets rerequested`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(rdbService, 'buildList').and.returnValue(cold('a-b-c-d-e', { a: remoteDataMocks.Success, b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, })); const expected = 'a-b-c-d-e'; const values = { a: remoteDataMocks.Success, b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, }; expectObservable(service.findAllByHref(selfLink, findListOptions, true, true, ...linksToFollow)).toBe(expected, values); }); }); it(`should not emit a cached stale RemoteData, but only start emitting after the state first changes to RequestPending`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(rdbService, 'buildList').and.returnValue(cold('a-b-c-d-e', { a: remoteDataMocks.SuccessStale, b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, })); const expected = '--b-c-d-e'; const values = { b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, }; expectObservable(service.findAllByHref(selfLink, findListOptions, true, true, ...linksToFollow)).toBe(expected, values); }); }); }); describe(`when useCachedVersionIfAvailable is false`, () => { beforeEach(() => { spyOn(service, 'buildHrefFromFindOptions').and.returnValue(selfLink); spyOn(service as any, 'reRequestStaleRemoteData').and.callFake(() => (source) => source); }); it(`should not emit a cached completed RemoteData, but only start emitting after the state first changes to RequestPending`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(rdbService, 'buildList').and.returnValue(cold('a-b-c-d-e', { a: remoteDataMocks.Success, b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, })); const expected = '--b-c-d-e'; const values = { b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, }; expectObservable(service.findAllByHref(selfLink, findListOptions, false, true, ...linksToFollow)).toBe(expected, values); }); }); it(`should not emit a cached stale RemoteData, but only start emitting after the state first changes to RequestPending`, () => { testScheduler.run(({ cold, expectObservable }) => { spyOn(rdbService, 'buildList').and.returnValue(cold('a-b-c-d-e', { a: remoteDataMocks.SuccessStale, b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, })); const expected = '--b-c-d-e'; const values = { b: remoteDataMocks.RequestPending, c: remoteDataMocks.ResponsePending, d: remoteDataMocks.Success, e: remoteDataMocks.SuccessStale, }; expectObservable(service.findAllByHref(selfLink, findListOptions, false, true, ...linksToFollow)).toBe(expected, values); }); }); }); }); }); /* tslint:enable:max-classes-per-file */
the_stack
import { Store, CreateDocumentParams, ReadDocumentParams, UpdateDocumentParams, DeleteDocumentParams, FindDocumentsParams, CountDocumentsParams, MigrateCollectionParams, MigrateCollectionResult, Document, Expression, Path, Operand } from '@layr/store'; import type { StorableComponent, Query, SortDescriptor, SortDirection, Operator } from '@layr/storable'; import {ensureComponentInstance} from '@layr/component'; import {MongoClient, Db, Collection, Filter, FindOptions} from 'mongodb'; import {Microbatcher, Operation} from 'microbatcher'; import {hasOwnProperty, assertIsObjectLike} from 'core-helpers'; import isEmpty from 'lodash/isEmpty'; import mapKeys from 'lodash/mapKeys'; import mapValues from 'lodash/mapValues'; import escapeRegExp from 'lodash/escapeRegExp'; import groupBy from 'lodash/groupBy'; import debugModule from 'debug'; const debug = debugModule('layr:mongodb-store'); // To display the debug log, set this environment: // DEBUG=layr:mongodb-store DEBUG_DEPTH=10 const MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_NAME = '_id'; const MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_INDEX_NAME = '_id_'; /** * *Inherits from [`Store`](https://layrjs.com/docs/v2/reference/store).* * * A [`Store`](https://layrjs.com/docs/v2/reference/store) that uses a [MongoDB](https://www.mongodb.com/) database to persist its registered [storable components](https://layrjs.com/docs/v2/reference/storable#storable-component-class). * * #### Usage * * Create a `MongoDBStore` instance, register some [storable components](https://layrjs.com/docs/v2/reference/storable#storable-component-class) into it, and then use any [`StorableComponent`](https://layrjs.com/docs/v2/reference/storable#storable-component-class)'s method to load, save, delete, or find components from the store. * * For example, let's build a simple `Backend` that provides a `Movie` component. * * First, let's define the components that we are going to use: * * ``` * // JS * * import {Component} from '﹫layr/component'; * import {Storable, primaryIdentifier, attribute} from '@layr/storable'; * * class Movie extends Storable(Component) { * @primaryIdentifier() id; * * @attribute() title = ''; * } * * class Backend extends Component { * ﹫provide() static Movie = Movie; * } * ``` * * ``` * // TS * * import {Component} from '﹫layr/component'; * import {Storable, primaryIdentifier, attribute} from '@layr/storable'; * * class Movie extends Storable(Component) { * @primaryIdentifier() id!: string; * * @attribute() title = ''; * } * * class Backend extends Component { * ﹫provide() static Movie = Movie; * } * ``` * * Next, let's create a `MongoDBStore` instance, and let's register the `Backend` component as the root component of the store: * * ``` * import {MongoDBStore} from '﹫layr/mongodb-store'; * * const store = new MongoDBStore('mongodb://user:pass@host:port/db'); * * store.registerRootComponent(Backend); * ``` * * Finally, we can interact with the store by calling some [`StorableComponent`](https://layrjs.com/docs/v2/reference/storable#storable-component-class) methods: * * ``` * let movie = new Movie({id: 'abc123', title: 'Inception'}); * * // Save the movie to the store * await movie.save(); * * // Get the movie from the store * movie = await Movie.get('abc123'); * movie.title; // => 'Inception' * * // Modify the movie, and save it to the store * movie.title = 'Inception 2'; * await movie.save(); * * // Find the movies that have a title starting with 'Inception' * const movies = await Movie.find({title: {$startsWith: 'Inception'}}); * movies.length; // => 1 (one movie found) * movies[0].title; // => 'Inception 2' * movies[0] === movie; // true (thanks to the identity mapping) * * // Delete the movie from the store * await movie.delete(); * ``` */ export class MongoDBStore extends Store { private _connectionString: string; private _poolSize: number; /** * Creates a [`MongoDBStore`](https://layrjs.com/docs/v2/reference/mongodb-store). * * @param connectionString The [connection string](https://docs.mongodb.com/manual/reference/connection-string/) of the MongoDB database to use. * @param [options.poolSize] A number specifying the maximum size of the connection pool (default: `1`). * * @returns The [`MongoDBStore`](https://layrjs.com/docs/v2/reference/mongodb-store) instance that was created. * * @example * ``` * const store = new MongoDBStore('mongodb://user:pass@host:port/db'); * ``` * * @category Creation */ constructor(connectionString: string, options: {poolSize?: number} = {}) { if (typeof connectionString !== 'string') { throw new Error( `Expected a 'connectionString' to create a MongoDBStore, but received a value of type '${typeof connectionString}'` ); } if (connectionString.length === 0) { throw new Error( `Expected a 'connectionString' to create a MongoDBStore, but received an empty string` ); } const {poolSize = 1, ...otherOptions} = options; super(otherOptions); this._connectionString = connectionString; this._poolSize = poolSize; } getURL() { return this._connectionString; } // === Component Registration === /** * See the methods that are inherited from the [`Store`](https://layrjs.com/docs/v2/reference/store#component-registration) class. * * @category Component Registration */ // === Connection === /** * Initiates a connection to the MongoDB database. * * Since this method is called automatically when you interact with the store through any of the [`StorableComponent`](https://layrjs.com/docs/v2/reference/storable#storable-component-class) methods, you shouldn't have to call it manually. * * @category Connection to MongoDB */ async connect() { await this._connectClient(); } /** * Closes the connection to the MongoDB database. Unless you are building a tool that uses a store for an ephemeral duration, you shouldn't have to call this method. * * @category Connection to MongoDB */ async disconnect() { await this._disconnectClient(); } // === Documents === async createDocument({collectionName, document}: CreateDocumentParams) { const collection = await this._getCollection(collectionName); try { const {acknowledged} = await debugCall( async () => { const {acknowledged} = await collection.insertOne(document); return {acknowledged}; }, 'db.%s.insertOne(%o)', collectionName, document ); return acknowledged; } catch (error) { if (error.name === 'MongoServerError' && error.code === 11000) { const matches = error.message.match(/ index: (.*) dup key/); if (matches === null) { throw error; } const indexName = matches[1]; if (indexName === MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_INDEX_NAME) { return false; // The document already exists } throw Object.assign( new Error( `A duplicate key error occurred while creating a MongoDB document (collection: '${collectionName}', index: '${indexName}')` ), {code: 'DUPLICATE_KEY_ERROR', collectionName, indexName} ); } throw error; } } async readDocument({ collectionName, identifierDescriptor, projection }: ReadDocumentParams): Promise<Document | undefined> { const collection = await this._getCollection(collectionName); const query = identifierDescriptor; const options = {projection}; const document: Document | null = await debugCall( async () => await batchableFindOne(collection, query, options), 'db.%s.batchableFindOne(%o, %o)', collectionName, query, options ); if (document === null) { return undefined; } return document; } async updateDocument({ collectionName, identifierDescriptor, documentPatch }: UpdateDocumentParams) { const collection = await this._getCollection(collectionName); const filter = identifierDescriptor; const {matchedCount} = await debugCall( async () => { try { const {matchedCount, modifiedCount} = await collection.updateOne(filter, documentPatch); return {matchedCount, modifiedCount}; } catch (error) { if (error.name === 'MongoServerError' && error.code === 11000) { const matches = error.message.match(/ index: (.*) dup key/); if (matches === null) { throw error; } const indexName = matches[1]; throw Object.assign( new Error( `A duplicate key error occurred while updating a MongoDB document (collection: '${collectionName}', index: '${indexName}')` ), {code: 'DUPLICATE_KEY_ERROR', collectionName, indexName} ); } throw error; } }, 'db.%s.updateOne(%o, %o)', collectionName, filter, documentPatch ); return matchedCount === 1; } async deleteDocument({collectionName, identifierDescriptor}: DeleteDocumentParams) { const collection = await this._getCollection(collectionName); const filter = identifierDescriptor; const {deletedCount} = await debugCall( async () => { const {deletedCount} = await collection.deleteOne(filter); return {deletedCount}; }, 'db.%s.deleteOne(%o)', collectionName, filter ); return deletedCount === 1; } async findDocuments({ collectionName, expressions, projection, sort, skip, limit }: FindDocumentsParams): Promise<Document[]> { const collection = await this._getCollection(collectionName); const mongoQuery = buildMongoQuery(expressions); const mongoSort = buildMongoSort(sort); const options = {projection}; const documents: Document[] = await debugCall( async () => { const cursor = collection.find(mongoQuery, options); if (mongoSort !== undefined) { cursor.sort(mongoSort); } if (skip !== undefined) { cursor.skip(skip); } if (limit !== undefined) { cursor.limit(limit); } const documents = await cursor.toArray(); return documents; }, 'db.%s.find(%o, %o)', collectionName, mongoQuery, options ); return documents; } async countDocuments({collectionName, expressions}: CountDocumentsParams) { const collection = await this._getCollection(collectionName); const query = buildMongoQuery(expressions); const documentsCount = await debugCall( async () => { const documentsCount = await collection.countDocuments(query); return documentsCount; }, 'db.%s.countDocuments(%o)', collectionName, query ); return documentsCount; } // === Serialization === toDocument<Value>(storable: typeof StorableComponent | StorableComponent, value: Value) { let document = super.toDocument(storable, value); if (typeof document === 'object') { const primaryIdentifierAttributeName = ensureComponentInstance(storable) .getPrimaryIdentifierAttribute() .getName(); document = mapKeys(document as any, (_, name) => name === primaryIdentifierAttributeName ? MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_NAME : name ) as Value; } return document; } fromDocument( storable: typeof StorableComponent | StorableComponent, document: Document ): Document { let serializedStorable = super.fromDocument(storable, document); if (typeof serializedStorable === 'object') { const primaryIdentifierAttributeName = ensureComponentInstance(storable) .getPrimaryIdentifierAttribute() .getName(); serializedStorable = mapKeys(serializedStorable, (_, name) => name === MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_NAME ? primaryIdentifierAttributeName : name ); } return serializedStorable; } // === Migration === /** * See the methods that are inherited from the [`Store`](https://layrjs.com/docs/v2/reference/store#migration) class. * * @category Migration */ async migrateCollection({ collectionName, collectionSchema, silent = false }: MigrateCollectionParams) { const result: MigrateCollectionResult = { name: collectionName, createdIndexes: [], droppedIndexes: [] }; const database = await this._getDatabase(); let collection: Collection; let collectionHasBeenCreated: boolean; const collections = await database .listCollections({name: collectionName}, {nameOnly: true}) .toArray(); if (collections.length === 0) { if (!silent) { console.log(`Creating collection: '${collectionName}'`); } collection = await database.createCollection(collectionName); collectionHasBeenCreated = true; } else { collection = database.collection(collectionName); collectionHasBeenCreated = false; } const existingIndexNames: string[] = (await collection.indexes()).map( (index: any) => index.name ); const indexesToEnsure: any[] = []; for (const index of collectionSchema.indexes) { let indexName = ''; let indexSpec: any = {}; for (let [name, direction] of Object.entries(index.attributes)) { const directionString = direction.toLowerCase(); if (indexName !== '') { indexName += ' + '; } indexName += name; if (directionString === 'desc') { indexName += ' (desc)'; } indexSpec[name] = directionString === 'desc' ? -1 : 1; } if (index.isUnique) { indexName += ' [unique]'; } if (indexName === `${MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_NAME} [unique]`) { indexName = MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_INDEX_NAME; } indexesToEnsure.push({name: indexName, spec: indexSpec, isUnique: index.isUnique}); } const indexesToCreate = indexesToEnsure.filter( (index) => !existingIndexNames.includes(index.name) ); const indexNamesToDrop = existingIndexNames.filter( (name) => name !== MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_INDEX_NAME && !indexesToEnsure.some((index) => index.name === name) ); if (indexesToCreate.length !== 0 || indexNamesToDrop.length !== 0) { if (!collectionHasBeenCreated && !silent) { console.log(`Migrating collection: '${collectionName}'`); } } for (const name of indexNamesToDrop) { if (!silent) { console.log(`- Dropping index: '${name}'`); } await collection.dropIndex(name); result.droppedIndexes.push(name); } for (const index of indexesToCreate) { if (!silent) { console.log(`- Creating index: '${index.name}'`); } await collection.createIndex(index.spec, {name: index.name, unique: index.isUnique}); result.createdIndexes.push(index.name); } return result; } // === MongoDB client === private _client: MongoClient | undefined; private async _getClient() { await this._connectClient(); return this._client!; } private _connectClientPromise: Promise<void> | undefined; private _connectClient() { // This method memoize the ongoing promise to allow concurrent execution if (this._connectClientPromise !== undefined) { return this._connectClientPromise; } this._connectClientPromise = (async () => { try { if (this._client === undefined) { debug(`Connecting to MongoDB Server (connectionString: ${this._connectionString})...`); this._client = await MongoClient.connect(this._connectionString, { maxPoolSize: this._poolSize }); debug(`Connected to MongoDB Server (connectionString: ${this._connectionString})`); } } finally { this._connectClientPromise = undefined; } })(); return this._connectClientPromise; } private async _disconnectClient() { if (this._connectClientPromise !== undefined) { // If the connection is ongoing, let's wait it finishes before disconnecting try { await this._connectClientPromise; } catch { // NOOP } } const client = this._client; if (client !== undefined) { // Unset `this._client` and `this._db` early to avoid issue in case of concurrent execution this._client = undefined; this._db = undefined; debug(`Disconnecting from MongoDB Server (connectionString: ${this._connectionString})...`); await client.close(); debug(`Disconnected from MongoDB Server (connectionString: ${this._connectionString})`); } } private _db: Db | undefined; private async _getDatabase() { if (!this._db) { const client = await this._getClient(); this._db = client.db(); } return this._db; } private _collections: {[name: string]: Collection} | undefined; private async _getCollection(name: string) { if (this._collections === undefined) { this._collections = Object.create(null); } if (this._collections![name] === undefined) { const database = await this._getDatabase(); this._collections![name] = database.collection(name); } return this._collections![name]; } } function buildMongoQuery(expressions: Expression[]) { const query: Query = {}; for (const [path, operator, value] of expressions) { let subquery: Query; if (path !== '') { subquery = query[path]; if (subquery === undefined) { subquery = {}; query[path] = subquery; } } else { subquery = query; } const [actualOperator, actualValue] = handleOperator(operator, value, {path}); subquery[actualOperator] = actualValue; } return query; } function handleOperator( operator: Operator, value: Operand, {path}: {path: Path} ): [Operator, unknown] { // --- Basic operators --- if (operator === '$equal') { return ['$eq', value]; } if (operator === '$notEqual') { return ['$ne', value]; } if (operator === '$greaterThan') { return ['$gt', value]; } if (operator === '$greaterThanOrEqual') { return ['$gte', value]; } if (operator === '$lessThan') { return ['$lt', value]; } if (operator === '$lessThanOrEqual') { return ['$lte', value]; } if (operator === '$in') { return ['$in', value]; } // --- String operators --- if (operator === '$includes') { return ['$regex', escapeRegExp(value as string)]; } if (operator === '$startsWith') { return ['$regex', `^${escapeRegExp(value as string)}`]; } if (operator === '$endsWith') { return ['$regex', `${escapeRegExp(value as string)}$`]; } if (operator === '$matches') { return ['$regex', value]; } // --- Array operators --- if (operator === '$some') { const subexpressions = value as Expression[]; const subquery = buildMongoQuery(subexpressions); return ['$elemMatch', subquery]; } if (operator === '$every') { // TODO: Make it works for complex queries (regexps, array of objects, etc.) const subexpressions = value as Expression[]; const subquery = buildMongoQuery(subexpressions); return ['$not', {$elemMatch: {$not: subquery}}]; } if (operator === '$length') { return ['$size', value]; } // --- Logical operators --- if (operator === '$not') { const subexpressions = value as Expression[]; const subquery = buildMongoQuery(subexpressions); return ['$not', subquery]; } if (operator === '$and') { const andSubexpressions = value as Expression[][]; const andSubqueries = andSubexpressions.map((subexpressions) => buildMongoQuery(subexpressions) ); return ['$and', andSubqueries]; } if (operator === '$or') { const orSubexpressions = value as Expression[][]; const orSubqueries = orSubexpressions.map((subexpressions) => buildMongoQuery(subexpressions)); return ['$or', orSubqueries]; } if (operator === '$nor') { const norSubexpressions = value as Expression[][]; const norSubqueries = norSubexpressions.map((subexpressions) => buildMongoQuery(subexpressions) ); return ['$nor', norSubqueries]; } throw new Error( `A query contains an operator that is not supported (operator: '${operator}', path: '${path}')` ); } function buildMongoSort(sort: SortDescriptor | undefined) { if (sort === undefined || isEmpty(sort)) { return undefined; } return mapValues(sort, (direction: SortDirection) => direction.toLowerCase() === 'desc' ? -1 : 1 ); } async function debugCall<Result>( func: () => Promise<Result>, message: string, ...params: unknown[] ): Promise<Result> { let result; let error; try { result = await func(); } catch (err) { error = err; } if (error !== undefined) { debug(`${message} => Error`, ...params); throw error; } debug(`${message} => %o`, ...params, result); return result as Result; } const findOneBatcher = Symbol('batcher'); interface FindOneOperation extends Operation { params: [filter: Filter<any>, options: FindOptions<any>]; } function batchableFindOne( collection: Collection & {[findOneBatcher]?: Microbatcher<FindOneOperation>}, query: Filter<any>, options: FindOptions<any> ) { assertIsObjectLike(query); if (collection[findOneBatcher] === undefined) { collection[findOneBatcher] = new Microbatcher(function (operations) { const operationGroups = groupBy(operations, ({params: [query, options]}) => { if ( hasOwnProperty(query, MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_NAME) && Object.keys(query).length === 1 ) { // 'query' has a single '_id' attribute query = {[MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_NAME]: '___???___'}; } return JSON.stringify([query, options]); }); for (const operations of Object.values(operationGroups)) { if (operations.length > 1) { // Multiple `findOne()` that can be transformed into a single `find()` const ids = operations.map( (operation) => operation.params[0][MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_NAME] ); const options = operations[0].params[1]; // All 'options' objects should be identical collection .find({[MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_NAME]: {$in: ids}}, options) .toArray() .then( (documents) => { for (const { params: [query], resolve } of operations) { const document = documents.find( (document) => document[MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_NAME] === query[MONGODB_PRIMARY_IDENTIFIER_ATTRIBUTE_NAME] ); resolve(document !== undefined ? document : null); } }, (error) => { for (const {reject} of operations) { reject(error); } } ); } else { // Single `findOne()` const { params: [query, options], resolve, reject } = operations[0]; collection.findOne(query, options).then(resolve, reject); } } }); } return collection[findOneBatcher]!.batch(query, options); }
the_stack
import { DataArrayTypes, DataType } from "../../interface/core/constants"; import { shaderGenHeader, shaderGenTensorNDGet, shaderGenTensorNDGetUniformItem, shaderGenTensorOutputCoordsWithReturn, shaderGenTensorOutputUniform, shaderGenTensorOutputUniformItem, } from "../../operators/webgl/shaderHelper"; import { TensorImpl } from "../../core/tensorImpl"; import { WebDNNWebGLContextImpl, WebGLSharedTexture } from "./webglContextImpl"; import { WebGLTensor } from "../../interface/backend/webgl/webglTensor"; import { WebGLUniformItem } from "../../interface/backend/webgl/webglContext"; export class WebGLTensorImpl extends TensorImpl implements WebGLTensor { textureWidth: number; textureHeight: number; sharedTexture: WebGLSharedTexture; private isBoundToDrawFrameBuffer = false; private readTextureUnitIndices: number[] = []; constructor( private context: WebDNNWebGLContextImpl, dims: ReadonlyArray<number>, dataType: DataType = "float32", public readonly dimPerPixel: 1 | 4 = 1, textureShape?: ReadonlyArray<number>, sharedTexture?: WebGLSharedTexture ) { super(dims, dataType, "webgl"); if (dataType !== "float32") { throw new Error("WebGLTensor only supports float32"); } const pixels = Math.ceil(this.length / dimPerPixel); // This makes computing slightly slow. why? // this.textureWidth = Math.pow( // 2, // Math.ceil(Math.log2(Math.min(pixels, this.context.maxTextureSize))) // ); if (textureShape) { this.textureHeight = textureShape[0]; this.textureWidth = textureShape[1]; } else { this.textureWidth = this.context.maxTextureSize; this.textureHeight = Math.ceil(pixels / this.textureWidth); } if ( this.textureHeight > this.context.maxTextureSize || this.textureWidth > this.context.maxTextureSize ) { throw new Error( `Cannot allocate texture of size ${this.length} in this environment. Please split large tensor in the model.` ); } if (sharedTexture) { this.sharedTexture = sharedTexture; } else { this.sharedTexture = new WebGLSharedTexture( this.context, this.textureWidth, this.textureHeight, this.dimPerPixel ); } } getTexture(): WebGLTexture { return this.sharedTexture.texture; } alias(dims: ReadonlyArray<number>): WebGLTensorImpl { this.sharedTexture.incrRef(); return new WebGLTensorImpl( this.context, dims, this.dataType, this.dimPerPixel, [this.textureHeight, this.textureWidth], this.sharedTexture ); } async getData(): Promise<DataArrayTypes> { const { gl } = this.context; let data: Float32Array; if ( this.context.isWebGL2(gl) && this.context.canOnlyReadRGBA && this.dimPerPixel === 1 ) { // RGBAにパックしてから読み取る必要がある const packed = await this.packToRGBA(); data = (await packed.getData()) as Float32Array; packed.dispose(); return data; } this.bindToDrawTexture(); if (this.context.isWebGL2(gl)) { const buf = new Float32Array( this.textureHeight * this.textureWidth * this.dimPerPixel ); gl.readPixels( 0, 0, this.textureWidth, this.textureHeight, this.dimPerPixel === 1 ? gl.RED : gl.RGBA, gl.FLOAT, buf ); data = new Float32Array(buf.buffer, 0, this.length); } else { const buf = new Uint8Array(this.textureHeight * this.textureWidth * 4); gl.readPixels( 0, 0, this.textureWidth, this.textureHeight, gl.RGBA, gl.UNSIGNED_BYTE, buf ); data = this.unpackColor(buf); } this.unbindFromDrawTexture(); return data; } private unpackColor(buf: Uint8Array): Float32Array { // unpack 8bit texture according to shaderHelper const unpacked = new Float32Array(this.length); for (let i = 0; i < this.length; i++) { const b0 = buf[i * 4]; const b1 = buf[i * 4 + 1]; const b2 = buf[i * 4 + 2]; const b3 = buf[i * 4 + 3]; let val = 0.0; if (b0 > 0) { let sign: number, exponent: number; if (b0 >= 128) { sign = 1.0; exponent = b0 - 192; } else { sign = -1.0; exponent = b0 - 64; } const scaled = b1 / 255 + b2 / (255 * 255) + b3 / (255 * 255 * 255); val = scaled * Math.pow(2, exponent) * sign; } unpacked[i] = val; } return unpacked; } async setData(data: DataArrayTypes): Promise<void> { const { gl } = this.context; this.bindToReadTexture(9); if (this.context.isWebGL2(gl)) { const buf = new Float32Array( this.textureWidth * this.textureHeight * this.dimPerPixel ); buf.set(data); gl.texSubImage2D( gl.TEXTURE_2D, 0, 0, 0, this.textureWidth, this.textureHeight, this.dimPerPixel === 1 ? gl.RED : gl.RGBA, gl.FLOAT, buf ); } else { const buf = this.packColor(data); gl.texSubImage2D( gl.TEXTURE_2D, 0, 0, 0, this.textureWidth, this.textureHeight, gl.RGBA, gl.UNSIGNED_BYTE, buf ); } this.unbindFromReadTexture(); } private packColor(data: DataArrayTypes): Uint8Array { const packed = new Uint8Array(this.textureWidth * this.textureHeight * 4); for (let i = 0; i < this.length; i++) { const val = data[i]; let b0 = 0, b1 = 0, b2 = 0, b3 = 0; if (val !== 0.0) { const sign = val > 0.0 ? 192 : 64; const absval = Math.abs(val); const exponent = Math.ceil(Math.log2(absval) + 0.0001); const scaled = absval * Math.pow(2, -exponent); let s1 = scaled; let s2 = scaled * 255; s2 -= Math.trunc(s2); s1 -= s2 / 255; let s3 = scaled * (255 * 255); s3 -= Math.trunc(s3); s2 -= s3 / 255; b0 = sign + exponent; b1 = Math.min(Math.max(Math.ceil((s1 - 0.5 / 255) * 255), 0), 255); b2 = Math.min(Math.max(Math.ceil((s2 - 0.5 / 255) * 255), 0), 255); b3 = Math.min(Math.max(Math.ceil((s3 - 0.5 / 255) * 255), 0), 255); } packed[i * 4] = b0; packed[i * 4 + 1] = b1; packed[i * 4 + 2] = b2; packed[i * 4 + 3] = b3; } return packed; } dispose(): void { this.sharedTexture.dispose(); } bindToReadTexture(unit: number): void { if (this.isBoundToDrawFrameBuffer) throw Error( "This buffer is already registered as draw buffer. " + "You may forgot to unbind the binding while previous operations." ); const { gl } = this.context; gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, this.getTexture()); this.readTextureUnitIndices.push(unit); } unbindFromReadTexture(): void { const { gl } = this.context; for (const unit of this.readTextureUnitIndices) { gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, null); } this.readTextureUnitIndices = []; } bindToDrawTexture(): void { if (this.readTextureUnitIndices.length > 0) throw Error( "This buffer is already registered as read buffer. " + "You cannot bind a texture as both read and draw texture buffer at same time." ); if (this.isBoundToDrawFrameBuffer) throw Error( "This buffer is already registered as draw buffer. " + "You may forgot to unbind the binding while previous operations." ); const { gl } = this.context; gl.viewport(0, 0, this.textureWidth, this.textureHeight); gl.scissor(0, 0, this.textureWidth, this.textureHeight); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.getTexture(), 0 ); this.isBoundToDrawFrameBuffer = true; } unbindFromDrawTexture(): void { if (!this.isBoundToDrawFrameBuffer) return; const { gl } = this.context; gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, null, 0 ); this.isBoundToDrawFrameBuffer = false; } private async packToRGBA(): Promise<WebGLTensorImpl> { const outputTensor = new WebGLTensorImpl( this.context, this.dims, "float32", 4 ), inputPixels = this.length, outputPixels = Math.ceil(outputTensor.length / 4), kernelName = "RToRGBA"; if (!this.context.hasKernel(kernelName)) { const kernelSource = `${shaderGenHeader(this.context.webgl2)} ${shaderGenTensorOutputUniform(1)} ${shaderGenTensorNDGet("tex_input", 1, this.context.webgl2)} uniform int input_pixels; void main() { ${shaderGenTensorOutputCoordsWithReturn(1)} vec4 result = vec4(0.0, 0.0, 0.0, 0.0); int pos = tex_output_0 * 4; if (pos < input_pixels) { result.r = get_tex_input(pos); } pos++; if (pos < input_pixels) { result.g = get_tex_input(pos); } pos++; if (pos < input_pixels) { result.b = get_tex_input(pos); } pos++; if (pos < input_pixels) { result.a = get_tex_input(pos); } fragColor = result; return; } `; this.context.addKernel(kernelName, kernelSource); } const uniforms: WebGLUniformItem[] = [ ...shaderGenTensorNDGetUniformItem( "tex_input", [1], [this.textureHeight, this.textureWidth], this.context.webgl2 ), ...shaderGenTensorOutputUniformItem( [outputPixels], [outputTensor.textureHeight, outputTensor.textureWidth], this.context.webgl2 ), { name: "input_pixels", type: "int", value: inputPixels }, ]; await this.context.runKernel( kernelName, [{ tensor: this, name: "tex_input" }], outputTensor, uniforms ); return outputTensor; } }
the_stack
import { formatQuery } from '..'; test('When specifying indentation for a query, the relative indentation within closures should be preserved', () => { // Test that relative indentation is preserved between all the lines within a closure when indentation is 0 expect( formatQuery( `g.V(). has('sell_price'). has('buy_price'). project('product', 'profit'). by('name'). by{ it.get().value('sell_price') - it.get().value('buy_price') };`, { indentation: 0, maxLineLength: 70, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe(`g.V(). has('sell_price'). has('buy_price'). project('product', 'profit'). by('name'). by{ it.get().value('sell_price') - it.get().value('buy_price') };`); // Test that relative indentation is preserved between all the lines within a closure when indentation is 20 expect( formatQuery( `g.V(). has('sell_price'). has('buy_price'). project('product', 'profit'). by('name'). by{ it.get().value('sell_price') - it.get().value('buy_price') };`, { indentation: 20, maxLineLength: 70, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe(` g.V(). has('sell_price'). has('buy_price'). project('product', 'profit'). by('name'). by{ it.get().value('sell_price') - it.get().value('buy_price') };`); // Test that relative indentation is preserved in closures which are nested expect( formatQuery( `g.V().filter(out('Sells'). map{ it.get('sell_price') - it.get('buy_price') }. where(gt(50)))`, { indentation: 0, maxLineLength: 45, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe( `g.V(). filter( out('Sells'). map{ it.get('sell_price') - it.get('buy_price') }. where(gt(50)))`, ); expect( formatQuery( `g.V().filter(map{ one = 1 two = 2 three = 3 }))`, { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V().filter(map{ one = 1 two = 2 three = 3 }))`); expect( formatQuery( `g.V().filter(map{ one = 1 two = 2 three = 3 }))`, { indentation: 0, maxLineLength: 28, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V(). filter(map{ one = 1 two = 2 three = 3 }))`); expect( formatQuery( `g.V().filter(map{ one = 1 two = 2 three = 3 }))`, { indentation: 0, maxLineLength: 22, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V(). filter( map{ one = 1 two = 2 three = 3 }))`); expect( formatQuery( `g.V().where(map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`, { indentation: 0, maxLineLength: 60, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V().where(map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`); expect( formatQuery( `g.V().where(map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`, { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V(). where(map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`); expect( formatQuery( `g.V().where(map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`, { indentation: 0, maxLineLength: 45, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V(). where( map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`); expect( formatQuery( `g.V().where(out().map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`, { indentation: 0, maxLineLength: 60, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V().where(out().map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`); expect( formatQuery( `g.V().where(out().map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`, { indentation: 0, maxLineLength: 55, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V(). where(out().map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`); expect( formatQuery( `g.V().where(out().map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`, { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V(). where( out().map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`); expect( formatQuery( `g.V().where(out().map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`, { indentation: 0, maxLineLength: 45, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V(). where( out(). map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }. is(gt(50)))`); // Test that relative indentation is preserved between all the lines within a closure when not all tokens in a stepGroup are methods (for instance, g in g.V() adds to the width of the stepGroup even if it is not a method) expect( formatQuery( `g.V().map({ it.get('sell_price') - it.get('buy_price') }))`, { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe(`g.V().map({ it.get('sell_price') - it.get('buy_price') }))`); // Test that relative indentation is preserved between all the lines within a closure when the first line is indented because the query doesn't start at the beginning of the line expect( formatQuery( `profit = g.V().map({ it.get('sell_price') - it.get('buy_price') }))`, { indentation: 0, maxLineLength: 45, shouldPlaceDotsAfterLineBreaks: false, }, ), ).toBe(`profit = g.V().map({ it.get('sell_price') - it.get('buy_price') }))`); // Test that relative indentation is preserved between all lines within a closure when the method to which the closure is an argument is wrapped expect( formatQuery( `g.V(ids). has('factor_a'). has('factor_b'). project('Factor A', 'Factor B', 'Product'). by(values('factor_a')). by(values('factor_b')). by(map{ it.get().value('factor_a') * it.get().value('factor_b') })`, { indentation: 0, maxLineLength: 40, shouldPlaceDotsAfterLineBreaks: false }, ), ).toBe(`g.V(ids). has('factor_a'). has('factor_b'). project( 'Factor A', 'Factor B', 'Product'). by(values('factor_a')). by(values('factor_b')). by( map{ it.get().value('factor_a') * it.get().value('factor_b') })`); // Test that relative indentation is preserved between all lines within a closure when dots are placed after line breaks // When the whole query is long enough to wrap expect( formatQuery( `g.V(ids). has('factor_a'). has('factor_b'). project('Factor A', 'Factor B', 'Product'). by(values('factor_a')). by(values('factor_b')). by(map{ it.get().value('factor_a') * it.get().value('factor_b') })`, { indentation: 0, maxLineLength: 45, shouldPlaceDotsAfterLineBreaks: true }, ), ).toBe(`g.V(ids) .has('factor_a') .has('factor_b') .project('Factor A', 'Factor B', 'Product') .by(values('factor_a')) .by(values('factor_b')) .by(map{ it.get().value('factor_a') * it.get().value('factor_b') })`); // When the query is long enough to wrap, but the traversal containing the closure is not the first step in its step group and not long enough to wrap expect( formatQuery( `g.V().where(out().map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; })`, { indentation: 0, maxLineLength: 50, shouldPlaceDotsAfterLineBreaks: true }, ), ).toBe(`g.V().where(out().map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; })`); // When the query is long enough to wrap, but the traversal containing the closure is the first step in its step group and not long enough to wrap expect( formatQuery( `g.V().where(out().map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; }.is(gt(50)))`, { indentation: 0, maxLineLength: 45, shouldPlaceDotsAfterLineBreaks: true }, ), ).toBe(`g.V() .where( out() .map{ buyPrice = it.get().value('buy_price'); sellPrice = it.get().value('sell_price'); sellPrice - buyPrice; } .is(gt(50)))`); // When the query is long enough to wrap, but the traversal containing the closure is the first step in its traversal and not long enough to wrap expect( formatQuery( `g.V(ids). has('factor_a'). has('factor_b'). project('Factor A', 'Factor B', 'Product'). by(values('factor_a')). by(values('factor_b')). by(map{ it.get().value('factor_a') * it.get().value('factor_b') })`, { indentation: 0, maxLineLength: 40, shouldPlaceDotsAfterLineBreaks: true }, ), ).toBe(`g.V(ids) .has('factor_a') .has('factor_b') .project( 'Factor A', 'Factor B', 'Product') .by(values('factor_a')) .by(values('factor_b')) .by( map{ it.get().value('factor_a') * it.get().value('factor_b') })`); // When the whole query is short enough to not wrap expect( formatQuery( `g.V().map({ it.get('sell_price') - it.get('buy_price') }))`, { indentation: 0, maxLineLength: 35, shouldPlaceDotsAfterLineBreaks: true, }, ), ).toBe(`g.V().map({ it.get('sell_price') - it.get('buy_price') }))`); });
the_stack
import C from 'xxscreeps/game/constants'; import { assert, describe, simulate, test } from 'xxscreeps/test'; import { RoomPosition } from 'xxscreeps/game/position'; import { create } from './creep'; describe('Movement', () => { const movement = simulate({ W0N0: room => { room['#insertObject'](create(new RoomPosition(25, 25, 'W0N0'), [ C.MOVE ], 'topLeft', '100')); room['#insertObject'](create(new RoomPosition(26, 25, 'W0N0'), [ C.MOVE ], 'topRight', '100')); room['#insertObject'](create(new RoomPosition(25, 26, 'W0N0'), [ C.MOVE ], 'bottomLeft', '100')); room['#insertObject'](create(new RoomPosition(26, 26, 'W0N0'), [ C.MOVE, C.MOVE ], 'bottomRight', '100')); }, }); test('following', () => movement(async({ player, tick }) => { await player('100', Game => { Game.creeps.topLeft.move(C.RIGHT); Game.creeps.topRight.move(C.RIGHT); }); await tick(); await player('100', Game => { assert(Game.creeps.topLeft.pos.isEqualTo(26, 25)); assert(Game.creeps.topRight.pos.isEqualTo(27, 25)); }); })); test('swapping', () => movement(async({ player, tick }) => { await player('100', Game => { Game.creeps.bottomLeft.move(C.TOP); Game.creeps.bottomRight.move(C.LEFT); Game.creeps.topLeft.move(C.RIGHT); Game.creeps.topRight.move(C.LEFT); }); await tick(); await player('100', Game => { assert(Game.creeps.topLeft.pos.isEqualTo(26, 25)); assert(Game.creeps.topRight.pos.isEqualTo(25, 25)); assert(Game.creeps.bottomLeft.pos.isEqualTo(25, 26)); assert(Game.creeps.bottomRight.pos.isEqualTo(26, 26)); }); })); test('swapping second', () => movement(async({ player, tick }) => { await player('100', Game => { Game.creeps.topLeft.move(C.RIGHT); Game.creeps.topRight.move(C.LEFT); Game.creeps.bottomLeft.move(C.TOP); Game.creeps.bottomRight.move(C.LEFT); }); await tick(); await player('100', Game => { assert(Game.creeps.topLeft.pos.isEqualTo(26, 25)); assert(Game.creeps.topRight.pos.isEqualTo(25, 25)); assert(Game.creeps.bottomLeft.pos.isEqualTo(25, 26)); assert(Game.creeps.bottomRight.pos.isEqualTo(26, 26)); }); })); test('swapping against fast', () => movement(async({ player, tick }) => { await player('100', Game => { Game.creeps.bottomRight.move(C.TOP); Game.creeps.topLeft.move(C.RIGHT); Game.creeps.topRight.move(C.LEFT); }); await tick(); await player('100', Game => { assert(Game.creeps.topLeft.pos.isEqualTo(26, 25)); assert(Game.creeps.topRight.pos.isEqualTo(25, 25)); assert(Game.creeps.bottomRight.pos.isEqualTo(26, 26)); }); })); /* // nb: This will pass 1/3 of the time. test('with followers', () => movement(async({ player, tick }) => { await player('100', Game => { Game.creeps.bottomLeft.move(C.TOP_LEFT); Game.creeps.topLeft.move(C.LEFT); Game.creeps.topRight.move(C.LEFT); }); await tick(); await player('100', Game => { assert(Game.creeps.topLeft.pos.isEqualTo(24, 25, 'W0N0')); assert(Game.creeps.bottomLeft.pos.isEqualTo(25, 26, 'W0N0')); }); })); */ const fastSlow = simulate({ W0N0: room => { room['#insertObject'](create(new RoomPosition(25, 25, 'W0N0'), [ C.MOVE, C.MOVE ], 'topLeft', '100')); room['#insertObject'](create(new RoomPosition(25, 26, 'W0N0'), [ C.MOVE ], 'bottomLeft', '100')); }, }); test('fast wins', () => fastSlow(async({ player, tick }) => { await player('100', Game => { Game.creeps.bottomLeft.move(C.TOP_LEFT); Game.creeps.topLeft.move(C.LEFT); }); await tick(); await player('100', Game => { assert(Game.creeps.bottomLeft.pos.isEqualTo(25, 26)); assert(Game.creeps.topLeft.pos.isEqualTo(24, 25)); }); })); const hostile = simulate({ W1N1: room => { room['#level'] = 1; room['#user'] = room.controller!['#user'] = '100'; room['#safeModeUntil'] = 100; room['#insertObject'](create(new RoomPosition(25, 25, 'W1N1'), [ C.MOVE ], 'creep', '100')); room['#insertObject'](create(new RoomPosition(25, 26, 'W1N1'), [ C.MOVE, C.MOVE ], 'creep', '101')); }, }); test('safe mode', () => hostile(async({ player, tick }) => { await player('100', Game => { assert.strictEqual(Game.creeps.creep.move(C.BOTTOM), C.OK); }); await tick(); await player('100', Game => { assert(Game.creeps.creep.pos.isEqualTo(25, 26)); assert.strictEqual(Game.creeps.creep.move(C.TOP), C.OK); }); await player('101', Game => { assert.strictEqual(Game.creeps.creep.move(C.TOP), C.OK); }); await tick(); await player('100', Game => { assert(Game.creeps.creep.pos.isEqualTo(25, 25)); }); })); const enterSameTileOwnerObstacle = simulate({ W2N2: room => { room['#level'] = 1; room['#user'] = room.controller!['#user'] = '100'; room['#safeModeUntil'] = 100; room['#insertObject'](create(new RoomPosition(20, 20, 'W2N2'), [ C.MOVE ], 'owner', '100')); room['#insertObject'](create(new RoomPosition(20, 21, 'W2N2'), [ C.MOVE ], 'ownerObstacle', '100')); room['#insertObject'](create(new RoomPosition(20, 22, 'W2N2'), [ C.MOVE, C.MOVE ], 'hostile2', '101')); }, }); test('safe mode - friendly obstacle', () => enterSameTileOwnerObstacle(async({ player, tick }) => { await player('100', Game => { assert.strictEqual(Game.creeps.owner.move(C.BOTTOM), C.OK); }); await player('101', Game => { assert.strictEqual(Game.creeps.hostile2.move(C.TOP), C.OK); }); await tick(); await player('100', Game => { assert(Game.creeps.ownerObstacle.pos.isEqualTo(20, 21)); assert(Game.creeps.owner.pos.isEqualTo(20, 20)); }); await player('101', Game => { assert(Game.creeps.hostile2.pos.isEqualTo(20, 22)); }); })); const enterSameTileHostileObstacle = simulate({ W2N2: room => { room['#level'] = 1; room['#user'] = room.controller!['#user'] = '100'; room['#safeModeUntil'] = 100; room['#insertObject'](create(new RoomPosition(20, 20, 'W2N2'), [ C.MOVE ], 'owner', '100')); room['#insertObject'](create(new RoomPosition(20, 21, 'W2N2'), [ C.MOVE ], 'hostileObstacle', '101')); room['#insertObject'](create(new RoomPosition(20, 22, 'W2N2'), [ C.MOVE, C.MOVE ], 'hostile2', '101')); }, }); test('safe mode - hostile obstacle', () => enterSameTileHostileObstacle(async({ player, tick }) => { await player('100', Game => { assert.strictEqual(Game.creeps.owner.move(C.BOTTOM), C.OK); }); await player('101', Game => { assert.strictEqual(Game.creeps.hostile2.move(C.TOP), C.OK); }); await tick(); await player('100', Game => { assert(Game.creeps.owner.pos.isEqualTo(20, 21)); }); await player('101', Game => { assert(Game.creeps.hostileObstacle.pos.isEqualTo(20, 21)); assert(Game.creeps.hostile2.pos.isEqualTo(20, 22)); }); })); const enterPossiblyFreeTile = simulate({ W2N2: room => { room['#level'] = 1; room['#user'] = room.controller!['#user'] = '100'; room['#safeModeUntil'] = 100; room['#insertObject'](create(new RoomPosition(20, 20, 'W2N2'), [ C.MOVE ], 'owner', '100')); room['#insertObject'](create(new RoomPosition(19, 21, 'W2N2'), [ C.MOVE ], 'ownerObstacle', '100')); room['#insertObject'](create(new RoomPosition(20, 21, 'W2N2'), [ C.MOVE ], 'hostile', '101')); room['#insertObject'](create(new RoomPosition(20, 22, 'W2N2'), [ C.MOVE, C.MOVE ], 'hostile2', '101')); }, }); test('safe mode - hostile obstacle w/ follower', () => enterPossiblyFreeTile(async({ player, tick }) => { await player('100', Game => { // try to move into hostile position assert(Game.creeps.owner.pos.isEqualTo(20, 20)); assert.strictEqual(Game.creeps.owner.move(C.BOTTOM), C.OK); }); await player('101', Game => { // try to move into ownerObstacle position assert.strictEqual(Game.creeps.hostile.move(C.LEFT), C.OK); // try to move into hostile position assert.strictEqual(Game.creeps.hostile2.move(C.TOP), C.OK); }); await tick(); await player('101', Game => { // hostile & hostile2 did not move assert(Game.creeps.hostile.pos.isEqualTo(20, 21)); assert(Game.creeps.hostile2.pos.isEqualTo(20, 22)); }); await player('100', Game => { // owner moved to hostile position assert(Game.creeps.owner.pos.isEqualTo(20, 21)); assert(Game.creeps.ownerObstacle.pos.isEqualTo(19, 21)); }); })); test('safe mode - hostile conflict w/ follower', () => enterPossiblyFreeTile(async({ player, tick }) => { await player('100', Game => { // move to [21,21] assert.strictEqual(Game.creeps.owner.move(C.BOTTOM_RIGHT), C.OK); }); await player('101', Game => { // move to [21,21] assert.strictEqual(Game.creeps.hostile.move(C.RIGHT), C.OK); // move to `hostile` assert.strictEqual(Game.creeps.hostile2.move(C.TOP), C.OK); }); await tick(); await player('100', Game => { assert(Game.creeps.owner.pos.isEqualTo(21, 21)); }); await player('101', Game => { assert(Game.creeps.hostile.pos.isEqualTo(20, 21)); assert(Game.creeps.hostile2.pos.isEqualTo(20, 22)); }); })); describe('Room', () => { const sim = simulate({ W0N0: room => { room['#insertObject'](create(new RoomPosition(24, 5, 'W0N0'), [ C.MOVE, C.TOUGH, C.TOUGH ], 'slow', '100')); }, }); test('edge fatigue', () => sim(async({ player, tick }) => { await tick(11, { 100: ({ creeps: { slow } }) => { slow.moveTo(new RoomPosition(24, 48, 'W0N1')); }, }); await player('100', ({ creeps: { slow } }) => { assert(slow.pos.isEqualTo(24, 48)); }); })); }); // These tests are adapted from the vanilla server: // https://github.com/screeps/engine/blob/9aa2e113355b35789d975bea2ef49aec37c15185/spec/engine/processor/intents/movementSpec.js#L277-L433 // The coordinates are shifted up by 20 because there's a bunch of rough terrain in the middle of // W0N0 which would obstruct movement. describe('Pull', () => { const sim = simulate({ W0N0: room => { room['#insertObject'](create(new RoomPosition(23, 5, 'W0N0'), [ C.TOUGH ], 'noMove', '100')); room['#insertObject'](create(new RoomPosition(24, 4, 'W0N0'), [ C.MOVE, C.TOUGH, C.TOUGH ], 'halfSpeed', '100')); room['#insertObject'](create(new RoomPosition(25, 3, 'W0N0'), [ C.MOVE, C.TOUGH, C.TOUGH ], 'halfSpeed2', '100')); room['#insertObject'](create(new RoomPosition(24, 5, 'W0N0'), [ C.MOVE, C.TOUGH ], 'fullSpeed', '100')); }, }); test('direction syntax', () => sim(async({ player, tick }) => { await player('100', ({ creeps: { halfSpeed, fullSpeed } }) => { assert.strictEqual(fullSpeed.move(C.BOTTOM), C.OK); assert.strictEqual(fullSpeed.pull(halfSpeed), C.OK); assert.strictEqual(halfSpeed.move(C.BOTTOM), C.OK); }); await tick(); await player('100', ({ creeps: { halfSpeed, fullSpeed } }) => { assert(fullSpeed.pos.isEqualTo(24, 6)); assert(halfSpeed.pos.isEqualTo(24, 5)); assert.strictEqual(halfSpeed.fatigue, 0); assert.strictEqual(fullSpeed.fatigue, 2); }); })); test('creep', () => sim(async({ player, tick }) => { await player('100', ({ creeps: { halfSpeed, fullSpeed } }) => { assert.strictEqual(fullSpeed.move(C.BOTTOM), C.OK); assert.strictEqual(fullSpeed.pull(halfSpeed), C.OK); assert.strictEqual(halfSpeed.move(fullSpeed), C.OK); }); await tick(); await player('100', ({ creeps: { halfSpeed, fullSpeed } }) => { assert(fullSpeed.pos.isEqualTo(24, 6)); assert(halfSpeed.pos.isEqualTo(24, 5)); assert.strictEqual(halfSpeed.fatigue, 0); assert.strictEqual(fullSpeed.fatigue, 2); }); })); test('without follow', () => sim(async({ player, tick }) => { await player('100', ({ creeps: { halfSpeed, fullSpeed } }) => { assert.strictEqual(fullSpeed.move(C.BOTTOM), C.OK); assert.strictEqual(fullSpeed.pull(halfSpeed), C.OK); assert.strictEqual(halfSpeed.move(C.TOP_LEFT), C.OK); }); await tick(); await player('100', ({ creeps: { halfSpeed, fullSpeed } }) => { assert(fullSpeed.pos.isEqualTo(24, 6)); assert(halfSpeed.pos.isEqualTo(23, 3)); assert.strictEqual(halfSpeed.fatigue, 2); assert.strictEqual(fullSpeed.fatigue, 0); }); })); test('no move parts', () => sim(async({ player, tick }) => { await player('100', ({ creeps: { noMove, fullSpeed } }) => { assert.strictEqual(fullSpeed.move(C.TOP_LEFT), C.OK); assert.strictEqual(fullSpeed.pull(noMove), C.OK); assert.strictEqual(noMove.move(fullSpeed), C.OK); }); await tick(); await player('100', ({ creeps: { noMove, fullSpeed } }) => { assert(fullSpeed.pos.isEqualTo(23, 4)); assert(noMove.pos.isEqualTo(24, 5)); assert.strictEqual(noMove.fatigue, 0); assert.strictEqual(fullSpeed.fatigue, 2); }); })); test('with fatigue', () => sim(async({ player, poke, tick }) => { await poke('W0N0', '100', Game => { Game.creeps.halfSpeed.fatigue = 2; }); await player('100', ({ creeps: { halfSpeed, fullSpeed } }) => { assert.strictEqual(halfSpeed.move(fullSpeed), C.OK); assert.strictEqual(fullSpeed.move(C.BOTTOM), C.OK); assert.strictEqual(fullSpeed.pull(halfSpeed), C.OK); }); await tick(); await player('100', ({ creeps: { halfSpeed, fullSpeed } }) => { assert(fullSpeed.pos.isEqualTo(24, 6)); assert(halfSpeed.pos.isEqualTo(24, 5)); assert.strictEqual(halfSpeed.fatigue, 0); assert.strictEqual(fullSpeed.fatigue, 4); }); })); test('cycle', () => sim(async({ player, tick }) => { await player('100', ({ creeps: { halfSpeed, halfSpeed2 } }) => { assert.strictEqual(halfSpeed.move(halfSpeed2), C.OK); assert.strictEqual(halfSpeed.pull(halfSpeed2), C.OK); assert.strictEqual(halfSpeed2.move(halfSpeed), C.OK); assert.strictEqual(halfSpeed2.pull(halfSpeed), C.OK); }); await tick(); await player('100', ({ creeps: { halfSpeed, halfSpeed2 } }) => { assert(halfSpeed.pos.isEqualTo(25, 3)); assert(halfSpeed2.pos.isEqualTo(24, 4)); assert((halfSpeed.fatigue === 0) !== (halfSpeed2.fatigue === 0)); }); })); test('move chain', () => sim(async({ player, tick }) => { await player('100', ({ creeps: { fullSpeed, halfSpeed, halfSpeed2 } }) => { assert.strictEqual(fullSpeed.move(C.BOTTOM), C.OK); assert.strictEqual(fullSpeed.pull(halfSpeed), C.OK); assert.strictEqual(halfSpeed.move(fullSpeed), C.OK); assert.strictEqual(halfSpeed.pull(halfSpeed2), C.OK); assert.strictEqual(halfSpeed2.move(halfSpeed), C.OK); }); await tick(); await player('100', ({ creeps: { halfSpeed, halfSpeed2, fullSpeed } }) => { assert(fullSpeed.pos.isEqualTo(24, 6)); assert(halfSpeed.pos.isEqualTo(24, 5)); assert(halfSpeed2.pos.isEqualTo(24, 4)); assert.strictEqual(fullSpeed.fatigue, 4); assert.strictEqual(halfSpeed.fatigue, 0); assert.strictEqual(halfSpeed2.fatigue, 0); }); })); test('move chain w/ fatigue', () => sim(async({ player, tick, poke }) => { await poke('W0N0', '100', ({ creeps: { halfSpeed, halfSpeed2 } }) => { halfSpeed.fatigue = 2; halfSpeed2.fatigue = 2; }); await player('100', ({ creeps: { fullSpeed, halfSpeed, halfSpeed2 } }) => { assert.strictEqual(fullSpeed.move(C.BOTTOM), C.OK); assert.strictEqual(fullSpeed.pull(halfSpeed), C.OK); assert.strictEqual(halfSpeed.move(fullSpeed), C.OK); assert.strictEqual(halfSpeed.pull(halfSpeed2), C.OK); assert.strictEqual(halfSpeed2.move(halfSpeed), C.OK); }); await tick(); await player('100', ({ creeps: { halfSpeed, halfSpeed2, fullSpeed } }) => { assert(fullSpeed.pos.isEqualTo(24, 6)); assert(halfSpeed.pos.isEqualTo(24, 5)); assert(halfSpeed2.pos.isEqualTo(24, 4)); assert.strictEqual(fullSpeed.fatigue, 8); assert.strictEqual(halfSpeed.fatigue, 0); assert.strictEqual(halfSpeed2.fatigue, 0); }); })); }); });
the_stack
export enum UnicodePoCodePoint { /** * @see https://www.fileformat.info/info/unicode/char/0021/index.htm */ EXCLAMATION_MARK = 0x00021, /** * @see https://www.fileformat.info/info/unicode/char/0022/index.htm */ QUOTATION_MARK = 0x00022, /** * @see https://www.fileformat.info/info/unicode/char/0023/index.htm */ NUMBER_SIGN = 0x00023, /** * @see https://www.fileformat.info/info/unicode/char/0025/index.htm */ PERCENT_SIGN = 0x00025, /** * @see https://www.fileformat.info/info/unicode/char/0026/index.htm */ AMPERSAND = 0x00026, /** * @see https://www.fileformat.info/info/unicode/char/0027/index.htm */ APOSTROPHE = 0x00027, /** * @see https://www.fileformat.info/info/unicode/char/002a/index.htm */ ASTERISK = 0x0002a, /** * @see https://www.fileformat.info/info/unicode/char/002c/index.htm */ COMMA = 0x0002c, /** * @see https://www.fileformat.info/info/unicode/char/002e/index.htm */ FULL_STOP = 0x0002e, /** * @see https://www.fileformat.info/info/unicode/char/002f/index.htm */ SOLIDUS = 0x0002f, /** * @see https://www.fileformat.info/info/unicode/char/003a/index.htm */ COLON = 0x0003a, /** * @see https://www.fileformat.info/info/unicode/char/003b/index.htm */ SEMICOLON = 0x0003b, /** * @see https://www.fileformat.info/info/unicode/char/003f/index.htm */ QUESTION_MARK = 0x0003f, /** * @see https://www.fileformat.info/info/unicode/char/0040/index.htm */ COMMERCIAL_AT = 0x00040, /** * @see https://www.fileformat.info/info/unicode/char/005c/index.htm */ REVERSE_SOLIDUS = 0x0005c, /** * @see https://www.fileformat.info/info/unicode/char/00a1/index.htm */ INVERTED_EXCLAMATION_MARK = 0x000a1, /** * @see https://www.fileformat.info/info/unicode/char/00a7/index.htm */ SECTION_SIGN = 0x000a7, /** * @see https://www.fileformat.info/info/unicode/char/00b6/index.htm */ PILCROW_SIGN = 0x000b6, /** * @see https://www.fileformat.info/info/unicode/char/00b7/index.htm */ MIDDLE_DOT = 0x000b7, /** * @see https://www.fileformat.info/info/unicode/char/00bf/index.htm */ INVERTED_QUESTION_MARK = 0x000bf, /** * @see https://www.fileformat.info/info/unicode/char/037e/index.htm */ GREEK_QUESTION_MARK = 0x0037e, /** * @see https://www.fileformat.info/info/unicode/char/0387/index.htm */ GREEK_ANO_TELEIA = 0x00387, /** * @see https://www.fileformat.info/info/unicode/char/055a/index.htm */ ARMENIAN_APOSTROPHE = 0x0055a, /** * @see https://www.fileformat.info/info/unicode/char/055b/index.htm */ ARMENIAN_EMPHASIS_MARK = 0x0055b, /** * @see https://www.fileformat.info/info/unicode/char/055c/index.htm */ ARMENIAN_EXCLAMATION_MARK = 0x0055c, /** * @see https://www.fileformat.info/info/unicode/char/055d/index.htm */ ARMENIAN_COMMA = 0x0055d, /** * @see https://www.fileformat.info/info/unicode/char/055e/index.htm */ ARMENIAN_QUESTION_MARK = 0x0055e, /** * @see https://www.fileformat.info/info/unicode/char/055f/index.htm */ ARMENIAN_ABBREVIATION_MARK = 0x0055f, /** * @see https://www.fileformat.info/info/unicode/char/0589/index.htm */ ARMENIAN_FULL_STOP = 0x00589, /** * @see https://www.fileformat.info/info/unicode/char/05c0/index.htm */ HEBREW_PUNCTUATION_PASEQ = 0x005c0, /** * @see https://www.fileformat.info/info/unicode/char/05c3/index.htm */ HEBREW_PUNCTUATION_SOF_PASUQ = 0x005c3, /** * @see https://www.fileformat.info/info/unicode/char/05c6/index.htm */ HEBREW_PUNCTUATION_NUN_HAFUKHA = 0x005c6, /** * @see https://www.fileformat.info/info/unicode/char/05f3/index.htm */ HEBREW_PUNCTUATION_GERESH = 0x005f3, /** * @see https://www.fileformat.info/info/unicode/char/05f4/index.htm */ HEBREW_PUNCTUATION_GERSHAYIM = 0x005f4, /** * @see https://www.fileformat.info/info/unicode/char/0609/index.htm */ ARABIC_INDIC_PER_MILLE_SIGN = 0x00609, /** * @see https://www.fileformat.info/info/unicode/char/060a/index.htm */ ARABIC_INDIC_PER_TEN_THOUSAND_SIGN = 0x0060a, /** * @see https://www.fileformat.info/info/unicode/char/060c/index.htm */ ARABIC_COMMA = 0x0060c, /** * @see https://www.fileformat.info/info/unicode/char/060d/index.htm */ ARABIC_DATE_SEPARATOR = 0x0060d, /** * @see https://www.fileformat.info/info/unicode/char/061b/index.htm */ ARABIC_SEMICOLON = 0x0061b, /** * @see https://www.fileformat.info/info/unicode/char/061e/index.htm */ ARABIC_TRIPLE_DOT_PUNCTUATION_MARK = 0x0061e, /** * @see https://www.fileformat.info/info/unicode/char/061f/index.htm */ ARABIC_QUESTION_MARK = 0x0061f, /** * @see https://www.fileformat.info/info/unicode/char/066a/index.htm */ ARABIC_PERCENT_SIGN = 0x0066a, /** * @see https://www.fileformat.info/info/unicode/char/066b/index.htm */ ARABIC_DECIMAL_SEPARATOR = 0x0066b, /** * @see https://www.fileformat.info/info/unicode/char/066c/index.htm */ ARABIC_THOUSANDS_SEPARATOR = 0x0066c, /** * @see https://www.fileformat.info/info/unicode/char/066d/index.htm */ ARABIC_FIVE_POINTED_STAR = 0x0066d, /** * @see https://www.fileformat.info/info/unicode/char/06d4/index.htm */ ARABIC_FULL_STOP = 0x006d4, /** * @see https://www.fileformat.info/info/unicode/char/0700/index.htm */ SYRIAC_END_OF_PARAGRAPH = 0x00700, /** * @see https://www.fileformat.info/info/unicode/char/0701/index.htm */ SYRIAC_SUPRALINEAR_FULL_STOP = 0x00701, /** * @see https://www.fileformat.info/info/unicode/char/0702/index.htm */ SYRIAC_SUBLINEAR_FULL_STOP = 0x00702, /** * @see https://www.fileformat.info/info/unicode/char/0703/index.htm */ SYRIAC_SUPRALINEAR_COLON = 0x00703, /** * @see https://www.fileformat.info/info/unicode/char/0704/index.htm */ SYRIAC_SUBLINEAR_COLON = 0x00704, /** * @see https://www.fileformat.info/info/unicode/char/0705/index.htm */ SYRIAC_HORIZONTAL_COLON = 0x00705, /** * @see https://www.fileformat.info/info/unicode/char/0706/index.htm */ SYRIAC_COLON_SKEWED_LEFT = 0x00706, /** * @see https://www.fileformat.info/info/unicode/char/0707/index.htm */ SYRIAC_COLON_SKEWED_RIGHT = 0x00707, /** * @see https://www.fileformat.info/info/unicode/char/0708/index.htm */ SYRIAC_SUPRALINEAR_COLON_SKEWED_LEFT = 0x00708, /** * @see https://www.fileformat.info/info/unicode/char/0709/index.htm */ SYRIAC_SUBLINEAR_COLON_SKEWED_RIGHT = 0x00709, /** * @see https://www.fileformat.info/info/unicode/char/070a/index.htm */ SYRIAC_CONTRACTION = 0x0070a, /** * @see https://www.fileformat.info/info/unicode/char/070b/index.htm */ SYRIAC_HARKLEAN_OBELUS = 0x0070b, /** * @see https://www.fileformat.info/info/unicode/char/070c/index.htm */ SYRIAC_HARKLEAN_METOBELUS = 0x0070c, /** * @see https://www.fileformat.info/info/unicode/char/070d/index.htm */ SYRIAC_HARKLEAN_ASTERISCUS = 0x0070d, /** * @see https://www.fileformat.info/info/unicode/char/07f7/index.htm */ NKO_SYMBOL_GBAKURUNEN = 0x007f7, /** * @see https://www.fileformat.info/info/unicode/char/07f8/index.htm */ NKO_COMMA = 0x007f8, /** * @see https://www.fileformat.info/info/unicode/char/07f9/index.htm */ NKO_EXCLAMATION_MARK = 0x007f9, /** * @see https://www.fileformat.info/info/unicode/char/0830/index.htm */ SAMARITAN_PUNCTUATION_NEQUDAA = 0x00830, /** * @see https://www.fileformat.info/info/unicode/char/0831/index.htm */ SAMARITAN_PUNCTUATION_AFSAAQ = 0x00831, /** * @see https://www.fileformat.info/info/unicode/char/0832/index.htm */ SAMARITAN_PUNCTUATION_ANGED = 0x00832, /** * @see https://www.fileformat.info/info/unicode/char/0833/index.htm */ SAMARITAN_PUNCTUATION_BAU = 0x00833, /** * @see https://www.fileformat.info/info/unicode/char/0834/index.htm */ SAMARITAN_PUNCTUATION_ATMAAU = 0x00834, /** * @see https://www.fileformat.info/info/unicode/char/0835/index.htm */ SAMARITAN_PUNCTUATION_SHIYYAALAA = 0x00835, /** * @see https://www.fileformat.info/info/unicode/char/0836/index.htm */ SAMARITAN_ABBREVIATION_MARK = 0x00836, /** * @see https://www.fileformat.info/info/unicode/char/0837/index.htm */ SAMARITAN_PUNCTUATION_MELODIC_QITSA = 0x00837, /** * @see https://www.fileformat.info/info/unicode/char/0838/index.htm */ SAMARITAN_PUNCTUATION_ZIQAA = 0x00838, /** * @see https://www.fileformat.info/info/unicode/char/0839/index.htm */ SAMARITAN_PUNCTUATION_QITSA = 0x00839, /** * @see https://www.fileformat.info/info/unicode/char/083a/index.htm */ SAMARITAN_PUNCTUATION_ZAEF = 0x0083a, /** * @see https://www.fileformat.info/info/unicode/char/083b/index.htm */ SAMARITAN_PUNCTUATION_TURU = 0x0083b, /** * @see https://www.fileformat.info/info/unicode/char/083c/index.htm */ SAMARITAN_PUNCTUATION_ARKAANU = 0x0083c, /** * @see https://www.fileformat.info/info/unicode/char/083d/index.htm */ SAMARITAN_PUNCTUATION_SOF_MASHFAAT = 0x0083d, /** * @see https://www.fileformat.info/info/unicode/char/083e/index.htm */ SAMARITAN_PUNCTUATION_ANNAAU = 0x0083e, /** * @see https://www.fileformat.info/info/unicode/char/085e/index.htm */ MANDAIC_PUNCTUATION = 0x0085e, /** * @see https://www.fileformat.info/info/unicode/char/0964/index.htm */ DEVANAGARI_DANDA = 0x00964, /** * @see https://www.fileformat.info/info/unicode/char/0965/index.htm */ DEVANAGARI_DOUBLE_DANDA = 0x00965, /** * @see https://www.fileformat.info/info/unicode/char/0970/index.htm */ DEVANAGARI_ABBREVIATION_SIGN = 0x00970, /** * @see https://www.fileformat.info/info/unicode/char/09fd/index.htm */ BENGALI_ABBREVIATION_SIGN = 0x009fd, /** * @see https://www.fileformat.info/info/unicode/char/0a76/index.htm */ GURMUKHI_ABBREVIATION_SIGN = 0x00a76, /** * @see https://www.fileformat.info/info/unicode/char/0af0/index.htm */ GUJARATI_ABBREVIATION_SIGN = 0x00af0, /** * @see https://www.fileformat.info/info/unicode/char/0c77/index.htm */ TELUGU_SIGN_SIDDHAM = 0x00c77, /** * @see https://www.fileformat.info/info/unicode/char/0c84/index.htm */ KANNADA_SIGN_SIDDHAM = 0x00c84, /** * @see https://www.fileformat.info/info/unicode/char/0df4/index.htm */ SINHALA_PUNCTUATION_KUNDDALIYA = 0x00df4, /** * @see https://www.fileformat.info/info/unicode/char/0e4f/index.htm */ THAI_CHARACTER_FONGMAN = 0x00e4f, /** * @see https://www.fileformat.info/info/unicode/char/0e5a/index.htm */ THAI_CHARACTER_ANGKHANKHU = 0x00e5a, /** * @see https://www.fileformat.info/info/unicode/char/0e5b/index.htm */ THAI_CHARACTER_KHOMUT = 0x00e5b, /** * @see https://www.fileformat.info/info/unicode/char/0f04/index.htm */ TIBETAN_MARK_INITIAL_YIG_MGO_MDUN_MA = 0x00f04, /** * @see https://www.fileformat.info/info/unicode/char/0f05/index.htm */ TIBETAN_MARK_CLOSING_YIG_MGO_SGAB_MA = 0x00f05, /** * @see https://www.fileformat.info/info/unicode/char/0f06/index.htm */ TIBETAN_MARK_CARET_YIG_MGO_PHUR_SHAD_MA = 0x00f06, /** * @see https://www.fileformat.info/info/unicode/char/0f07/index.htm */ TIBETAN_MARK_YIG_MGO_TSHEG_SHAD_MA = 0x00f07, /** * @see https://www.fileformat.info/info/unicode/char/0f08/index.htm */ TIBETAN_MARK_SBRUL_SHAD = 0x00f08, /** * @see https://www.fileformat.info/info/unicode/char/0f09/index.htm */ TIBETAN_MARK_BSKUR_YIG_MGO = 0x00f09, /** * @see https://www.fileformat.info/info/unicode/char/0f0a/index.htm */ TIBETAN_MARK_BKA__SHOG_YIG_MGO = 0x00f0a, /** * @see https://www.fileformat.info/info/unicode/char/0f0b/index.htm */ TIBETAN_MARK_INTERSYLLABIC_TSHEG = 0x00f0b, /** * @see https://www.fileformat.info/info/unicode/char/0f0c/index.htm */ TIBETAN_MARK_DELIMITER_TSHEG_BSTAR = 0x00f0c, /** * @see https://www.fileformat.info/info/unicode/char/0f0d/index.htm */ TIBETAN_MARK_SHAD = 0x00f0d, /** * @see https://www.fileformat.info/info/unicode/char/0f0e/index.htm */ TIBETAN_MARK_NYIS_SHAD = 0x00f0e, /** * @see https://www.fileformat.info/info/unicode/char/0f0f/index.htm */ TIBETAN_MARK_TSHEG_SHAD = 0x00f0f, /** * @see https://www.fileformat.info/info/unicode/char/0f10/index.htm */ TIBETAN_MARK_NYIS_TSHEG_SHAD = 0x00f10, /** * @see https://www.fileformat.info/info/unicode/char/0f11/index.htm */ TIBETAN_MARK_RIN_CHEN_SPUNGS_SHAD = 0x00f11, /** * @see https://www.fileformat.info/info/unicode/char/0f12/index.htm */ TIBETAN_MARK_RGYA_GRAM_SHAD = 0x00f12, /** * @see https://www.fileformat.info/info/unicode/char/0f14/index.htm */ TIBETAN_MARK_GTER_TSHEG = 0x00f14, /** * @see https://www.fileformat.info/info/unicode/char/0f85/index.htm */ TIBETAN_MARK_PALUTA = 0x00f85, /** * @see https://www.fileformat.info/info/unicode/char/0fd0/index.htm */ TIBETAN_MARK_BSKA__SHOG_GI_MGO_RGYAN = 0x00fd0, /** * @see https://www.fileformat.info/info/unicode/char/0fd1/index.htm */ TIBETAN_MARK_MNYAM_YIG_GI_MGO_RGYAN = 0x00fd1, /** * @see https://www.fileformat.info/info/unicode/char/0fd2/index.htm */ TIBETAN_MARK_NYIS_TSHEG = 0x00fd2, /** * @see https://www.fileformat.info/info/unicode/char/0fd3/index.htm */ TIBETAN_MARK_INITIAL_BRDA_RNYING_YIG_MGO_MDUN_MA = 0x00fd3, /** * @see https://www.fileformat.info/info/unicode/char/0fd4/index.htm */ TIBETAN_MARK_CLOSING_BRDA_RNYING_YIG_MGO_SGAB_MA = 0x00fd4, /** * @see https://www.fileformat.info/info/unicode/char/0fd9/index.htm */ TIBETAN_MARK_LEADING_MCHAN_RTAGS = 0x00fd9, /** * @see https://www.fileformat.info/info/unicode/char/0fda/index.htm */ TIBETAN_MARK_TRAILING_MCHAN_RTAGS = 0x00fda, /** * @see https://www.fileformat.info/info/unicode/char/104a/index.htm */ MYANMAR_SIGN_LITTLE_SECTION = 0x0104a, /** * @see https://www.fileformat.info/info/unicode/char/104b/index.htm */ MYANMAR_SIGN_SECTION = 0x0104b, /** * @see https://www.fileformat.info/info/unicode/char/104c/index.htm */ MYANMAR_SYMBOL_LOCATIVE = 0x0104c, /** * @see https://www.fileformat.info/info/unicode/char/104d/index.htm */ MYANMAR_SYMBOL_COMPLETED = 0x0104d, /** * @see https://www.fileformat.info/info/unicode/char/104e/index.htm */ MYANMAR_SYMBOL_AFOREMENTIONED = 0x0104e, /** * @see https://www.fileformat.info/info/unicode/char/104f/index.htm */ MYANMAR_SYMBOL_GENITIVE = 0x0104f, /** * @see https://www.fileformat.info/info/unicode/char/10fb/index.htm */ GEORGIAN_PARAGRAPH_SEPARATOR = 0x010fb, /** * @see https://www.fileformat.info/info/unicode/char/1360/index.htm */ ETHIOPIC_SECTION_MARK = 0x01360, /** * @see https://www.fileformat.info/info/unicode/char/1361/index.htm */ ETHIOPIC_WORDSPACE = 0x01361, /** * @see https://www.fileformat.info/info/unicode/char/1362/index.htm */ ETHIOPIC_FULL_STOP = 0x01362, /** * @see https://www.fileformat.info/info/unicode/char/1363/index.htm */ ETHIOPIC_COMMA = 0x01363, /** * @see https://www.fileformat.info/info/unicode/char/1364/index.htm */ ETHIOPIC_SEMICOLON = 0x01364, /** * @see https://www.fileformat.info/info/unicode/char/1365/index.htm */ ETHIOPIC_COLON = 0x01365, /** * @see https://www.fileformat.info/info/unicode/char/1366/index.htm */ ETHIOPIC_PREFACE_COLON = 0x01366, /** * @see https://www.fileformat.info/info/unicode/char/1367/index.htm */ ETHIOPIC_QUESTION_MARK = 0x01367, /** * @see https://www.fileformat.info/info/unicode/char/1368/index.htm */ ETHIOPIC_PARAGRAPH_SEPARATOR = 0x01368, /** * @see https://www.fileformat.info/info/unicode/char/166e/index.htm */ CANADIAN_SYLLABICS_FULL_STOP = 0x0166e, /** * @see https://www.fileformat.info/info/unicode/char/16eb/index.htm */ RUNIC_SINGLE_PUNCTUATION = 0x016eb, /** * @see https://www.fileformat.info/info/unicode/char/16ec/index.htm */ RUNIC_MULTIPLE_PUNCTUATION = 0x016ec, /** * @see https://www.fileformat.info/info/unicode/char/16ed/index.htm */ RUNIC_CROSS_PUNCTUATION = 0x016ed, /** * @see https://www.fileformat.info/info/unicode/char/1735/index.htm */ PHILIPPINE_SINGLE_PUNCTUATION = 0x01735, /** * @see https://www.fileformat.info/info/unicode/char/1736/index.htm */ PHILIPPINE_DOUBLE_PUNCTUATION = 0x01736, /** * @see https://www.fileformat.info/info/unicode/char/17d4/index.htm */ KHMER_SIGN_KHAN = 0x017d4, /** * @see https://www.fileformat.info/info/unicode/char/17d5/index.htm */ KHMER_SIGN_BARIYOOSAN = 0x017d5, /** * @see https://www.fileformat.info/info/unicode/char/17d6/index.htm */ KHMER_SIGN_CAMNUC_PII_KUUH = 0x017d6, /** * @see https://www.fileformat.info/info/unicode/char/17d8/index.htm */ KHMER_SIGN_BEYYAL = 0x017d8, /** * @see https://www.fileformat.info/info/unicode/char/17d9/index.htm */ KHMER_SIGN_PHNAEK_MUAN = 0x017d9, /** * @see https://www.fileformat.info/info/unicode/char/17da/index.htm */ KHMER_SIGN_KOOMUUT = 0x017da, /** * @see https://www.fileformat.info/info/unicode/char/1800/index.htm */ MONGOLIAN_BIRGA = 0x01800, /** * @see https://www.fileformat.info/info/unicode/char/1801/index.htm */ MONGOLIAN_ELLIPSIS = 0x01801, /** * @see https://www.fileformat.info/info/unicode/char/1802/index.htm */ MONGOLIAN_COMMA = 0x01802, /** * @see https://www.fileformat.info/info/unicode/char/1803/index.htm */ MONGOLIAN_FULL_STOP = 0x01803, /** * @see https://www.fileformat.info/info/unicode/char/1804/index.htm */ MONGOLIAN_COLON = 0x01804, /** * @see https://www.fileformat.info/info/unicode/char/1805/index.htm */ MONGOLIAN_FOUR_DOTS = 0x01805, /** * @see https://www.fileformat.info/info/unicode/char/1807/index.htm */ MONGOLIAN_SIBE_SYLLABLE_BOUNDARY_MARKER = 0x01807, /** * @see https://www.fileformat.info/info/unicode/char/1808/index.htm */ MONGOLIAN_MANCHU_COMMA = 0x01808, /** * @see https://www.fileformat.info/info/unicode/char/1809/index.htm */ MONGOLIAN_MANCHU_FULL_STOP = 0x01809, /** * @see https://www.fileformat.info/info/unicode/char/180a/index.htm */ MONGOLIAN_NIRUGU = 0x0180a, /** * @see https://www.fileformat.info/info/unicode/char/1944/index.htm */ LIMBU_EXCLAMATION_MARK = 0x01944, /** * @see https://www.fileformat.info/info/unicode/char/1945/index.htm */ LIMBU_QUESTION_MARK = 0x01945, /** * @see https://www.fileformat.info/info/unicode/char/1a1e/index.htm */ BUGINESE_PALLAWA = 0x01a1e, /** * @see https://www.fileformat.info/info/unicode/char/1a1f/index.htm */ BUGINESE_END_OF_SECTION = 0x01a1f, /** * @see https://www.fileformat.info/info/unicode/char/1aa0/index.htm */ TAI_THAM_SIGN_WIANG = 0x01aa0, /** * @see https://www.fileformat.info/info/unicode/char/1aa1/index.htm */ TAI_THAM_SIGN_WIANGWAAK = 0x01aa1, /** * @see https://www.fileformat.info/info/unicode/char/1aa2/index.htm */ TAI_THAM_SIGN_SAWAN = 0x01aa2, /** * @see https://www.fileformat.info/info/unicode/char/1aa3/index.htm */ TAI_THAM_SIGN_KEOW = 0x01aa3, /** * @see https://www.fileformat.info/info/unicode/char/1aa4/index.htm */ TAI_THAM_SIGN_HOY = 0x01aa4, /** * @see https://www.fileformat.info/info/unicode/char/1aa5/index.htm */ TAI_THAM_SIGN_DOKMAI = 0x01aa5, /** * @see https://www.fileformat.info/info/unicode/char/1aa6/index.htm */ TAI_THAM_SIGN_REVERSED_ROTATED_RANA = 0x01aa6, /** * @see https://www.fileformat.info/info/unicode/char/1aa8/index.htm */ TAI_THAM_SIGN_KAAN = 0x01aa8, /** * @see https://www.fileformat.info/info/unicode/char/1aa9/index.htm */ TAI_THAM_SIGN_KAANKUU = 0x01aa9, /** * @see https://www.fileformat.info/info/unicode/char/1aaa/index.htm */ TAI_THAM_SIGN_SATKAAN = 0x01aaa, /** * @see https://www.fileformat.info/info/unicode/char/1aab/index.htm */ TAI_THAM_SIGN_SATKAANKUU = 0x01aab, /** * @see https://www.fileformat.info/info/unicode/char/1aac/index.htm */ TAI_THAM_SIGN_HANG = 0x01aac, /** * @see https://www.fileformat.info/info/unicode/char/1aad/index.htm */ TAI_THAM_SIGN_CAANG = 0x01aad, /** * @see https://www.fileformat.info/info/unicode/char/1b5a/index.htm */ BALINESE_PANTI = 0x01b5a, /** * @see https://www.fileformat.info/info/unicode/char/1b5b/index.htm */ BALINESE_PAMADA = 0x01b5b, /** * @see https://www.fileformat.info/info/unicode/char/1b5c/index.htm */ BALINESE_WINDU = 0x01b5c, /** * @see https://www.fileformat.info/info/unicode/char/1b5d/index.htm */ BALINESE_CARIK_PAMUNGKAH = 0x01b5d, /** * @see https://www.fileformat.info/info/unicode/char/1b5e/index.htm */ BALINESE_CARIK_SIKI = 0x01b5e, /** * @see https://www.fileformat.info/info/unicode/char/1b5f/index.htm */ BALINESE_CARIK_PAREREN = 0x01b5f, /** * @see https://www.fileformat.info/info/unicode/char/1b60/index.htm */ BALINESE_PAMENENG = 0x01b60, /** * @see https://www.fileformat.info/info/unicode/char/1bfc/index.htm */ BATAK_SYMBOL_BINDU_NA_METEK = 0x01bfc, /** * @see https://www.fileformat.info/info/unicode/char/1bfd/index.htm */ BATAK_SYMBOL_BINDU_PINARBORAS = 0x01bfd, /** * @see https://www.fileformat.info/info/unicode/char/1bfe/index.htm */ BATAK_SYMBOL_BINDU_JUDUL = 0x01bfe, /** * @see https://www.fileformat.info/info/unicode/char/1bff/index.htm */ BATAK_SYMBOL_BINDU_PANGOLAT = 0x01bff, /** * @see https://www.fileformat.info/info/unicode/char/1c3b/index.htm */ LEPCHA_PUNCTUATION_TA_ROL = 0x01c3b, /** * @see https://www.fileformat.info/info/unicode/char/1c3c/index.htm */ LEPCHA_PUNCTUATION_NYET_THYOOM_TA_ROL = 0x01c3c, /** * @see https://www.fileformat.info/info/unicode/char/1c3d/index.htm */ LEPCHA_PUNCTUATION_CER_WA = 0x01c3d, /** * @see https://www.fileformat.info/info/unicode/char/1c3e/index.htm */ LEPCHA_PUNCTUATION_TSHOOK_CER_WA = 0x01c3e, /** * @see https://www.fileformat.info/info/unicode/char/1c3f/index.htm */ LEPCHA_PUNCTUATION_TSHOOK = 0x01c3f, /** * @see https://www.fileformat.info/info/unicode/char/1c7e/index.htm */ OL_CHIKI_PUNCTUATION_MUCAAD = 0x01c7e, /** * @see https://www.fileformat.info/info/unicode/char/1c7f/index.htm */ OL_CHIKI_PUNCTUATION_DOUBLE_MUCAAD = 0x01c7f, /** * @see https://www.fileformat.info/info/unicode/char/1cc0/index.htm */ SUNDANESE_PUNCTUATION_BINDU_SURYA = 0x01cc0, /** * @see https://www.fileformat.info/info/unicode/char/1cc1/index.htm */ SUNDANESE_PUNCTUATION_BINDU_PANGLONG = 0x01cc1, /** * @see https://www.fileformat.info/info/unicode/char/1cc2/index.htm */ SUNDANESE_PUNCTUATION_BINDU_PURNAMA = 0x01cc2, /** * @see https://www.fileformat.info/info/unicode/char/1cc3/index.htm */ SUNDANESE_PUNCTUATION_BINDU_CAKRA = 0x01cc3, /** * @see https://www.fileformat.info/info/unicode/char/1cc4/index.htm */ SUNDANESE_PUNCTUATION_BINDU_LEU_SATANGA = 0x01cc4, /** * @see https://www.fileformat.info/info/unicode/char/1cc5/index.htm */ SUNDANESE_PUNCTUATION_BINDU_KA_SATANGA = 0x01cc5, /** * @see https://www.fileformat.info/info/unicode/char/1cc6/index.htm */ SUNDANESE_PUNCTUATION_BINDU_DA_SATANGA = 0x01cc6, /** * @see https://www.fileformat.info/info/unicode/char/1cc7/index.htm */ SUNDANESE_PUNCTUATION_BINDU_BA_SATANGA = 0x01cc7, /** * @see https://www.fileformat.info/info/unicode/char/1cd3/index.htm */ VEDIC_SIGN_NIHSHVASA = 0x01cd3, /** * @see https://www.fileformat.info/info/unicode/char/2016/index.htm */ DOUBLE_VERTICAL_LINE = 0x02016, /** * @see https://www.fileformat.info/info/unicode/char/2017/index.htm */ DOUBLE_LOW_LINE = 0x02017, /** * @see https://www.fileformat.info/info/unicode/char/2020/index.htm */ DAGGER = 0x02020, /** * @see https://www.fileformat.info/info/unicode/char/2021/index.htm */ DOUBLE_DAGGER = 0x02021, /** * @see https://www.fileformat.info/info/unicode/char/2022/index.htm */ BULLET = 0x02022, /** * @see https://www.fileformat.info/info/unicode/char/2023/index.htm */ TRIANGULAR_BULLET = 0x02023, /** * @see https://www.fileformat.info/info/unicode/char/2024/index.htm */ ONE_DOT_LEADER = 0x02024, /** * @see https://www.fileformat.info/info/unicode/char/2025/index.htm */ TWO_DOT_LEADER = 0x02025, /** * @see https://www.fileformat.info/info/unicode/char/2026/index.htm */ HORIZONTAL_ELLIPSIS = 0x02026, /** * @see https://www.fileformat.info/info/unicode/char/2027/index.htm */ HYPHENATION_POINT = 0x02027, /** * @see https://www.fileformat.info/info/unicode/char/2030/index.htm */ PER_MILLE_SIGN = 0x02030, /** * @see https://www.fileformat.info/info/unicode/char/2031/index.htm */ PER_TEN_THOUSAND_SIGN = 0x02031, /** * @see https://www.fileformat.info/info/unicode/char/2032/index.htm */ PRIME = 0x02032, /** * @see https://www.fileformat.info/info/unicode/char/2033/index.htm */ DOUBLE_PRIME = 0x02033, /** * @see https://www.fileformat.info/info/unicode/char/2034/index.htm */ TRIPLE_PRIME = 0x02034, /** * @see https://www.fileformat.info/info/unicode/char/2035/index.htm */ REVERSED_PRIME = 0x02035, /** * @see https://www.fileformat.info/info/unicode/char/2036/index.htm */ REVERSED_DOUBLE_PRIME = 0x02036, /** * @see https://www.fileformat.info/info/unicode/char/2037/index.htm */ REVERSED_TRIPLE_PRIME = 0x02037, /** * @see https://www.fileformat.info/info/unicode/char/2038/index.htm */ CARET = 0x02038, /** * @see https://www.fileformat.info/info/unicode/char/203b/index.htm */ REFERENCE_MARK = 0x0203b, /** * @see https://www.fileformat.info/info/unicode/char/203c/index.htm */ DOUBLE_EXCLAMATION_MARK = 0x0203c, /** * @see https://www.fileformat.info/info/unicode/char/203d/index.htm */ INTERROBANG = 0x0203d, /** * @see https://www.fileformat.info/info/unicode/char/203e/index.htm */ OVERLINE = 0x0203e, /** * @see https://www.fileformat.info/info/unicode/char/2041/index.htm */ CARET_INSERTION_POINT = 0x02041, /** * @see https://www.fileformat.info/info/unicode/char/2042/index.htm */ ASTERISM = 0x02042, /** * @see https://www.fileformat.info/info/unicode/char/2043/index.htm */ HYPHEN_BULLET = 0x02043, /** * @see https://www.fileformat.info/info/unicode/char/2047/index.htm */ DOUBLE_QUESTION_MARK = 0x02047, /** * @see https://www.fileformat.info/info/unicode/char/2048/index.htm */ QUESTION_EXCLAMATION_MARK = 0x02048, /** * @see https://www.fileformat.info/info/unicode/char/2049/index.htm */ EXCLAMATION_QUESTION_MARK = 0x02049, /** * @see https://www.fileformat.info/info/unicode/char/204a/index.htm */ TIRONIAN_SIGN_ET = 0x0204a, /** * @see https://www.fileformat.info/info/unicode/char/204b/index.htm */ REVERSED_PILCROW_SIGN = 0x0204b, /** * @see https://www.fileformat.info/info/unicode/char/204c/index.htm */ BLACK_LEFTWARDS_BULLET = 0x0204c, /** * @see https://www.fileformat.info/info/unicode/char/204d/index.htm */ BLACK_RIGHTWARDS_BULLET = 0x0204d, /** * @see https://www.fileformat.info/info/unicode/char/204e/index.htm */ LOW_ASTERISK = 0x0204e, /** * @see https://www.fileformat.info/info/unicode/char/204f/index.htm */ REVERSED_SEMICOLON = 0x0204f, /** * @see https://www.fileformat.info/info/unicode/char/2050/index.htm */ CLOSE_UP = 0x02050, /** * @see https://www.fileformat.info/info/unicode/char/2051/index.htm */ TWO_ASTERISKS_ALIGNED_VERTICALLY = 0x02051, /** * @see https://www.fileformat.info/info/unicode/char/2053/index.htm */ SWUNG_DASH = 0x02053, /** * @see https://www.fileformat.info/info/unicode/char/2055/index.htm */ FLOWER_PUNCTUATION_MARK = 0x02055, /** * @see https://www.fileformat.info/info/unicode/char/2056/index.htm */ THREE_DOT_PUNCTUATION = 0x02056, /** * @see https://www.fileformat.info/info/unicode/char/2057/index.htm */ QUADRUPLE_PRIME = 0x02057, /** * @see https://www.fileformat.info/info/unicode/char/2058/index.htm */ FOUR_DOT_PUNCTUATION = 0x02058, /** * @see https://www.fileformat.info/info/unicode/char/2059/index.htm */ FIVE_DOT_PUNCTUATION = 0x02059, /** * @see https://www.fileformat.info/info/unicode/char/205a/index.htm */ TWO_DOT_PUNCTUATION = 0x0205a, /** * @see https://www.fileformat.info/info/unicode/char/205b/index.htm */ FOUR_DOT_MARK = 0x0205b, /** * @see https://www.fileformat.info/info/unicode/char/205c/index.htm */ DOTTED_CROSS = 0x0205c, /** * @see https://www.fileformat.info/info/unicode/char/205d/index.htm */ TRICOLON = 0x0205d, /** * @see https://www.fileformat.info/info/unicode/char/205e/index.htm */ VERTICAL_FOUR_DOTS = 0x0205e, /** * @see https://www.fileformat.info/info/unicode/char/2cf9/index.htm */ COPTIC_OLD_NUBIAN_FULL_STOP = 0x02cf9, /** * @see https://www.fileformat.info/info/unicode/char/2cfa/index.htm */ COPTIC_OLD_NUBIAN_DIRECT_QUESTION_MARK = 0x02cfa, /** * @see https://www.fileformat.info/info/unicode/char/2cfb/index.htm */ COPTIC_OLD_NUBIAN_INDIRECT_QUESTION_MARK = 0x02cfb, /** * @see https://www.fileformat.info/info/unicode/char/2cfc/index.htm */ COPTIC_OLD_NUBIAN_VERSE_DIVIDER = 0x02cfc, /** * @see https://www.fileformat.info/info/unicode/char/2cfe/index.htm */ COPTIC_FULL_STOP = 0x02cfe, /** * @see https://www.fileformat.info/info/unicode/char/2cff/index.htm */ COPTIC_MORPHOLOGICAL_DIVIDER = 0x02cff, /** * @see https://www.fileformat.info/info/unicode/char/2d70/index.htm */ TIFINAGH_SEPARATOR_MARK = 0x02d70, /** * @see https://www.fileformat.info/info/unicode/char/2e00/index.htm */ RIGHT_ANGLE_SUBSTITUTION_MARKER = 0x02e00, /** * @see https://www.fileformat.info/info/unicode/char/2e01/index.htm */ RIGHT_ANGLE_DOTTED_SUBSTITUTION_MARKER = 0x02e01, /** * @see https://www.fileformat.info/info/unicode/char/2e06/index.htm */ RAISED_INTERPOLATION_MARKER = 0x02e06, /** * @see https://www.fileformat.info/info/unicode/char/2e07/index.htm */ RAISED_DOTTED_INTERPOLATION_MARKER = 0x02e07, /** * @see https://www.fileformat.info/info/unicode/char/2e08/index.htm */ DOTTED_TRANSPOSITION_MARKER = 0x02e08, /** * @see https://www.fileformat.info/info/unicode/char/2e0b/index.htm */ RAISED_SQUARE = 0x02e0b, /** * @see https://www.fileformat.info/info/unicode/char/2e0e/index.htm */ EDITORIAL_CORONIS = 0x02e0e, /** * @see https://www.fileformat.info/info/unicode/char/2e0f/index.htm */ PARAGRAPHOS = 0x02e0f, /** * @see https://www.fileformat.info/info/unicode/char/2e10/index.htm */ FORKED_PARAGRAPHOS = 0x02e10, /** * @see https://www.fileformat.info/info/unicode/char/2e11/index.htm */ REVERSED_FORKED_PARAGRAPHOS = 0x02e11, /** * @see https://www.fileformat.info/info/unicode/char/2e12/index.htm */ HYPODIASTOLE = 0x02e12, /** * @see https://www.fileformat.info/info/unicode/char/2e13/index.htm */ DOTTED_OBELOS = 0x02e13, /** * @see https://www.fileformat.info/info/unicode/char/2e14/index.htm */ DOWNWARDS_ANCORA = 0x02e14, /** * @see https://www.fileformat.info/info/unicode/char/2e15/index.htm */ UPWARDS_ANCORA = 0x02e15, /** * @see https://www.fileformat.info/info/unicode/char/2e16/index.htm */ DOTTED_RIGHT_POINTING_ANGLE = 0x02e16, /** * @see https://www.fileformat.info/info/unicode/char/2e18/index.htm */ INVERTED_INTERROBANG = 0x02e18, /** * @see https://www.fileformat.info/info/unicode/char/2e19/index.htm */ PALM_BRANCH = 0x02e19, /** * @see https://www.fileformat.info/info/unicode/char/2e1b/index.htm */ TILDE_WITH_RING_ABOVE = 0x02e1b, /** * @see https://www.fileformat.info/info/unicode/char/2e1e/index.htm */ TILDE_WITH_DOT_ABOVE = 0x02e1e, /** * @see https://www.fileformat.info/info/unicode/char/2e1f/index.htm */ TILDE_WITH_DOT_BELOW = 0x02e1f, /** * @see https://www.fileformat.info/info/unicode/char/2e2a/index.htm */ TWO_DOTS_OVER_ONE_DOT_PUNCTUATION = 0x02e2a, /** * @see https://www.fileformat.info/info/unicode/char/2e2b/index.htm */ ONE_DOT_OVER_TWO_DOTS_PUNCTUATION = 0x02e2b, /** * @see https://www.fileformat.info/info/unicode/char/2e2c/index.htm */ SQUARED_FOUR_DOT_PUNCTUATION = 0x02e2c, /** * @see https://www.fileformat.info/info/unicode/char/2e2d/index.htm */ FIVE_DOT_MARK = 0x02e2d, /** * @see https://www.fileformat.info/info/unicode/char/2e2e/index.htm */ REVERSED_QUESTION_MARK = 0x02e2e, /** * @see https://www.fileformat.info/info/unicode/char/2e30/index.htm */ RING_POINT = 0x02e30, /** * @see https://www.fileformat.info/info/unicode/char/2e31/index.htm */ WORD_SEPARATOR_MIDDLE_DOT = 0x02e31, /** * @see https://www.fileformat.info/info/unicode/char/2e32/index.htm */ TURNED_COMMA = 0x02e32, /** * @see https://www.fileformat.info/info/unicode/char/2e33/index.htm */ RAISED_DOT = 0x02e33, /** * @see https://www.fileformat.info/info/unicode/char/2e34/index.htm */ RAISED_COMMA = 0x02e34, /** * @see https://www.fileformat.info/info/unicode/char/2e35/index.htm */ TURNED_SEMICOLON = 0x02e35, /** * @see https://www.fileformat.info/info/unicode/char/2e36/index.htm */ DAGGER_WITH_LEFT_GUARD = 0x02e36, /** * @see https://www.fileformat.info/info/unicode/char/2e37/index.htm */ DAGGER_WITH_RIGHT_GUARD = 0x02e37, /** * @see https://www.fileformat.info/info/unicode/char/2e38/index.htm */ TURNED_DAGGER = 0x02e38, /** * @see https://www.fileformat.info/info/unicode/char/2e39/index.htm */ TOP_HALF_SECTION_SIGN = 0x02e39, /** * @see https://www.fileformat.info/info/unicode/char/2e3c/index.htm */ STENOGRAPHIC_FULL_STOP = 0x02e3c, /** * @see https://www.fileformat.info/info/unicode/char/2e3d/index.htm */ VERTICAL_SIX_DOTS = 0x02e3d, /** * @see https://www.fileformat.info/info/unicode/char/2e3e/index.htm */ WIGGLY_VERTICAL_LINE = 0x02e3e, /** * @see https://www.fileformat.info/info/unicode/char/2e3f/index.htm */ CAPITULUM = 0x02e3f, /** * @see https://www.fileformat.info/info/unicode/char/2e41/index.htm */ REVERSED_COMMA = 0x02e41, /** * @see https://www.fileformat.info/info/unicode/char/2e43/index.htm */ DASH_WITH_LEFT_UPTURN = 0x02e43, /** * @see https://www.fileformat.info/info/unicode/char/2e44/index.htm */ DOUBLE_SUSPENSION_MARK = 0x02e44, /** * @see https://www.fileformat.info/info/unicode/char/2e45/index.htm */ INVERTED_LOW_KAVYKA = 0x02e45, /** * @see https://www.fileformat.info/info/unicode/char/2e46/index.htm */ INVERTED_LOW_KAVYKA_WITH_KAVYKA_ABOVE = 0x02e46, /** * @see https://www.fileformat.info/info/unicode/char/2e47/index.htm */ LOW_KAVYKA = 0x02e47, /** * @see https://www.fileformat.info/info/unicode/char/2e48/index.htm */ LOW_KAVYKA_WITH_DOT = 0x02e48, /** * @see https://www.fileformat.info/info/unicode/char/2e49/index.htm */ DOUBLE_STACKED_COMMA = 0x02e49, /** * @see https://www.fileformat.info/info/unicode/char/2e4a/index.htm */ DOTTED_SOLIDUS = 0x02e4a, /** * @see https://www.fileformat.info/info/unicode/char/2e4b/index.htm */ TRIPLE_DAGGER = 0x02e4b, /** * @see https://www.fileformat.info/info/unicode/char/2e4c/index.htm */ MEDIEVAL_COMMA = 0x02e4c, /** * @see https://www.fileformat.info/info/unicode/char/2e4d/index.htm */ PARAGRAPHUS_MARK = 0x02e4d, /** * @see https://www.fileformat.info/info/unicode/char/2e4e/index.htm */ PUNCTUS_ELEVATUS_MARK = 0x02e4e, /** * @see https://www.fileformat.info/info/unicode/char/2e4f/index.htm */ CORNISH_VERSE_DIVIDER = 0x02e4f, /** * @see https://www.fileformat.info/info/unicode/char/2e52/index.htm */ TIRONIAN_SIGN_CAPITAL_ET = 0x02e52, /** * @see https://www.fileformat.info/info/unicode/char/3001/index.htm */ IDEOGRAPHIC_COMMA = 0x03001, /** * @see https://www.fileformat.info/info/unicode/char/3002/index.htm */ IDEOGRAPHIC_FULL_STOP = 0x03002, /** * @see https://www.fileformat.info/info/unicode/char/3003/index.htm */ DITTO_MARK = 0x03003, /** * @see https://www.fileformat.info/info/unicode/char/303d/index.htm */ PART_ALTERNATION_MARK = 0x0303d, /** * @see https://www.fileformat.info/info/unicode/char/30fb/index.htm */ KATAKANA_MIDDLE_DOT = 0x030fb, /** * @see https://www.fileformat.info/info/unicode/char/a4fe/index.htm */ LISU_PUNCTUATION_COMMA = 0x0a4fe, /** * @see https://www.fileformat.info/info/unicode/char/a4ff/index.htm */ LISU_PUNCTUATION_FULL_STOP = 0x0a4ff, /** * @see https://www.fileformat.info/info/unicode/char/a60d/index.htm */ VAI_COMMA = 0x0a60d, /** * @see https://www.fileformat.info/info/unicode/char/a60e/index.htm */ VAI_FULL_STOP = 0x0a60e, /** * @see https://www.fileformat.info/info/unicode/char/a60f/index.htm */ VAI_QUESTION_MARK = 0x0a60f, /** * @see https://www.fileformat.info/info/unicode/char/a673/index.htm */ SLAVONIC_ASTERISK = 0x0a673, /** * @see https://www.fileformat.info/info/unicode/char/a67e/index.htm */ CYRILLIC_KAVYKA = 0x0a67e, /** * @see https://www.fileformat.info/info/unicode/char/a6f2/index.htm */ BAMUM_NJAEMLI = 0x0a6f2, /** * @see https://www.fileformat.info/info/unicode/char/a6f3/index.htm */ BAMUM_FULL_STOP = 0x0a6f3, /** * @see https://www.fileformat.info/info/unicode/char/a6f4/index.htm */ BAMUM_COLON = 0x0a6f4, /** * @see https://www.fileformat.info/info/unicode/char/a6f5/index.htm */ BAMUM_COMMA = 0x0a6f5, /** * @see https://www.fileformat.info/info/unicode/char/a6f6/index.htm */ BAMUM_SEMICOLON = 0x0a6f6, /** * @see https://www.fileformat.info/info/unicode/char/a6f7/index.htm */ BAMUM_QUESTION_MARK = 0x0a6f7, /** * @see https://www.fileformat.info/info/unicode/char/a874/index.htm */ PHAGS_PA_SINGLE_HEAD_MARK = 0x0a874, /** * @see https://www.fileformat.info/info/unicode/char/a875/index.htm */ PHAGS_PA_DOUBLE_HEAD_MARK = 0x0a875, /** * @see https://www.fileformat.info/info/unicode/char/a876/index.htm */ PHAGS_PA_MARK_SHAD = 0x0a876, /** * @see https://www.fileformat.info/info/unicode/char/a877/index.htm */ PHAGS_PA_MARK_DOUBLE_SHAD = 0x0a877, /** * @see https://www.fileformat.info/info/unicode/char/a8ce/index.htm */ SAURASHTRA_DANDA = 0x0a8ce, /** * @see https://www.fileformat.info/info/unicode/char/a8cf/index.htm */ SAURASHTRA_DOUBLE_DANDA = 0x0a8cf, /** * @see https://www.fileformat.info/info/unicode/char/a8f8/index.htm */ DEVANAGARI_SIGN_PUSHPIKA = 0x0a8f8, /** * @see https://www.fileformat.info/info/unicode/char/a8f9/index.htm */ DEVANAGARI_GAP_FILLER = 0x0a8f9, /** * @see https://www.fileformat.info/info/unicode/char/a8fa/index.htm */ DEVANAGARI_CARET = 0x0a8fa, /** * @see https://www.fileformat.info/info/unicode/char/a8fc/index.htm */ DEVANAGARI_SIGN_SIDDHAM = 0x0a8fc, /** * @see https://www.fileformat.info/info/unicode/char/a92e/index.htm */ KAYAH_LI_SIGN_CWI = 0x0a92e, /** * @see https://www.fileformat.info/info/unicode/char/a92f/index.htm */ KAYAH_LI_SIGN_SHYA = 0x0a92f, /** * @see https://www.fileformat.info/info/unicode/char/a95f/index.htm */ REJANG_SECTION_MARK = 0x0a95f, /** * @see https://www.fileformat.info/info/unicode/char/a9c1/index.htm */ JAVANESE_LEFT_RERENGGAN = 0x0a9c1, /** * @see https://www.fileformat.info/info/unicode/char/a9c2/index.htm */ JAVANESE_RIGHT_RERENGGAN = 0x0a9c2, /** * @see https://www.fileformat.info/info/unicode/char/a9c3/index.htm */ JAVANESE_PADA_ANDAP = 0x0a9c3, /** * @see https://www.fileformat.info/info/unicode/char/a9c4/index.htm */ JAVANESE_PADA_MADYA = 0x0a9c4, /** * @see https://www.fileformat.info/info/unicode/char/a9c5/index.htm */ JAVANESE_PADA_LUHUR = 0x0a9c5, /** * @see https://www.fileformat.info/info/unicode/char/a9c6/index.htm */ JAVANESE_PADA_WINDU = 0x0a9c6, /** * @see https://www.fileformat.info/info/unicode/char/a9c7/index.htm */ JAVANESE_PADA_PANGKAT = 0x0a9c7, /** * @see https://www.fileformat.info/info/unicode/char/a9c8/index.htm */ JAVANESE_PADA_LINGSA = 0x0a9c8, /** * @see https://www.fileformat.info/info/unicode/char/a9c9/index.htm */ JAVANESE_PADA_LUNGSI = 0x0a9c9, /** * @see https://www.fileformat.info/info/unicode/char/a9ca/index.htm */ JAVANESE_PADA_ADEG = 0x0a9ca, /** * @see https://www.fileformat.info/info/unicode/char/a9cb/index.htm */ JAVANESE_PADA_ADEG_ADEG = 0x0a9cb, /** * @see https://www.fileformat.info/info/unicode/char/a9cc/index.htm */ JAVANESE_PADA_PISELEH = 0x0a9cc, /** * @see https://www.fileformat.info/info/unicode/char/a9cd/index.htm */ JAVANESE_TURNED_PADA_PISELEH = 0x0a9cd, /** * @see https://www.fileformat.info/info/unicode/char/a9de/index.htm */ JAVANESE_PADA_TIRTA_TUMETES = 0x0a9de, /** * @see https://www.fileformat.info/info/unicode/char/a9df/index.htm */ JAVANESE_PADA_ISEN_ISEN = 0x0a9df, /** * @see https://www.fileformat.info/info/unicode/char/aa5c/index.htm */ CHAM_PUNCTUATION_SPIRAL = 0x0aa5c, /** * @see https://www.fileformat.info/info/unicode/char/aa5d/index.htm */ CHAM_PUNCTUATION_DANDA = 0x0aa5d, /** * @see https://www.fileformat.info/info/unicode/char/aa5e/index.htm */ CHAM_PUNCTUATION_DOUBLE_DANDA = 0x0aa5e, /** * @see https://www.fileformat.info/info/unicode/char/aa5f/index.htm */ CHAM_PUNCTUATION_TRIPLE_DANDA = 0x0aa5f, /** * @see https://www.fileformat.info/info/unicode/char/aade/index.htm */ TAI_VIET_SYMBOL_HO_HOI = 0x0aade, /** * @see https://www.fileformat.info/info/unicode/char/aadf/index.htm */ TAI_VIET_SYMBOL_KOI_KOI = 0x0aadf, /** * @see https://www.fileformat.info/info/unicode/char/aaf0/index.htm */ MEETEI_MAYEK_CHEIKHAN = 0x0aaf0, /** * @see https://www.fileformat.info/info/unicode/char/aaf1/index.htm */ MEETEI_MAYEK_AHANG_KHUDAM = 0x0aaf1, /** * @see https://www.fileformat.info/info/unicode/char/abeb/index.htm */ MEETEI_MAYEK_CHEIKHEI = 0x0abeb, /** * @see https://www.fileformat.info/info/unicode/char/fe10/index.htm */ PRESENTATION_FORM_FOR_VERTICAL_COMMA = 0x0fe10, /** * @see https://www.fileformat.info/info/unicode/char/fe11/index.htm */ PRESENTATION_FORM_FOR_VERTICAL_IDEOGRAPHIC_COMMA = 0x0fe11, /** * @see https://www.fileformat.info/info/unicode/char/fe12/index.htm */ PRESENTATION_FORM_FOR_VERTICAL_IDEOGRAPHIC_FULL_STOP = 0x0fe12, /** * @see https://www.fileformat.info/info/unicode/char/fe13/index.htm */ PRESENTATION_FORM_FOR_VERTICAL_COLON = 0x0fe13, /** * @see https://www.fileformat.info/info/unicode/char/fe14/index.htm */ PRESENTATION_FORM_FOR_VERTICAL_SEMICOLON = 0x0fe14, /** * @see https://www.fileformat.info/info/unicode/char/fe15/index.htm */ PRESENTATION_FORM_FOR_VERTICAL_EXCLAMATION_MARK = 0x0fe15, /** * @see https://www.fileformat.info/info/unicode/char/fe16/index.htm */ PRESENTATION_FORM_FOR_VERTICAL_QUESTION_MARK = 0x0fe16, /** * @see https://www.fileformat.info/info/unicode/char/fe19/index.htm */ PRESENTATION_FORM_FOR_VERTICAL_HORIZONTAL_ELLIPSIS = 0x0fe19, /** * @see https://www.fileformat.info/info/unicode/char/fe30/index.htm */ PRESENTATION_FORM_FOR_VERTICAL_TWO_DOT_LEADER = 0x0fe30, /** * @see https://www.fileformat.info/info/unicode/char/fe45/index.htm */ SESAME_DOT = 0x0fe45, /** * @see https://www.fileformat.info/info/unicode/char/fe46/index.htm */ WHITE_SESAME_DOT = 0x0fe46, /** * @see https://www.fileformat.info/info/unicode/char/fe49/index.htm */ DASHED_OVERLINE = 0x0fe49, /** * @see https://www.fileformat.info/info/unicode/char/fe4a/index.htm */ CENTRELINE_OVERLINE = 0x0fe4a, /** * @see https://www.fileformat.info/info/unicode/char/fe4b/index.htm */ WAVY_OVERLINE = 0x0fe4b, /** * @see https://www.fileformat.info/info/unicode/char/fe4c/index.htm */ DOUBLE_WAVY_OVERLINE = 0x0fe4c, /** * @see https://www.fileformat.info/info/unicode/char/fe50/index.htm */ SMALL_COMMA = 0x0fe50, /** * @see https://www.fileformat.info/info/unicode/char/fe51/index.htm */ SMALL_IDEOGRAPHIC_COMMA = 0x0fe51, /** * @see https://www.fileformat.info/info/unicode/char/fe52/index.htm */ SMALL_FULL_STOP = 0x0fe52, /** * @see https://www.fileformat.info/info/unicode/char/fe54/index.htm */ SMALL_SEMICOLON = 0x0fe54, /** * @see https://www.fileformat.info/info/unicode/char/fe55/index.htm */ SMALL_COLON = 0x0fe55, /** * @see https://www.fileformat.info/info/unicode/char/fe56/index.htm */ SMALL_QUESTION_MARK = 0x0fe56, /** * @see https://www.fileformat.info/info/unicode/char/fe57/index.htm */ SMALL_EXCLAMATION_MARK = 0x0fe57, /** * @see https://www.fileformat.info/info/unicode/char/fe5f/index.htm */ SMALL_NUMBER_SIGN = 0x0fe5f, /** * @see https://www.fileformat.info/info/unicode/char/fe60/index.htm */ SMALL_AMPERSAND = 0x0fe60, /** * @see https://www.fileformat.info/info/unicode/char/fe61/index.htm */ SMALL_ASTERISK = 0x0fe61, /** * @see https://www.fileformat.info/info/unicode/char/fe68/index.htm */ SMALL_REVERSE_SOLIDUS = 0x0fe68, /** * @see https://www.fileformat.info/info/unicode/char/fe6a/index.htm */ SMALL_PERCENT_SIGN = 0x0fe6a, /** * @see https://www.fileformat.info/info/unicode/char/fe6b/index.htm */ SMALL_COMMERCIAL_AT = 0x0fe6b, /** * @see https://www.fileformat.info/info/unicode/char/ff01/index.htm */ FULLWIDTH_EXCLAMATION_MARK = 0x0ff01, /** * @see https://www.fileformat.info/info/unicode/char/ff02/index.htm */ FULLWIDTH_QUOTATION_MARK = 0x0ff02, /** * @see https://www.fileformat.info/info/unicode/char/ff03/index.htm */ FULLWIDTH_NUMBER_SIGN = 0x0ff03, /** * @see https://www.fileformat.info/info/unicode/char/ff05/index.htm */ FULLWIDTH_PERCENT_SIGN = 0x0ff05, /** * @see https://www.fileformat.info/info/unicode/char/ff06/index.htm */ FULLWIDTH_AMPERSAND = 0x0ff06, /** * @see https://www.fileformat.info/info/unicode/char/ff07/index.htm */ FULLWIDTH_APOSTROPHE = 0x0ff07, /** * @see https://www.fileformat.info/info/unicode/char/ff0a/index.htm */ FULLWIDTH_ASTERISK = 0x0ff0a, /** * @see https://www.fileformat.info/info/unicode/char/ff0c/index.htm */ FULLWIDTH_COMMA = 0x0ff0c, /** * @see https://www.fileformat.info/info/unicode/char/ff0e/index.htm */ FULLWIDTH_FULL_STOP = 0x0ff0e, /** * @see https://www.fileformat.info/info/unicode/char/ff0f/index.htm */ FULLWIDTH_SOLIDUS = 0x0ff0f, /** * @see https://www.fileformat.info/info/unicode/char/ff1a/index.htm */ FULLWIDTH_COLON = 0x0ff1a, /** * @see https://www.fileformat.info/info/unicode/char/ff1b/index.htm */ FULLWIDTH_SEMICOLON = 0x0ff1b, /** * @see https://www.fileformat.info/info/unicode/char/ff1f/index.htm */ FULLWIDTH_QUESTION_MARK = 0x0ff1f, /** * @see https://www.fileformat.info/info/unicode/char/ff20/index.htm */ FULLWIDTH_COMMERCIAL_AT = 0x0ff20, /** * @see https://www.fileformat.info/info/unicode/char/ff3c/index.htm */ FULLWIDTH_REVERSE_SOLIDUS = 0x0ff3c, /** * @see https://www.fileformat.info/info/unicode/char/ff61/index.htm */ HALFWIDTH_IDEOGRAPHIC_FULL_STOP = 0x0ff61, /** * @see https://www.fileformat.info/info/unicode/char/ff64/index.htm */ HALFWIDTH_IDEOGRAPHIC_COMMA = 0x0ff64, /** * @see https://www.fileformat.info/info/unicode/char/ff65/index.htm */ HALFWIDTH_KATAKANA_MIDDLE_DOT = 0x0ff65, /** * @see https://www.fileformat.info/info/unicode/char/10100/index.htm */ AEGEAN_WORD_SEPARATOR_LINE = 0x010100, /** * @see https://www.fileformat.info/info/unicode/char/10101/index.htm */ AEGEAN_WORD_SEPARATOR_DOT = 0x010101, /** * @see https://www.fileformat.info/info/unicode/char/10102/index.htm */ AEGEAN_CHECK_MARK = 0x010102, /** * @see https://www.fileformat.info/info/unicode/char/1039f/index.htm */ UGARITIC_WORD_DIVIDER = 0x01039f, /** * @see https://www.fileformat.info/info/unicode/char/103d0/index.htm */ OLD_PERSIAN_WORD_DIVIDER = 0x0103d0, /** * @see https://www.fileformat.info/info/unicode/char/1056f/index.htm */ CAUCASIAN_ALBANIAN_CITATION_MARK = 0x01056f, /** * @see https://www.fileformat.info/info/unicode/char/10857/index.htm */ IMPERIAL_ARAMAIC_SECTION_SIGN = 0x010857, /** * @see https://www.fileformat.info/info/unicode/char/1091f/index.htm */ PHOENICIAN_WORD_SEPARATOR = 0x01091f, /** * @see https://www.fileformat.info/info/unicode/char/1093f/index.htm */ LYDIAN_TRIANGULAR_MARK = 0x01093f, /** * @see https://www.fileformat.info/info/unicode/char/10a50/index.htm */ KHAROSHTHI_PUNCTUATION_DOT = 0x010a50, /** * @see https://www.fileformat.info/info/unicode/char/10a51/index.htm */ KHAROSHTHI_PUNCTUATION_SMALL_CIRCLE = 0x010a51, /** * @see https://www.fileformat.info/info/unicode/char/10a52/index.htm */ KHAROSHTHI_PUNCTUATION_CIRCLE = 0x010a52, /** * @see https://www.fileformat.info/info/unicode/char/10a53/index.htm */ KHAROSHTHI_PUNCTUATION_CRESCENT_BAR = 0x010a53, /** * @see https://www.fileformat.info/info/unicode/char/10a54/index.htm */ KHAROSHTHI_PUNCTUATION_MANGALAM = 0x010a54, /** * @see https://www.fileformat.info/info/unicode/char/10a55/index.htm */ KHAROSHTHI_PUNCTUATION_LOTUS = 0x010a55, /** * @see https://www.fileformat.info/info/unicode/char/10a56/index.htm */ KHAROSHTHI_PUNCTUATION_DANDA = 0x010a56, /** * @see https://www.fileformat.info/info/unicode/char/10a57/index.htm */ KHAROSHTHI_PUNCTUATION_DOUBLE_DANDA = 0x010a57, /** * @see https://www.fileformat.info/info/unicode/char/10a58/index.htm */ KHAROSHTHI_PUNCTUATION_LINES = 0x010a58, /** * @see https://www.fileformat.info/info/unicode/char/10a7f/index.htm */ OLD_SOUTH_ARABIAN_NUMERIC_INDICATOR = 0x010a7f, /** * @see https://www.fileformat.info/info/unicode/char/10af0/index.htm */ MANICHAEAN_PUNCTUATION_STAR = 0x010af0, /** * @see https://www.fileformat.info/info/unicode/char/10af1/index.htm */ MANICHAEAN_PUNCTUATION_FLEURON = 0x010af1, /** * @see https://www.fileformat.info/info/unicode/char/10af2/index.htm */ MANICHAEAN_PUNCTUATION_DOUBLE_DOT_WITHIN_DOT = 0x010af2, /** * @see https://www.fileformat.info/info/unicode/char/10af3/index.htm */ MANICHAEAN_PUNCTUATION_DOT_WITHIN_DOT = 0x010af3, /** * @see https://www.fileformat.info/info/unicode/char/10af4/index.htm */ MANICHAEAN_PUNCTUATION_DOT = 0x010af4, /** * @see https://www.fileformat.info/info/unicode/char/10af5/index.htm */ MANICHAEAN_PUNCTUATION_TWO_DOTS = 0x010af5, /** * @see https://www.fileformat.info/info/unicode/char/10af6/index.htm */ MANICHAEAN_PUNCTUATION_LINE_FILLER = 0x010af6, /** * @see https://www.fileformat.info/info/unicode/char/10b39/index.htm */ AVESTAN_ABBREVIATION_MARK = 0x010b39, /** * @see https://www.fileformat.info/info/unicode/char/10b3a/index.htm */ TINY_TWO_DOTS_OVER_ONE_DOT_PUNCTUATION = 0x010b3a, /** * @see https://www.fileformat.info/info/unicode/char/10b3b/index.htm */ SMALL_TWO_DOTS_OVER_ONE_DOT_PUNCTUATION = 0x010b3b, /** * @see https://www.fileformat.info/info/unicode/char/10b3c/index.htm */ LARGE_TWO_DOTS_OVER_ONE_DOT_PUNCTUATION = 0x010b3c, /** * @see https://www.fileformat.info/info/unicode/char/10b3d/index.htm */ LARGE_ONE_DOT_OVER_TWO_DOTS_PUNCTUATION = 0x010b3d, /** * @see https://www.fileformat.info/info/unicode/char/10b3e/index.htm */ LARGE_TWO_RINGS_OVER_ONE_RING_PUNCTUATION = 0x010b3e, /** * @see https://www.fileformat.info/info/unicode/char/10b3f/index.htm */ LARGE_ONE_RING_OVER_TWO_RINGS_PUNCTUATION = 0x010b3f, /** * @see https://www.fileformat.info/info/unicode/char/10b99/index.htm */ PSALTER_PAHLAVI_SECTION_MARK = 0x010b99, /** * @see https://www.fileformat.info/info/unicode/char/10b9a/index.htm */ PSALTER_PAHLAVI_TURNED_SECTION_MARK = 0x010b9a, /** * @see https://www.fileformat.info/info/unicode/char/10b9b/index.htm */ PSALTER_PAHLAVI_FOUR_DOTS_WITH_CROSS = 0x010b9b, /** * @see https://www.fileformat.info/info/unicode/char/10b9c/index.htm */ PSALTER_PAHLAVI_FOUR_DOTS_WITH_DOT = 0x010b9c, /** * @see https://www.fileformat.info/info/unicode/char/10f55/index.htm */ SOGDIAN_PUNCTUATION_TWO_VERTICAL_BARS = 0x010f55, /** * @see https://www.fileformat.info/info/unicode/char/10f56/index.htm */ SOGDIAN_PUNCTUATION_TWO_VERTICAL_BARS_WITH_DOTS = 0x010f56, /** * @see https://www.fileformat.info/info/unicode/char/10f57/index.htm */ SOGDIAN_PUNCTUATION_CIRCLE_WITH_DOT = 0x010f57, /** * @see https://www.fileformat.info/info/unicode/char/10f58/index.htm */ SOGDIAN_PUNCTUATION_TWO_CIRCLES_WITH_DOTS = 0x010f58, /** * @see https://www.fileformat.info/info/unicode/char/10f59/index.htm */ SOGDIAN_PUNCTUATION_HALF_CIRCLE_WITH_DOT = 0x010f59, /** * @see https://www.fileformat.info/info/unicode/char/11047/index.htm */ BRAHMI_DANDA = 0x011047, /** * @see https://www.fileformat.info/info/unicode/char/11048/index.htm */ BRAHMI_DOUBLE_DANDA = 0x011048, /** * @see https://www.fileformat.info/info/unicode/char/11049/index.htm */ BRAHMI_PUNCTUATION_DOT = 0x011049, /** * @see https://www.fileformat.info/info/unicode/char/1104a/index.htm */ BRAHMI_PUNCTUATION_DOUBLE_DOT = 0x01104a, /** * @see https://www.fileformat.info/info/unicode/char/1104b/index.htm */ BRAHMI_PUNCTUATION_LINE = 0x01104b, /** * @see https://www.fileformat.info/info/unicode/char/1104c/index.htm */ BRAHMI_PUNCTUATION_CRESCENT_BAR = 0x01104c, /** * @see https://www.fileformat.info/info/unicode/char/1104d/index.htm */ BRAHMI_PUNCTUATION_LOTUS = 0x01104d, /** * @see https://www.fileformat.info/info/unicode/char/110bb/index.htm */ KAITHI_ABBREVIATION_SIGN = 0x0110bb, /** * @see https://www.fileformat.info/info/unicode/char/110bc/index.htm */ KAITHI_ENUMERATION_SIGN = 0x0110bc, /** * @see https://www.fileformat.info/info/unicode/char/110be/index.htm */ KAITHI_SECTION_MARK = 0x0110be, /** * @see https://www.fileformat.info/info/unicode/char/110bf/index.htm */ KAITHI_DOUBLE_SECTION_MARK = 0x0110bf, /** * @see https://www.fileformat.info/info/unicode/char/110c0/index.htm */ KAITHI_DANDA = 0x0110c0, /** * @see https://www.fileformat.info/info/unicode/char/110c1/index.htm */ KAITHI_DOUBLE_DANDA = 0x0110c1, /** * @see https://www.fileformat.info/info/unicode/char/11140/index.htm */ CHAKMA_SECTION_MARK = 0x011140, /** * @see https://www.fileformat.info/info/unicode/char/11141/index.htm */ CHAKMA_DANDA = 0x011141, /** * @see https://www.fileformat.info/info/unicode/char/11142/index.htm */ CHAKMA_DOUBLE_DANDA = 0x011142, /** * @see https://www.fileformat.info/info/unicode/char/11143/index.htm */ CHAKMA_QUESTION_MARK = 0x011143, /** * @see https://www.fileformat.info/info/unicode/char/11174/index.htm */ MAHAJANI_ABBREVIATION_SIGN = 0x011174, /** * @see https://www.fileformat.info/info/unicode/char/11175/index.htm */ MAHAJANI_SECTION_MARK = 0x011175, /** * @see https://www.fileformat.info/info/unicode/char/111c5/index.htm */ SHARADA_DANDA = 0x0111c5, /** * @see https://www.fileformat.info/info/unicode/char/111c6/index.htm */ SHARADA_DOUBLE_DANDA = 0x0111c6, /** * @see https://www.fileformat.info/info/unicode/char/111c7/index.htm */ SHARADA_ABBREVIATION_SIGN = 0x0111c7, /** * @see https://www.fileformat.info/info/unicode/char/111c8/index.htm */ SHARADA_SEPARATOR = 0x0111c8, /** * @see https://www.fileformat.info/info/unicode/char/111cd/index.htm */ SHARADA_SUTRA_MARK = 0x0111cd, /** * @see https://www.fileformat.info/info/unicode/char/111db/index.htm */ SHARADA_SIGN_SIDDHAM = 0x0111db, /** * @see https://www.fileformat.info/info/unicode/char/111dd/index.htm */ SHARADA_CONTINUATION_SIGN = 0x0111dd, /** * @see https://www.fileformat.info/info/unicode/char/111de/index.htm */ SHARADA_SECTION_MARK_1 = 0x0111de, /** * @see https://www.fileformat.info/info/unicode/char/111df/index.htm */ SHARADA_SECTION_MARK_2 = 0x0111df, /** * @see https://www.fileformat.info/info/unicode/char/11238/index.htm */ KHOJKI_DANDA = 0x011238, /** * @see https://www.fileformat.info/info/unicode/char/11239/index.htm */ KHOJKI_DOUBLE_DANDA = 0x011239, /** * @see https://www.fileformat.info/info/unicode/char/1123a/index.htm */ KHOJKI_WORD_SEPARATOR = 0x01123a, /** * @see https://www.fileformat.info/info/unicode/char/1123b/index.htm */ KHOJKI_SECTION_MARK = 0x01123b, /** * @see https://www.fileformat.info/info/unicode/char/1123c/index.htm */ KHOJKI_DOUBLE_SECTION_MARK = 0x01123c, /** * @see https://www.fileformat.info/info/unicode/char/1123d/index.htm */ KHOJKI_ABBREVIATION_SIGN = 0x01123d, /** * @see https://www.fileformat.info/info/unicode/char/112a9/index.htm */ MULTANI_SECTION_MARK = 0x0112a9, /** * @see https://www.fileformat.info/info/unicode/char/1144b/index.htm */ NEWA_DANDA = 0x01144b, /** * @see https://www.fileformat.info/info/unicode/char/1144c/index.htm */ NEWA_DOUBLE_DANDA = 0x01144c, /** * @see https://www.fileformat.info/info/unicode/char/1144d/index.htm */ NEWA_COMMA = 0x01144d, /** * @see https://www.fileformat.info/info/unicode/char/1144e/index.htm */ NEWA_GAP_FILLER = 0x01144e, /** * @see https://www.fileformat.info/info/unicode/char/1144f/index.htm */ NEWA_ABBREVIATION_SIGN = 0x01144f, /** * @see https://www.fileformat.info/info/unicode/char/1145a/index.htm */ NEWA_DOUBLE_COMMA = 0x01145a, /** * @see https://www.fileformat.info/info/unicode/char/1145b/index.htm */ NEWA_PLACEHOLDER_MARK = 0x01145b, /** * @see https://www.fileformat.info/info/unicode/char/1145d/index.htm */ NEWA_INSERTION_SIGN = 0x01145d, /** * @see https://www.fileformat.info/info/unicode/char/114c6/index.htm */ TIRHUTA_ABBREVIATION_SIGN = 0x0114c6, /** * @see https://www.fileformat.info/info/unicode/char/115c1/index.htm */ SIDDHAM_SIGN_SIDDHAM = 0x0115c1, /** * @see https://www.fileformat.info/info/unicode/char/115c2/index.htm */ SIDDHAM_DANDA = 0x0115c2, /** * @see https://www.fileformat.info/info/unicode/char/115c3/index.htm */ SIDDHAM_DOUBLE_DANDA = 0x0115c3, /** * @see https://www.fileformat.info/info/unicode/char/115c4/index.htm */ SIDDHAM_SEPARATOR_DOT = 0x0115c4, /** * @see https://www.fileformat.info/info/unicode/char/115c5/index.htm */ SIDDHAM_SEPARATOR_BAR = 0x0115c5, /** * @see https://www.fileformat.info/info/unicode/char/115c6/index.htm */ SIDDHAM_REPETITION_MARK_1 = 0x0115c6, /** * @see https://www.fileformat.info/info/unicode/char/115c7/index.htm */ SIDDHAM_REPETITION_MARK_2 = 0x0115c7, /** * @see https://www.fileformat.info/info/unicode/char/115c8/index.htm */ SIDDHAM_REPETITION_MARK_3 = 0x0115c8, /** * @see https://www.fileformat.info/info/unicode/char/115c9/index.htm */ SIDDHAM_END_OF_TEXT_MARK = 0x0115c9, /** * @see https://www.fileformat.info/info/unicode/char/115ca/index.htm */ SIDDHAM_SECTION_MARK_WITH_TRIDENT_AND_U_SHAPED_ORNAMENTS = 0x0115ca, /** * @see https://www.fileformat.info/info/unicode/char/115cb/index.htm */ SIDDHAM_SECTION_MARK_WITH_TRIDENT_AND_DOTTED_CRESCENTS = 0x0115cb, /** * @see https://www.fileformat.info/info/unicode/char/115cc/index.htm */ SIDDHAM_SECTION_MARK_WITH_RAYS_AND_DOTTED_CRESCENTS = 0x0115cc, /** * @see https://www.fileformat.info/info/unicode/char/115cd/index.htm */ SIDDHAM_SECTION_MARK_WITH_RAYS_AND_DOTTED_DOUBLE_CRESCENTS = 0x0115cd, /** * @see https://www.fileformat.info/info/unicode/char/115ce/index.htm */ SIDDHAM_SECTION_MARK_WITH_RAYS_AND_DOTTED_TRIPLE_CRESCENTS = 0x0115ce, /** * @see https://www.fileformat.info/info/unicode/char/115cf/index.htm */ SIDDHAM_SECTION_MARK_DOUBLE_RING = 0x0115cf, /** * @see https://www.fileformat.info/info/unicode/char/115d0/index.htm */ SIDDHAM_SECTION_MARK_DOUBLE_RING_WITH_RAYS = 0x0115d0, /** * @see https://www.fileformat.info/info/unicode/char/115d1/index.htm */ SIDDHAM_SECTION_MARK_WITH_DOUBLE_CRESCENTS = 0x0115d1, /** * @see https://www.fileformat.info/info/unicode/char/115d2/index.htm */ SIDDHAM_SECTION_MARK_WITH_TRIPLE_CRESCENTS = 0x0115d2, /** * @see https://www.fileformat.info/info/unicode/char/115d3/index.htm */ SIDDHAM_SECTION_MARK_WITH_QUADRUPLE_CRESCENTS = 0x0115d3, /** * @see https://www.fileformat.info/info/unicode/char/115d4/index.htm */ SIDDHAM_SECTION_MARK_WITH_SEPTUPLE_CRESCENTS = 0x0115d4, /** * @see https://www.fileformat.info/info/unicode/char/115d5/index.htm */ SIDDHAM_SECTION_MARK_WITH_CIRCLES_AND_RAYS = 0x0115d5, /** * @see https://www.fileformat.info/info/unicode/char/115d6/index.htm */ SIDDHAM_SECTION_MARK_WITH_CIRCLES_AND_TWO_ENCLOSURES = 0x0115d6, /** * @see https://www.fileformat.info/info/unicode/char/115d7/index.htm */ SIDDHAM_SECTION_MARK_WITH_CIRCLES_AND_FOUR_ENCLOSURES = 0x0115d7, /** * @see https://www.fileformat.info/info/unicode/char/11641/index.htm */ MODI_DANDA = 0x011641, /** * @see https://www.fileformat.info/info/unicode/char/11642/index.htm */ MODI_DOUBLE_DANDA = 0x011642, /** * @see https://www.fileformat.info/info/unicode/char/11643/index.htm */ MODI_ABBREVIATION_SIGN = 0x011643, /** * @see https://www.fileformat.info/info/unicode/char/11660/index.htm */ MONGOLIAN_BIRGA_WITH_ORNAMENT = 0x011660, /** * @see https://www.fileformat.info/info/unicode/char/11661/index.htm */ MONGOLIAN_ROTATED_BIRGA = 0x011661, /** * @see https://www.fileformat.info/info/unicode/char/11662/index.htm */ MONGOLIAN_DOUBLE_BIRGA_WITH_ORNAMENT = 0x011662, /** * @see https://www.fileformat.info/info/unicode/char/11663/index.htm */ MONGOLIAN_TRIPLE_BIRGA_WITH_ORNAMENT = 0x011663, /** * @see https://www.fileformat.info/info/unicode/char/11664/index.htm */ MONGOLIAN_BIRGA_WITH_DOUBLE_ORNAMENT = 0x011664, /** * @see https://www.fileformat.info/info/unicode/char/11665/index.htm */ MONGOLIAN_ROTATED_BIRGA_WITH_ORNAMENT = 0x011665, /** * @see https://www.fileformat.info/info/unicode/char/11666/index.htm */ MONGOLIAN_ROTATED_BIRGA_WITH_DOUBLE_ORNAMENT = 0x011666, /** * @see https://www.fileformat.info/info/unicode/char/11667/index.htm */ MONGOLIAN_INVERTED_BIRGA = 0x011667, /** * @see https://www.fileformat.info/info/unicode/char/11668/index.htm */ MONGOLIAN_INVERTED_BIRGA_WITH_DOUBLE_ORNAMENT = 0x011668, /** * @see https://www.fileformat.info/info/unicode/char/11669/index.htm */ MONGOLIAN_SWIRL_BIRGA = 0x011669, /** * @see https://www.fileformat.info/info/unicode/char/1166a/index.htm */ MONGOLIAN_SWIRL_BIRGA_WITH_ORNAMENT = 0x01166a, /** * @see https://www.fileformat.info/info/unicode/char/1166b/index.htm */ MONGOLIAN_SWIRL_BIRGA_WITH_DOUBLE_ORNAMENT = 0x01166b, /** * @see https://www.fileformat.info/info/unicode/char/1166c/index.htm */ MONGOLIAN_TURNED_SWIRL_BIRGA_WITH_DOUBLE_ORNAMENT = 0x01166c, /** * @see https://www.fileformat.info/info/unicode/char/1173c/index.htm */ AHOM_SIGN_SMALL_SECTION = 0x01173c, /** * @see https://www.fileformat.info/info/unicode/char/1173d/index.htm */ AHOM_SIGN_SECTION = 0x01173d, /** * @see https://www.fileformat.info/info/unicode/char/1173e/index.htm */ AHOM_SIGN_RULAI = 0x01173e, /** * @see https://www.fileformat.info/info/unicode/char/1183b/index.htm */ DOGRA_ABBREVIATION_SIGN = 0x01183b, /** * @see https://www.fileformat.info/info/unicode/char/11944/index.htm */ DIVES_AKURU_DOUBLE_DANDA = 0x011944, /** * @see https://www.fileformat.info/info/unicode/char/11945/index.htm */ DIVES_AKURU_GAP_FILLER = 0x011945, /** * @see https://www.fileformat.info/info/unicode/char/11946/index.htm */ DIVES_AKURU_END_OF_TEXT_MARK = 0x011946, /** * @see https://www.fileformat.info/info/unicode/char/119e2/index.htm */ NANDINAGARI_SIGN_SIDDHAM = 0x0119e2, /** * @see https://www.fileformat.info/info/unicode/char/11a3f/index.htm */ ZANABAZAR_SQUARE_INITIAL_HEAD_MARK = 0x011a3f, /** * @see https://www.fileformat.info/info/unicode/char/11a40/index.htm */ ZANABAZAR_SQUARE_CLOSING_HEAD_MARK = 0x011a40, /** * @see https://www.fileformat.info/info/unicode/char/11a41/index.htm */ ZANABAZAR_SQUARE_MARK_TSHEG = 0x011a41, /** * @see https://www.fileformat.info/info/unicode/char/11a42/index.htm */ ZANABAZAR_SQUARE_MARK_SHAD = 0x011a42, /** * @see https://www.fileformat.info/info/unicode/char/11a43/index.htm */ ZANABAZAR_SQUARE_MARK_DOUBLE_SHAD = 0x011a43, /** * @see https://www.fileformat.info/info/unicode/char/11a44/index.htm */ ZANABAZAR_SQUARE_MARK_LONG_TSHEG = 0x011a44, /** * @see https://www.fileformat.info/info/unicode/char/11a45/index.htm */ ZANABAZAR_SQUARE_INITIAL_DOUBLE_LINED_HEAD_MARK = 0x011a45, /** * @see https://www.fileformat.info/info/unicode/char/11a46/index.htm */ ZANABAZAR_SQUARE_CLOSING_DOUBLE_LINED_HEAD_MARK = 0x011a46, /** * @see https://www.fileformat.info/info/unicode/char/11a9a/index.htm */ SOYOMBO_MARK_TSHEG = 0x011a9a, /** * @see https://www.fileformat.info/info/unicode/char/11a9b/index.htm */ SOYOMBO_MARK_SHAD = 0x011a9b, /** * @see https://www.fileformat.info/info/unicode/char/11a9c/index.htm */ SOYOMBO_MARK_DOUBLE_SHAD = 0x011a9c, /** * @see https://www.fileformat.info/info/unicode/char/11a9e/index.htm */ SOYOMBO_HEAD_MARK_WITH_MOON_AND_SUN_AND_TRIPLE_FLAME = 0x011a9e, /** * @see https://www.fileformat.info/info/unicode/char/11a9f/index.htm */ SOYOMBO_HEAD_MARK_WITH_MOON_AND_SUN_AND_FLAME = 0x011a9f, /** * @see https://www.fileformat.info/info/unicode/char/11aa0/index.htm */ SOYOMBO_HEAD_MARK_WITH_MOON_AND_SUN = 0x011aa0, /** * @see https://www.fileformat.info/info/unicode/char/11aa1/index.htm */ SOYOMBO_TERMINAL_MARK_1 = 0x011aa1, /** * @see https://www.fileformat.info/info/unicode/char/11aa2/index.htm */ SOYOMBO_TERMINAL_MARK_2 = 0x011aa2, /** * @see https://www.fileformat.info/info/unicode/char/11c41/index.htm */ BHAIKSUKI_DANDA = 0x011c41, /** * @see https://www.fileformat.info/info/unicode/char/11c42/index.htm */ BHAIKSUKI_DOUBLE_DANDA = 0x011c42, /** * @see https://www.fileformat.info/info/unicode/char/11c43/index.htm */ BHAIKSUKI_WORD_SEPARATOR = 0x011c43, /** * @see https://www.fileformat.info/info/unicode/char/11c44/index.htm */ BHAIKSUKI_GAP_FILLER_1 = 0x011c44, /** * @see https://www.fileformat.info/info/unicode/char/11c45/index.htm */ BHAIKSUKI_GAP_FILLER_2 = 0x011c45, /** * @see https://www.fileformat.info/info/unicode/char/11c70/index.htm */ MARCHEN_HEAD_MARK = 0x011c70, /** * @see https://www.fileformat.info/info/unicode/char/11c71/index.htm */ MARCHEN_MARK_SHAD = 0x011c71, /** * @see https://www.fileformat.info/info/unicode/char/11ef7/index.htm */ MAKASAR_PASSIMBANG = 0x011ef7, /** * @see https://www.fileformat.info/info/unicode/char/11ef8/index.htm */ MAKASAR_END_OF_SECTION = 0x011ef8, /** * @see https://www.fileformat.info/info/unicode/char/11fff/index.htm */ TAMIL_PUNCTUATION_END_OF_TEXT = 0x011fff, /** * @see https://www.fileformat.info/info/unicode/char/12470/index.htm */ CUNEIFORM_PUNCTUATION_SIGN_OLD_ASSYRIAN_WORD_DIVIDER = 0x012470, /** * @see https://www.fileformat.info/info/unicode/char/12471/index.htm */ CUNEIFORM_PUNCTUATION_SIGN_VERTICAL_COLON = 0x012471, /** * @see https://www.fileformat.info/info/unicode/char/12472/index.htm */ CUNEIFORM_PUNCTUATION_SIGN_DIAGONAL_COLON = 0x012472, /** * @see https://www.fileformat.info/info/unicode/char/12473/index.htm */ CUNEIFORM_PUNCTUATION_SIGN_DIAGONAL_TRICOLON = 0x012473, /** * @see https://www.fileformat.info/info/unicode/char/12474/index.htm */ CUNEIFORM_PUNCTUATION_SIGN_DIAGONAL_QUADCOLON = 0x012474, /** * @see https://www.fileformat.info/info/unicode/char/16a6e/index.htm */ MRO_DANDA = 0x016a6e, /** * @see https://www.fileformat.info/info/unicode/char/16a6f/index.htm */ MRO_DOUBLE_DANDA = 0x016a6f, /** * @see https://www.fileformat.info/info/unicode/char/16af5/index.htm */ BASSA_VAH_FULL_STOP = 0x016af5, /** * @see https://www.fileformat.info/info/unicode/char/16b37/index.htm */ PAHAWH_HMONG_SIGN_VOS_THOM = 0x016b37, /** * @see https://www.fileformat.info/info/unicode/char/16b38/index.htm */ PAHAWH_HMONG_SIGN_VOS_TSHAB_CEEB = 0x016b38, /** * @see https://www.fileformat.info/info/unicode/char/16b39/index.htm */ PAHAWH_HMONG_SIGN_CIM_CHEEM = 0x016b39, /** * @see https://www.fileformat.info/info/unicode/char/16b3a/index.htm */ PAHAWH_HMONG_SIGN_VOS_THIAB = 0x016b3a, /** * @see https://www.fileformat.info/info/unicode/char/16b3b/index.htm */ PAHAWH_HMONG_SIGN_VOS_FEEM = 0x016b3b, /** * @see https://www.fileformat.info/info/unicode/char/16b44/index.htm */ PAHAWH_HMONG_SIGN_XAUS = 0x016b44, /** * @see https://www.fileformat.info/info/unicode/char/16e97/index.htm */ MEDEFAIDRIN_COMMA = 0x016e97, /** * @see https://www.fileformat.info/info/unicode/char/16e98/index.htm */ MEDEFAIDRIN_FULL_STOP = 0x016e98, /** * @see https://www.fileformat.info/info/unicode/char/16e99/index.htm */ MEDEFAIDRIN_SYMBOL_AIVA = 0x016e99, /** * @see https://www.fileformat.info/info/unicode/char/16e9a/index.htm */ MEDEFAIDRIN_EXCLAMATION_OH = 0x016e9a, /** * @see https://www.fileformat.info/info/unicode/char/16fe2/index.htm */ OLD_CHINESE_HOOK_MARK = 0x016fe2, /** * @see https://www.fileformat.info/info/unicode/char/1bc9f/index.htm */ DUPLOYAN_PUNCTUATION_CHINOOK_FULL_STOP = 0x01bc9f, /** * @see https://www.fileformat.info/info/unicode/char/1da87/index.htm */ SIGNWRITING_COMMA = 0x01da87, /** * @see https://www.fileformat.info/info/unicode/char/1da88/index.htm */ SIGNWRITING_FULL_STOP = 0x01da88, /** * @see https://www.fileformat.info/info/unicode/char/1da89/index.htm */ SIGNWRITING_SEMICOLON = 0x01da89, /** * @see https://www.fileformat.info/info/unicode/char/1da8a/index.htm */ SIGNWRITING_COLON = 0x01da8a, /** * @see https://www.fileformat.info/info/unicode/char/1da8b/index.htm */ SIGNWRITING_PARENTHESIS = 0x01da8b, /** * @see https://www.fileformat.info/info/unicode/char/1e95e/index.htm */ ADLAM_INITIAL_EXCLAMATION_MARK = 0x01e95e, /** * @see https://www.fileformat.info/info/unicode/char/1e95f/index.htm */ ADLAM_INITIAL_QUESTION_MARK = 0x01e95f, }
the_stack
import fs = require('fs'); import path = require('path'); import underscore = require('underscore'); import urlLib = require('url'); import asyncutil = require('../base/asyncutil'); import collection_util = require('../base/collectionutil'); import http_client = require('../http_client'); import ico = require('./ico'); import image = require('./image'); import http_vfs = require('../vfs/http'); import node_vfs = require('../vfs/node'); import site_info = require('./site_info'); import site_info_service = require('./service'); import stringutil = require('../base/stringutil'); import testLib = require('../test'); import { defer } from '../base/promise_util'; var urlFetcher: site_info_service.UrlFetcher = { fetch(url: string): Promise<site_info_service.UrlResponse> { // the icon fetchers will fetch URLs with paths such as '/favicon.ico' // http_vfs.Server serves files under '/files/<path>', so we modify the // URL here before dispatching the request let parsedUrl = urlLib.parse(url); parsedUrl.pathname = '/files/' + parsedUrl.pathname; return http_client .request('GET', urlLib.format(parsedUrl)) .then(reply => { return { status: reply.status, body: reply.body, }; }); }, }; var TEST_SITE_PATH = path.join( stringutil.replaceLast(path.dirname(module.filename), 'build/', ''), '../test-data/site-icons' ); testLib.addTest('extract page links', assert => { var extractor = new site_info_service.PageLinkFetcher(urlFetcher); var testCases = [ { content: '<html><head>' + '<meta property="og:image" content="testicon.png">' + '<link rel="shortcut icon" href="http://www.foobar.com/icon.png">' + '</head></html>', links: [ { type: site_info_service.MetaTagType.Meta, rel: 'og:image', url: 'testicon.png', }, { type: site_info_service.MetaTagType.Link, rel: 'shortcut icon', url: 'http://www.foobar.com/icon.png', }, ], }, { content: '<LINK REL="shortcut ICON" HREF=favicon.png>', links: [ { type: site_info_service.MetaTagType.Link, rel: 'shortcut icon', url: 'favicon.png', }, ], }, { content: '<link\nrel="shortcut icon" href="ico.png">', links: [ { type: site_info_service.MetaTagType.Link, rel: 'shortcut icon', url: 'ico.png', }, ], }, ]; testCases.forEach(testCase => { var links = extractor.extractLinks(testCase.content); assert.deepEqual(links, testCase.links); }); }); function extractIconLinks( contentFilePath: string ): site_info_service.PageLink[] { var extractor = new site_info_service.PageLinkFetcher(urlFetcher); var content = fs .readFileSync(path.join(TEST_SITE_PATH, contentFilePath)) .toString(); return underscore.filter(extractor.extractLinks(content), link => { return site_info_service.isIconLink(link); }); } testLib.addTest('extract icon links', assert => { var links = extractIconLinks('evernote.html'); assert.deepEqual(links, [ { type: site_info_service.MetaTagType.Meta, rel: 'og:image', url: 'http://evernote.com/media/img/evernote_icon.png', }, { type: site_info_service.MetaTagType.Link, rel: 'shortcut icon', url: '/media/img/favicon.ico', }, { type: site_info_service.MetaTagType.Meta, rel: 'msapplication-tileimage', url: '/media/img/favicon_144.png', }, ]); }); testLib.addTest('read PNG icon', assert => { var iconPath = path.join( TEST_SITE_PATH, 'wikipedia/standard-icons/apple-touch-icon.png' ); var data = new Uint8Array(<any>fs.readFileSync(iconPath)); var size = site_info_service.iconFromData('apple-touch-icon.png', data); assert.equal(size.width, 144); assert.equal(size.height, 144); }); testLib.addTest('read BMP icon', assert => { var iconPath = path.join( TEST_SITE_PATH, 'wikipedia/linked-icons/favicon-16x16.bmp' ); var data = new Uint8Array(<any>fs.readFileSync(iconPath)); var size = site_info_service.iconFromData('favicon-16x16.bmp', data); assert.equal(size.width, 16); assert.equal(size.height, 16); }); testLib.addTest('read JPEG icon', assert => { var icons = [ { path: 'wikipedia/wikipedia.jpg', width: 144, height: 144, }, { path: 'wikipedia/wikipedia-progressive.jpg', width: 183, height: 200, }, ]; icons.forEach(icon => { var iconPath = path.join(TEST_SITE_PATH, icon.path); var data = new Uint8Array(<any>fs.readFileSync(iconPath)); var size = site_info_service.iconFromData(icon.path, data); assert.equal(size.width, icon.width); assert.equal(size.height, icon.height); }); }); testLib.addTest('read ICO icon', assert => { var iconPath = path.join( TEST_SITE_PATH, 'wikipedia/standard-icons/favicon.ico' ); var data = new Uint8Array(<any>fs.readFileSync(iconPath)); var icons = ico.read(new DataView(data.buffer)); assert.equal(icons.length, 3); var expectedIcons = [ { width: 16, height: 16, data: 'wikipedia/linked-icons/favicon-16x16.bmp', }, { width: 32, height: 32, data: 'wikipedia/linked-icons/favicon-32x32.bmp', }, { width: 48, height: 48, data: 'wikipedia/linked-icons/favicon-48x48.bmp', }, ]; icons.forEach((icon, index) => { var expectedIcon = expectedIcons[index]; var expectedData = fs.readFileSync( path.join(TEST_SITE_PATH, expectedIcon.data) ); assert.equal(icon.width, expectedIcon.width); assert.equal(icon.height, expectedIcon.height); assert.deepEqual( collection_util.bufferToArray(icon.data), collection_util.bufferToArray(expectedData) ); }); }); testLib.addTest('read ICO icons', assert => { // FIXME - Remaining non-working icons: ['eventbrite.ico'] var icons = [ 'icloud.ico', 'desk.ico', 'gocompare.ico', 'prodpad.ico', 'codeplex.ico', ]; icons.forEach(name => { var iconPath = path.join(TEST_SITE_PATH + '/ico', name); var data = new Uint8Array(<any>fs.readFileSync(iconPath)); try { var icons = ico.read(new DataView(data.buffer)); assert.ok(icons.length > 0); } catch (ex) { console.log('error reading icon', name, ':', ex.message); } }); }); testLib.addTest('image decode error', assert => { var PNG_SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; var invalidIconData = PNG_SIG.concat([0, 1, 2, 3, 4, 5]); try { site_info_service.iconFromData( 'foo.png', new Uint8Array(invalidIconData) ); assert.ok(false); } catch (ex) { assert.ok(ex instanceof image.DecodeError); } }); testLib.addTest('extract largest ICO icon', assert => { var iconPath = path.join( TEST_SITE_PATH, 'wikipedia/standard-icons/favicon.ico' ); var data = new Uint8Array(<any>fs.readFileSync(iconPath)); var icon = site_info_service.iconFromData('favicon.ico', data); assert.equal(icon.width, 48); assert.equal(icon.height, 48); assert.ok(icon.data != null); var expectedData = fs.readFileSync( path.join(TEST_SITE_PATH, 'wikipedia/linked-icons/favicon-48x48.bmp') ); assert.deepEqual( collection_util.bufferToArray(icon.data), collection_util.bufferToArray(expectedData) ); }); interface ServeFetchResult { server: http_vfs.Server; queryResult: site_info.QueryResult; provider: site_info.SiteInfoProvider; } function serveAndFetchIcons( port: number, siteRoot: string, queryPath: string ): Promise<ServeFetchResult> { var server = new http_vfs.Server(new node_vfs.FileVFS(siteRoot)); var provider = new site_info_service.SiteInfoService(urlFetcher); var result: site_info.QueryResult; var queryUrl = 'http://localhost:' + port + queryPath; return server .listen(port) .then(() => { return asyncutil.until(() => { var next = defer<boolean>(); result = provider.lookup(queryUrl); if (result.state == site_info.QueryState.Ready) { return Promise.resolve(true); } else { setTimeout(() => { next.resolve(false); }, 100); return next.promise; } }); }) .then(() => { return { queryResult: result, server: server, provider: provider, }; }); } var maxPort = 8561; function allocatePort(): number { var port = maxPort; ++maxPort; return port; } testLib.addTest('fail to fetch icons', assert => { var sitePath = path.join(TEST_SITE_PATH, 'wikipedia/no-icons'); return serveAndFetchIcons(allocatePort(), sitePath, '').then(result => { assert.equal(result.queryResult.state, site_info.QueryState.Ready); assert.equal(result.queryResult.info.icons.length, 0); result.server.close(); }); }); testLib.addTest('fetch static links', assert => { var sitePath = path.join(TEST_SITE_PATH, 'wikipedia/standard-icons'); return serveAndFetchIcons(allocatePort(), sitePath, '/').then(result => { assert.equal(result.queryResult.state, site_info.QueryState.Ready); assert.equal(result.queryResult.info.icons.length, 2); result.server.close(); }); }); testLib.addTest('fetch page links', assert => { var sitePath = path.join(TEST_SITE_PATH, 'wikipedia/linked-icons'); return serveAndFetchIcons(allocatePort(), sitePath, '/index.html').then( result => { assert.equal(result.queryResult.state, site_info.QueryState.Ready); assert.equal(result.queryResult.info.icons.length, 3); result.server.close(); } ); }); testLib.addTest('forget site info', assert => { var sitePath = path.join(TEST_SITE_PATH, 'wikipedia/linked-icons'); return serveAndFetchIcons(allocatePort(), sitePath, '/index.html').then( result => { var queryUrl = result.queryResult.info.url; assert.equal(result.queryResult.state, site_info.QueryState.Ready); // ask the provider to forget cached data and repeat the lookup result.provider.forget(queryUrl); var uncachedLookup = result.provider.lookup(queryUrl); assert.equal(uncachedLookup.state, site_info.QueryState.Updating); result.server.close(); } ); }); testLib.addTest('fetch site icon with DuckDuckGo', assert => { var urlFetcher: site_info_service.UrlFetcher = { fetch: (url: string) => { return Promise.resolve({ status: 200, body: JSON.stringify({ Image: 'https://duckduckgo.com/i/img.png', ImageIsLogo: 1, }), }); }, }; var ddgClient = new site_info_service.DuckDuckGoClient(urlFetcher); return ddgClient.fetchIconUrl('http://www.admiral.com').then(icon => { assert.equal(icon, 'https://duckduckgo.com/i/img.png'); }); });
the_stack
import { AnyVariableDefinition, DashboardResource } from '@perses-ui/core'; const nodeExporterDashboard: DashboardResource = { kind: 'Dashboard', metadata: { name: 'Node Stats', project: 'perses', created_at: '2021-11-09', updated_at: '2021-11-09', }, spec: { datasource: { kind: 'Prometheus', name: 'PrometheusDemo', global: true }, // TODO: Should duration actually be a time range? duration: '24h', variables: { job: { kind: 'PrometheusLabelValues', options: { label_name: 'job', match: ['node_uname_info'], }, display: { label: 'Job', }, selection: { default_value: 'node', }, } as AnyVariableDefinition, instance: { kind: 'PrometheusLabelValues', options: { label_name: 'instance', match: ['node_uname_info{job="node"}'], }, display: { label: 'Node', }, selection: { default_value: ['demo.do.prometheus.io:9100'], all_value: '$__all', }, } as AnyVariableDefinition, interval: { kind: 'Interval', options: { values: ['1m', '5m', '10m', '1h'], auto: { step_count: 50, min_interval: '1m', }, }, display: { label: 'Interval', }, selection: { default_value: '1m', }, } as AnyVariableDefinition, }, panels: { gaugeCpuBusy: { kind: 'GaugeChart', display: { name: 'CPU Busy' }, options: { query: { kind: 'PrometheusGraphQuery', options: { query: '(((count(count(node_cpu_seconds_total{job="node",instance="$instance"}) by (cpu))) - avg(sum by (mode)(rate(node_cpu_seconds_total{mode="idle",job="node",instance="$instance"}[$interval])))) * 100) / count(count(node_cpu_seconds_total{job="node",instance="$instance"}) by (cpu))', }, }, calculation: 'LastNumber', unit: { kind: 'Percent' }, thresholds: { // default_color: '#000', // optional steps: [ { value: 85, // color: '#800080', // optional, overrides defaultWarningColor }, { value: 95, // color: '#0000FF', // optional, overrides defaultAlertColor }, ], }, }, }, gaugeSystemLoad: { kind: 'GaugeChart', display: { name: 'Sys Load (5m avg)' }, options: { query: { kind: 'PrometheusGraphQuery', options: { query: 'avg(node_load5{job="node",instance="$instance"}) / count(count(node_cpu_seconds_total{job="node",instance="$instance"}) by (cpu)) * 100', }, }, calculation: 'LastNumber', unit: { kind: 'Percent' }, thresholds: { steps: [ { value: 85, }, { value: 95, }, ], }, }, }, gaugeSystemLoadAlt: { kind: 'GaugeChart', display: { name: 'Sys Load (15m avg)' }, options: { query: { kind: 'PrometheusGraphQuery', options: { query: 'avg(node_load15{job="node",instance="$instance"}) / count(count(node_cpu_seconds_total{job="node",instance="$instance"}) by (cpu)) * 100', }, }, calculation: 'LastNumber', unit: { kind: 'Percent' }, thresholds: { steps: [ { value: 85, }, { value: 95, }, ], }, }, }, gaugeRam: { kind: 'GaugeChart', display: { name: 'RAM Used' }, options: { query: { kind: 'PrometheusGraphQuery', options: { query: '100 - ((node_memory_MemAvailable_bytes{job="node",instance="$instance"} * 100) / node_memory_MemTotal_bytes{job="node",instance="$instance"})', }, }, calculation: 'LastNumber', unit: { kind: 'Percent' }, thresholds: { steps: [ { value: 80, }, { value: 90, }, ], }, }, }, gaugeSwap: { kind: 'GaugeChart', display: { name: 'SWAP Used' }, options: { query: { kind: 'PrometheusGraphQuery', options: { query: '((node_memory_SwapTotal_bytes{job="node",instance="$instance"} - node_memory_SwapFree_bytes{job="node",instance="$instance"}) / (node_memory_SwapTotal_bytes{job="node",instance="$instance"} )) * 100', }, }, calculation: 'LastNumber', unit: { kind: 'Percent' }, thresholds: { steps: [ { value: 10, }, { value: 25, }, ], }, }, }, gaugeRoot: { kind: 'GaugeChart', display: { name: 'Root FS Used' }, options: { query: { kind: 'PrometheusGraphQuery', options: { query: '100 - ((node_filesystem_avail_bytes{job="node",instance="$instance",mountpoint="/",fstype!="rootfs"} * 100) / node_filesystem_size_bytes{job="node",instance="$instance",mountpoint="/",fstype!="rootfs"})', }, }, calculation: 'LastNumber', unit: { kind: 'Percent' }, thresholds: { steps: [ { value: 80, }, { value: 90, }, ], }, }, }, emptyExample: { kind: 'EmptyChart', display: { name: 'Empty Example 1' }, options: {}, }, emptyExample2: { kind: 'EmptyChart', display: { name: 'Empty Example 2' }, options: {}, }, emptyExample3: { kind: 'EmptyChart', display: { name: 'Empty Example 3' }, options: {}, }, cpu: { kind: 'LineChart', display: { name: 'CPU' }, options: { queries: [ { kind: 'PrometheusGraphQuery', options: { query: 'avg without (cpu)(rate(node_cpu_seconds_total{job="node",instance="$instance",mode!="idle"}[$interval]))', }, }, ], unit: { kind: '%' }, }, }, memory: { kind: 'LineChart', display: { name: 'Memory' }, options: { queries: [ { kind: 'PrometheusGraphQuery', options: { query: 'node_memory_MemTotal_bytes{job="node",instance="$instance"} - node_memory_MemFree_bytes{job="node",instance="$instance"} - node_memory_Buffers_bytes{job="node",instance="$instance"} - node_memory_Cached_bytes{job="node",instance="$instance"}', }, }, { kind: 'PrometheusGraphQuery', options: { query: 'node_memory_Buffers_bytes{job="node",instance="$instance"}', }, }, { kind: 'PrometheusGraphQuery', options: { query: 'node_memory_Cached_bytes{job="node",instance="$instance"}', }, }, { kind: 'PrometheusGraphQuery', options: { query: 'node_memory_MemFree_bytes{job="node",instance="$instance"}', }, }, ], unit: { kind: 'Bytes' }, }, }, diskIO: { kind: 'LineChart', display: { name: 'Disk I/O Utilization' }, options: { queries: [ { kind: 'PrometheusGraphQuery', options: { query: 'rate(node_disk_io_time_seconds_total{job="node",instance="$instance",device!~"^(md\\\\d+$|dm-)"}[$interval])', }, }, ], unit: { kind: 'Percent' }, }, }, filesystemFullness: { kind: 'LineChart', display: { name: 'Filesystem Fullness' }, options: { queries: [ { kind: 'PrometheusGraphQuery', options: { query: '1 - node_filesystem_free_bytes{job="node",instance="$instance",fstype!="rootfs",mountpoint!~"/(run|var).*",mountpoint!=""} / node_filesystem_size_bytes{job="node",instance="$instance"}', }, }, ], unit: { kind: 'Percent' }, }, }, }, layouts: [ { kind: 'Grid', items: [ { x: 0, y: 0, width: 3, height: 4, content: { $ref: '#/panels/gaugeCpuBusy' }, }, { x: 3, y: 0, width: 3, height: 4, content: { $ref: '#/panels/gaugeSystemLoad' }, }, { x: 6, y: 0, width: 3, height: 4, content: { $ref: '#/panels/gaugeSystemLoadAlt' }, }, { x: 9, y: 0, width: 3, height: 4, content: { $ref: '#/panels/gaugeRam' }, }, { x: 12, y: 0, width: 3, height: 4, content: { $ref: '#/panels/gaugeSwap' }, }, { x: 15, y: 0, width: 3, height: 4, content: { $ref: '#/panels/gaugeRoot' }, }, { x: 18, y: 0, width: 6, height: 4, content: { $ref: '#/panels/emptyExample' }, }, ], }, { kind: 'Grid', items: [ // First Row { x: 0, y: 0, width: 12, height: 6, content: { $ref: '#/panels/cpu' }, }, { x: 12, y: 0, width: 12, height: 6, content: { $ref: '#/panels/memory' }, }, // Second Row { x: 0, y: 6, width: 12, height: 6, content: { $ref: '#/panels/diskIO' }, }, { x: 12, y: 6, width: 12, height: 6, content: { $ref: '#/panels/filesystemFullness' }, }, ], }, ], }, }; export default nodeExporterDashboard;
the_stack
import { Vector3, Quaternion, Object3D, Camera, PerspectiveCamera, Scene, AnimationMixer, AnimationClip, EventDispatcher, Euler, } from 'three' import gsap from 'gsap' /** * Event: Fired when CameraRig starts a transition * @example * ```javascript * rig.addEventListener('CameraMoveStart', handlerFunction) * ``` * */ export interface CameraMoveStartEvent { type: 'CameraMoveStart' } /** * Event: Fired on every tick of CameraRig's transition * @example * ```javascript * rig.addEventListener('CameraMoveUpdate', handlerFunction) * ``` * */ export interface CameraMoveUpdateEvent { type: 'CameraMoveUpdate' /** Percentage of transition completed, between 0 and 1. */ progress: number } /** * Event: Fired when CameraRig ends a transition * @example * ```javascript * rig.addEventListener('CameraMoveEnd', handlerFunction) * ``` * */ export interface CameraMoveEndEvent { type: 'CameraMoveEnd' } /** * Enum of camera actions used to control a {@link three-story-controls#CameraRig} */ export enum CameraAction { Pan = 'Pan', Tilt = 'Tilt', Roll = 'Roll', Truck = 'Truck', Pedestal = 'Pedestal', Dolly = 'Dolly', Zoom = 'Zoom', } /** * Enum of {@link three-story-controls#CameraRig} parts */ export enum RigComponent { Body = 'body', Head = 'head', Eyes = 'eyes', } /** * Enum of axes */ export enum Axis { X = 'x', Y = 'y', Z = 'z', } /** * Describe whether rig should translate along current rotation in each action axis */ export interface TranslateGuide { [CameraAction.Pan]: boolean [CameraAction.Tilt]: boolean [CameraAction.Roll]: boolean } /** * Mapping of rotation action to axis */ export interface ActionAxes { [CameraAction.Pan]: Axis [CameraAction.Tilt]: Axis [CameraAction.Roll]: Axis } const AxisVector = { [Axis.X]: new Vector3(1, 0, 0), [Axis.Y]: new Vector3(0, 1, 0), [Axis.Z]: new Vector3(0, 0, 1), } const ActionMappingByUpAxis = { [Axis.X]: { [CameraAction.Pan]: Axis.X, [CameraAction.Tilt]: Axis.Z, [CameraAction.Roll]: Axis.Y, }, [Axis.Y]: { [CameraAction.Pan]: Axis.Y, [CameraAction.Tilt]: Axis.X, [CameraAction.Roll]: Axis.Z, }, [Axis.Z]: { [CameraAction.Pan]: Axis.Z, [CameraAction.Tilt]: Axis.Y, [CameraAction.Roll]: Axis.X, }, } /** * The CameraRig holds the camera, and can respond to {@link three-story-controls#CameraAction}s such as Pan/Tilt/Dolly etc. It can also be controlled along a given path (in the form of an `AnimationClip`), or tweened to specified points. * * @remarks * The rig is constructed of three objects, analagous to a body, head and eyes. The camera is nested in the eyes and is never transformed directly. * * Instead of specifying the axis to rotate/translate the camera, {@link three-story-controls#CameraAction}s are used. The rotation order of actions is always `Pan` then `Tilt` then `Roll`. * The mapping of these actions to axes depends on the up axis, which defaults to `Y` (but can be changed with the {@link CameraRig.setUpAxis | setUpAxis() method}): * * * `CameraAction.Pan` rotates around the `Y` axis * * * `CameraAction.Tilt` rotates around the `X` axis * * * `CameraAction.Roll` rotates around the `Z` axis * * * `CameraAction.Dolly` translates on the `Z` axis * * * `CameraAction.Truck` translates on the `X` axis * * * `CameraAction.Pedestal` translates on the `Y` axis * * Translations will be applied to the 'body' of the rig, and rotations to the 'eyes'. If an animation clip is provided, or the camera is tweened to a specific location, * the rotations will be applied to the 'head', thus leaving the 'eyes' free to 'look around' from this base position. * * Additionally, the default setup assumes that the rig will move forward/backward (`Dolly`) in the direction the camera is panned to. * This can be configured through {@link CameraRig.translateAlong | translateAlong property}. * It can also be overwritten by providing the component name to the {@link CameraRig.do | do() method}, see {@link https://github.com/nytimes/three-story-controls/blob/main/src/controlschemes/ThreeDOFControls.ts#L96 | ThreeDOFControls implementation} for an example. * * To move the rig along a specified path, use the {@link CameraRig.setAnimationClip | setAnimationClip() method}, * and set the names for the `Translation` and `Rotation` objects to match those of the clip. The clip should have a `VectorKeyframeTrack` for the outer position/translation object, * and a `QuaternionKeyframeTrack` for the inner orientation/rotation object. * * See {@link three-story-controls#CameraMoveStartEvent}, {@link three-story-controls#CameraMoveUpdateEvent} and {@link three-story-controls#CameraMoveEndEvent} for emitted event signatures. */ export class CameraRig extends EventDispatcher { readonly camera: Camera readonly scene: Scene private body: Object3D private head: Object3D private eyes: Object3D private cameraIsInRig: boolean private inTransit = false private upAxis: Axis = Axis.Y private actionAxes: ActionAxes = ActionMappingByUpAxis[this.upAxis] private hasAnimation = false private animationClip: AnimationClip private mixer: AnimationMixer private animationTranslationObjectName = 'Translation' private animationRotationObjectName = 'Rotation' public translateAlong: TranslateGuide = { [CameraAction.Tilt]: false, [CameraAction.Pan]: true, [CameraAction.Roll]: false, } // Constructor constructor(camera: Camera, scene: Scene) { super() this.camera = camera this.scene = scene this.body = new Object3D() this.head = new Object3D() this.eyes = new Object3D() this.head.name = this.animationRotationObjectName this.body.name = this.animationTranslationObjectName this.body.rotation.order = this.getRotationOrder() this.head.rotation.order = this.getRotationOrder() this.eyes.rotation.order = this.getRotationOrder() this.scene.add(this.body.add(this.head.add(this.eyes.add(this.camera)))) this.cameraIsInRig = true this.unpackTransform() } /** * Get the axis for a given action * @param action * @returns x | y | z */ getAxisFor(action: CameraAction): string { return this.actionAxes[action] } /** * Get the axis' vector for a given action * @param action * @returns Normalized vector for the axis */ getAxisVectorFor(action: CameraAction): Vector3 { return AxisVector[this.actionAxes[action]] } /** * Main method for controlling the camera * @param action - Action to perform * @param amount - Amount to move/rotate/etc * @param rigComponent - Override the default component to perform the action on */ do(action: CameraAction, amount: number, rigComponent?: RigComponent): void { const targetComponent = this[rigComponent] switch (action) { case CameraAction.Pan: case CameraAction.Tilt: case CameraAction.Roll: { const axis = this.getAxisVectorFor(action) if (targetComponent) { targetComponent.rotateOnAxis(axis, amount) } else if (this.translateAlong[action]) { this.body.rotateOnAxis(axis, amount) } else { this.eyes.rotateOnAxis(axis, amount) } break } case CameraAction.Truck: { const axis = this.getAxisVectorFor(CameraAction.Tilt) const component = targetComponent || this.body component.translateOnAxis(axis, amount) break } case CameraAction.Pedestal: { const axis = this.getAxisVectorFor(CameraAction.Pan) const component = targetComponent || this.body component.translateOnAxis(axis, amount) break } case CameraAction.Dolly: { const axis = this.getAxisVectorFor(CameraAction.Roll) const component = targetComponent || this.body component.translateOnAxis(axis, amount) break } case CameraAction.Zoom: { if (this.camera instanceof PerspectiveCamera) { this.camera.fov = amount this.camera.updateProjectionMatrix() } break } default: break } } /** * Get world position and orientation of the camera */ getWorldCoordinates(): { position: Vector3; quaternion: Quaternion } { const position = new Vector3() this.camera.getWorldPosition(position) const quaternion = new Quaternion() this.camera.getWorldQuaternion(quaternion) return { position, quaternion } } /** * Sets world coordinates for the camera, and configures rig component transforms accordingly. * @param param0 */ setWorldCoordinates({ position, quaternion }: { position: Vector3; quaternion: Quaternion }): void { const currentRotation = new Euler().setFromQuaternion(quaternion, this.getRotationOrder()) const actions = [CameraAction.Pan, CameraAction.Tilt, CameraAction.Roll] this.eyes.position.set(0, 0, 0) this.eyes.rotation.set(0, 0, 0) this.head.position.set(0, 0, 0) this.head.rotation.set(0, 0, 0) this.body.position.copy(position) actions.forEach((action) => { const axis = this.getAxisFor(action) if (this.translateAlong[action]) { this.body.rotation[axis] = currentRotation[axis] } else { this.eyes.rotation[axis] = currentRotation[axis] } }) this.camera.rotation.set(0, 0, 0) this.camera.position.set(0, 0, 0) } /** * Packs transfrom into the body and head, and 0s out transforms of the eyes. Useful for preparing the * rig for control through an animation clip. */ packTransform(): void { const { position, quaternion } = this.getWorldCoordinates() this.body.position.copy(position) this.body.rotation.set(0, 0, 0) this.head.quaternion.copy(quaternion) this.head.position.set(0, 0, 0) this.eyes.position.set(0, 0, 0) this.eyes.rotation.set(0, 0, 0) } /** * Unpacks the current camera world coordinates and distributes transforms * across the rig componenets. */ unpackTransform(): void { const { position, quaternion } = this.getWorldCoordinates() this.setWorldCoordinates({ position, quaternion }) } /** * Disassemble the camera from the rig and attach it to the scene. */ disassemble(): void { if (this.cameraIsInRig) { this.scene.attach(this.camera) this.cameraIsInRig = false } } /** * Place the camera back in the rig */ assemble(): void { if (!this.cameraIsInRig) { this.eyes.attach(this.camera) this.unpackTransform() this.cameraIsInRig = true } } /** * Get the rotation order as a string compatible with what three.js uses */ getRotationOrder(): string { return Object.values(this.actionAxes).join('').toUpperCase() } /** * Whether the camera is currently attached to the rig */ isInRig(): boolean { return this.cameraIsInRig } /** * If the camera is in the middle of a transition */ isMoving(): boolean { return this.inTransit } /** * Set the up axis for the camera * @param axis - New Up axis */ setUpAxis(axis: Axis): void { this.upAxis = axis this.actionAxes = ActionMappingByUpAxis[this.upAxis] this.body.rotation.order = this.getRotationOrder() } /** * Set an animation clip for the rig * @param {AnimationClip} clip - AnimationClip containing a VectorKeyFrameTrack for position and a QuaternionKeyFrameTrack for rotation * @param {string} translationObjectName - Name of translation object * @param {string} rotationObjectName - Name of rotation object */ setAnimationClip(clip: AnimationClip, translationObjectName?: string, rotationObjectName?: string): void { this.animationClip = clip if (translationObjectName) this.animationTranslationObjectName = translationObjectName if (rotationObjectName) this.animationRotationObjectName = rotationObjectName this.hasAnimation = true // hack. threejs skips last frame when seek time = clip duration this.animationClip.duration += 0.01 this.mixer = new AnimationMixer(this.body) const action = this.mixer.clipAction(this.animationClip) action.clampWhenFinished = true action.play() } /** * Transition to a specific position and orientation in world space. * Transform on eyes will be reset to 0 as a result of this. * @param position * @param quaternion * @param duration * @param ease * @param useSlerp */ flyTo(position: Vector3, quaternion: Quaternion, duration = 1, ease = 'power1', useSlerp = true): void { if (!this.isMoving()) { const currentCoords = this.getWorldCoordinates() const currentValues = { px: currentCoords.position.x, py: currentCoords.position.y, pz: currentCoords.position.z, qx: currentCoords.quaternion.x, qy: currentCoords.quaternion.y, qz: currentCoords.quaternion.z, qw: currentCoords.quaternion.w, slerpAmt: 0, } const targetValues = { px: position.x, py: position.y, pz: position.z, qx: quaternion.x, qy: quaternion.y, qz: quaternion.z, qw: quaternion.w, slerpAmt: 1, } const tempQuaternion = new Quaternion() const startQuaternion = new Quaternion(currentValues.qx, currentValues.qy, currentValues.qz, currentValues.qw) const onStart = (): void => { this.inTransit = true this.packTransform() this.dispatchEvent({ type: 'CameraMoveStart' } as CameraMoveStartEvent) } const onUpdate = (tween): void => { this.body.position.set(currentValues.px, currentValues.py, currentValues.pz) if (useSlerp) { tempQuaternion.slerpQuaternions(startQuaternion, quaternion, currentValues.slerpAmt) this.head.setRotationFromQuaternion(tempQuaternion) } else { this.head.quaternion.set(currentValues.qx, currentValues.qy, currentValues.qz, currentValues.qw) } this.dispatchEvent({ type: 'CameraMoveUpdate', progress: tween.progress(), } as CameraMoveUpdateEvent) } const onComplete = (): void => { this.inTransit = false this.unpackTransform() this.dispatchEvent({ type: 'CameraMoveEnd' } as CameraMoveEndEvent) } gsap.to(currentValues, { duration, ease, ...targetValues, onStart, onUpdate: function () { onUpdate(this) }, onComplete, }) } } /** * Transition to a specific keyframe on the animation clip * Transform on eyes will be reset to 0 as a result of this. * @param frame - frame * @param duration - duration * @param ease - ease */ flyToKeyframe(frame: number, duration = 1, ease = 'power1'): void { if (this.hasAnimation && !this.isMoving()) { const currentValues = { time: this.mixer.time, } const targetValues = { time: this.animationClip.tracks[0].times[frame], } const onStart = (): void => { this.inTransit = true this.dispatchEvent({ type: 'CameraMoveStart' } as CameraMoveStartEvent) } const onUpdate = (tween): void => { this.mixer.setTime(currentValues.time) this.dispatchEvent({ type: 'CameraMoveUpdate', progress: tween.progress(), } as CameraMoveUpdateEvent) } const onComplete = (): void => { this.inTransit = false this.dispatchEvent({ type: 'CameraMoveEnd' } as CameraMoveEndEvent) } gsap.to(currentValues, { duration, ease, ...targetValues, onStart, onUpdate: function () { onUpdate(this) }, onComplete, }) } } /** * @param percentage - percentage of animation clip to move to, between 0 and 1 */ setAnimationPercentage(percentage: number): void { if (this.hasAnimation) { const percent = Math.max( 0, Math.min(percentage * this.animationClip.duration, this.animationClip.duration - 0.0001), ) this.mixer.setTime(percent) } } /** * @param time - timestamp of animation clip to move to */ setAnimationTime(time: number): void { if (this.hasAnimation) this.mixer.setTime(time) } /** * @param frame - frame of animation clip to move to */ setAnimationKeyframe(frame: number): void { if (this.hasAnimation) this.mixer.setTime(this.animationClip.tracks[0].times[frame]) } }
the_stack
import '../../_version.js'; interface LoggableObject { [key: string]: string | number; } interface MessageMap { [messageID: string]: (param: LoggableObject) => string; } export const messages: MessageMap = { 'invalid-value': ({paramName, validValueDescription, value}) => { if (!paramName || !validValueDescription) { throw new Error(`Unexpected input to 'invalid-value' error.`); } return ( `The '${paramName}' parameter was given a value with an ` + `unexpected value. ${validValueDescription} Received a value of ` + `${JSON.stringify(value)}.` ); }, 'not-an-array': ({moduleName, className, funcName, paramName}) => { if (!moduleName || !className || !funcName || !paramName) { throw new Error(`Unexpected input to 'not-an-array' error.`); } return ( `The parameter '${paramName}' passed into ` + `'${moduleName}.${className}.${funcName}()' must be an array.` ); }, 'incorrect-type': ({ expectedType, paramName, moduleName, className, funcName, }) => { if (!expectedType || !paramName || !moduleName || !funcName) { throw new Error(`Unexpected input to 'incorrect-type' error.`); } const classNameStr = className ? `${className}.` : ''; return ( `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}` + `${funcName}()' must be of type ${expectedType}.` ); }, 'incorrect-class': ({ expectedClassName, paramName, moduleName, className, funcName, isReturnValueProblem, }) => { if (!expectedClassName || !moduleName || !funcName) { throw new Error(`Unexpected input to 'incorrect-class' error.`); } const classNameStr = className ? `${className}.` : ''; if (isReturnValueProblem) { return ( `The return value from ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.` ); } return ( `The parameter '${paramName}' passed into ` + `'${moduleName}.${classNameStr}${funcName}()' ` + `must be an instance of class ${expectedClassName}.` ); }, 'missing-a-method': ({ expectedMethod, paramName, moduleName, className, funcName, }) => { if ( !expectedMethod || !paramName || !moduleName || !className || !funcName ) { throw new Error(`Unexpected input to 'missing-a-method' error.`); } return ( `${moduleName}.${className}.${funcName}() expected the ` + `'${paramName}' parameter to expose a '${expectedMethod}' method.` ); }, 'add-to-cache-list-unexpected-type': ({entry}) => { return ( `An unexpected entry was passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' The entry ` + `'${JSON.stringify( entry, )}' isn't supported. You must supply an array of ` + `strings with one or more characters, objects with a url property or ` + `Request objects.` ); }, 'add-to-cache-list-conflicting-entries': ({firstEntry, secondEntry}) => { if (!firstEntry || !secondEntry) { throw new Error( `Unexpected input to ` + `'add-to-cache-list-duplicate-entries' error.`, ); } return ( `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${firstEntry} but different revision details. Workbox is ` + `unable to cache and version the asset correctly. Please remove one ` + `of the entries.` ); }, 'plugin-error-request-will-fetch': ({thrownErrorMessage}) => { if (!thrownErrorMessage) { throw new Error( `Unexpected input to ` + `'plugin-error-request-will-fetch', error.`, ); } return ( `An error was thrown by a plugins 'requestWillFetch()' method. ` + `The thrown error message was: '${thrownErrorMessage}'.` ); }, 'invalid-cache-name': ({cacheNameId, value}) => { if (!cacheNameId) { throw new Error( `Expected a 'cacheNameId' for error 'invalid-cache-name'`, ); } return ( `You must provide a name containing at least one character for ` + `setCacheDetails({${cacheNameId}: '...'}). Received a value of ` + `'${JSON.stringify(value)}'` ); }, 'unregister-route-but-not-found-with-method': ({method}) => { if (!method) { throw new Error( `Unexpected input to ` + `'unregister-route-but-not-found-with-method' error.`, ); } return ( `The route you're trying to unregister was not previously ` + `registered for the method type '${method}'.` ); }, 'unregister-route-route-not-registered': () => { return ( `The route you're trying to unregister was not previously ` + `registered.` ); }, 'queue-replay-failed': ({name}) => { return `Replaying the background sync queue '${name}' failed.`; }, 'duplicate-queue-name': ({name}) => { return ( `The Queue name '${name}' is already being used. ` + `All instances of backgroundSync.Queue must be given unique names.` ); }, 'expired-test-without-max-age': ({methodName, paramName}) => { return ( `The '${methodName}()' method can only be used when the ` + `'${paramName}' is used in the constructor.` ); }, 'unsupported-route-type': ({moduleName, className, funcName, paramName}) => { return ( `The supplied '${paramName}' parameter was an unsupported type. ` + `Please check the docs for ${moduleName}.${className}.${funcName} for ` + `valid input types.` ); }, 'not-array-of-class': ({ value, expectedClass, moduleName, className, funcName, paramName, }) => { return ( `The supplied '${paramName}' parameter must be an array of ` + `'${expectedClass}' objects. Received '${JSON.stringify(value)},'. ` + `Please check the call to ${moduleName}.${className}.${funcName}() ` + `to fix the issue.` ); }, 'max-entries-or-age-required': ({moduleName, className, funcName}) => { return ( `You must define either config.maxEntries or config.maxAgeSeconds` + `in ${moduleName}.${className}.${funcName}` ); }, 'statuses-or-headers-required': ({moduleName, className, funcName}) => { return ( `You must define either config.statuses or config.headers` + `in ${moduleName}.${className}.${funcName}` ); }, 'invalid-string': ({moduleName, funcName, paramName}) => { if (!paramName || !moduleName || !funcName) { throw new Error(`Unexpected input to 'invalid-string' error.`); } return ( `When using strings, the '${paramName}' parameter must start with ` + `'http' (for cross-origin matches) or '/' (for same-origin matches). ` + `Please see the docs for ${moduleName}.${funcName}() for ` + `more info.` ); }, 'channel-name-required': () => { return ( `You must provide a channelName to construct a ` + `BroadcastCacheUpdate instance.` ); }, 'invalid-responses-are-same-args': () => { return ( `The arguments passed into responsesAreSame() appear to be ` + `invalid. Please ensure valid Responses are used.` ); }, 'expire-custom-caches-only': () => { return ( `You must provide a 'cacheName' property when using the ` + `expiration plugin with a runtime caching strategy.` ); }, 'unit-must-be-bytes': ({normalizedRangeHeader}) => { if (!normalizedRangeHeader) { throw new Error(`Unexpected input to 'unit-must-be-bytes' error.`); } return ( `The 'unit' portion of the Range header must be set to 'bytes'. ` + `The Range header provided was "${normalizedRangeHeader}"` ); }, 'single-range-only': ({normalizedRangeHeader}) => { if (!normalizedRangeHeader) { throw new Error(`Unexpected input to 'single-range-only' error.`); } return ( `Multiple ranges are not supported. Please use a single start ` + `value, and optional end value. The Range header provided was ` + `"${normalizedRangeHeader}"` ); }, 'invalid-range-values': ({normalizedRangeHeader}) => { if (!normalizedRangeHeader) { throw new Error(`Unexpected input to 'invalid-range-values' error.`); } return ( `The Range header is missing both start and end values. At least ` + `one of those values is needed. The Range header provided was ` + `"${normalizedRangeHeader}"` ); }, 'no-range-header': () => { return `No Range header was found in the Request provided.`; }, 'range-not-satisfiable': ({size, start, end}) => { return ( `The start (${start}) and end (${end}) values in the Range are ` + `not satisfiable by the cached response, which is ${size} bytes.` ); }, 'attempt-to-cache-non-get-request': ({url, method}) => { return ( `Unable to cache '${url}' because it is a '${method}' request and ` + `only 'GET' requests can be cached.` ); }, 'cache-put-with-no-response': ({url}) => { return ( `There was an attempt to cache '${url}' but the response was not ` + `defined.` ); }, 'no-response': ({url, error}) => { let message = `The strategy could not generate a response for '${url}'.`; if (error) { message += ` The underlying error is ${error}.`; } return message; }, 'bad-precaching-response': ({url, status}) => { return ( `The precaching request for '${url}' failed` + (status ? ` with an HTTP status of ${status}.` : `.`) ); }, 'non-precached-url': ({url}) => { return ( `createHandlerBoundToURL('${url}') was called, but that URL is ` + `not precached. Please pass in a URL that is precached instead.` ); }, 'add-to-cache-list-conflicting-integrities': ({url}) => { return ( `Two of the entries passed to ` + `'workbox-precaching.PrecacheController.addToCacheList()' had the URL ` + `${url} with different integrity values. Please remove one of them.` ); }, 'missing-precache-entry': ({cacheName, url}) => { return `Unable to find a precached response in ${cacheName} for ${url}.`; }, 'cross-origin-copy-response': ({origin}) => { return ( `workbox-core.copyResponse() can only be used with same-origin ` + `responses. It was passed a response with origin ${origin}.` ); }, };
the_stack
import { createSchemalize } from './utils' import { ColumnDefinitions } from './operations/tablesTypes' import { DB, MigrationBuilder, MigrationOptions, Logger } from './types' import * as domains from './operations/domains' import * as extensions from './operations/extensions' import * as functions from './operations/functions' import * as indexes from './operations/indexes' import * as operators from './operations/operators' import * as other from './operations/other' import * as policies from './operations/policies' import * as roles from './operations/roles' import * as schemas from './operations/schemas' import * as sequences from './operations/sequences' import * as tables from './operations/tables' import * as triggers from './operations/triggers' import * as types from './operations/types' import * as views from './operations/views' import * as mViews from './operations/viewsMaterialized' import PgLiteral from './operations/PgLiteral' export default class MigrationBuilderImpl implements MigrationBuilder { public readonly createExtension: (...args: Parameters<extensions.CreateExtension>) => void public readonly dropExtension: (...args: Parameters<extensions.DropExtension>) => void public readonly addExtension: (...args: Parameters<extensions.CreateExtension>) => void public readonly createTable: (...args: Parameters<tables.CreateTable>) => void public readonly dropTable: (...args: Parameters<tables.DropTable>) => void public readonly renameTable: (...args: Parameters<tables.RenameTable>) => void public readonly alterTable: (...args: Parameters<tables.AlterTable>) => void public readonly addColumns: (...args: Parameters<tables.AddColumns>) => void public readonly dropColumns: (...args: Parameters<tables.DropColumns>) => void public readonly renameColumn: (...args: Parameters<tables.RenameColumn>) => void public readonly alterColumn: (...args: Parameters<tables.AlterColumn>) => void public readonly addColumn: (...args: Parameters<tables.AddColumns>) => void public readonly dropColumn: (...args: Parameters<tables.DropColumns>) => void public readonly addConstraint: (...args: Parameters<tables.CreateConstraint>) => void public readonly dropConstraint: (...args: Parameters<tables.DropConstraint>) => void public readonly renameConstraint: (...args: Parameters<tables.RenameConstraint>) => void public readonly createConstraint: (...args: Parameters<tables.CreateConstraint>) => void public readonly createType: (...args: Parameters<types.CreateType>) => void public readonly dropType: (...args: Parameters<types.DropType>) => void public readonly addType: (...args: Parameters<types.CreateType>) => void public readonly renameType: (...args: Parameters<types.RenameType>) => void public readonly renameTypeAttribute: (...args: Parameters<types.RenameTypeAttribute>) => void public readonly renameTypeValue: (...args: Parameters<types.RenameTypeValue>) => void public readonly addTypeAttribute: (...args: Parameters<types.AddTypeAttribute>) => void public readonly dropTypeAttribute: (...args: Parameters<types.DropTypeAttribute>) => void public readonly setTypeAttribute: (...args: Parameters<types.SetTypeAttribute>) => void public readonly addTypeValue: (...args: Parameters<types.AddTypeValue>) => void public readonly createIndex: (...args: Parameters<indexes.CreateIndex>) => void public readonly dropIndex: (...args: Parameters<indexes.DropIndex>) => void public readonly addIndex: (...args: Parameters<indexes.CreateIndex>) => void public readonly createRole: (...args: Parameters<roles.CreateRole>) => void public readonly dropRole: (...args: Parameters<roles.DropRole>) => void public readonly alterRole: (...args: Parameters<roles.AlterRole>) => void public readonly renameRole: (...args: Parameters<roles.RenameRole>) => void public readonly createFunction: (...args: Parameters<functions.CreateFunction>) => void public readonly dropFunction: (...args: Parameters<functions.DropFunction>) => void public readonly renameFunction: (...args: Parameters<functions.RenameFunction>) => void public readonly createTrigger: (...args: Parameters<triggers.CreateTrigger>) => void public readonly dropTrigger: (...args: Parameters<triggers.DropTrigger>) => void public readonly renameTrigger: (...args: Parameters<triggers.RenameTrigger>) => void public readonly createSchema: (...args: Parameters<schemas.CreateSchema>) => void public readonly dropSchema: (...args: Parameters<schemas.DropSchema>) => void public readonly renameSchema: (...args: Parameters<schemas.RenameSchema>) => void public readonly createDomain: (...args: Parameters<domains.CreateDomain>) => void public readonly dropDomain: (...args: Parameters<domains.DropDomain>) => void public readonly alterDomain: (...args: Parameters<domains.AlterDomain>) => void public readonly renameDomain: (...args: Parameters<domains.RenameDomain>) => void public readonly createSequence: (...args: Parameters<sequences.CreateSequence>) => void public readonly dropSequence: (...args: Parameters<sequences.DropSequence>) => void public readonly alterSequence: (...args: Parameters<sequences.AlterSequence>) => void public readonly renameSequence: (...args: Parameters<sequences.RenameSequence>) => void public readonly createOperator: (...args: Parameters<operators.CreateOperator>) => void public readonly dropOperator: (...args: Parameters<operators.DropOperator>) => void public readonly createOperatorClass: (...args: Parameters<operators.CreateOperatorClass>) => void public readonly dropOperatorClass: (...args: Parameters<operators.DropOperatorClass>) => void public readonly renameOperatorClass: (...args: Parameters<operators.RenameOperatorClass>) => void public readonly createOperatorFamily: (...args: Parameters<operators.CreateOperatorFamily>) => void public readonly dropOperatorFamily: (...args: Parameters<operators.DropOperatorFamily>) => void public readonly renameOperatorFamily: (...args: Parameters<operators.RenameOperatorFamily>) => void public readonly addToOperatorFamily: (...args: Parameters<operators.AddToOperatorFamily>) => void public readonly removeFromOperatorFamily: (...args: Parameters<operators.RemoveFromOperatorFamily>) => void public readonly createPolicy: (...args: Parameters<policies.CreatePolicy>) => void public readonly dropPolicy: (...args: Parameters<policies.DropPolicy>) => void public readonly alterPolicy: (...args: Parameters<policies.AlterPolicy>) => void public readonly renamePolicy: (...args: Parameters<policies.RenamePolicy>) => void public readonly createView: (...args: Parameters<views.CreateView>) => void public readonly dropView: (...args: Parameters<views.DropView>) => void public readonly alterView: (...args: Parameters<views.AlterView>) => void public readonly alterViewColumn: (...args: Parameters<views.AlterViewColumn>) => void public readonly renameView: (...args: Parameters<views.RenameView>) => void public readonly createMaterializedView: (...args: Parameters<mViews.CreateMaterializedView>) => void public readonly dropMaterializedView: (...args: Parameters<mViews.DropMaterializedView>) => void public readonly alterMaterializedView: (...args: Parameters<mViews.AlterMaterializedView>) => void public readonly renameMaterializedView: (...args: Parameters<mViews.RenameMaterializedView>) => void public readonly renameMaterializedViewColumn: (...args: Parameters<mViews.RenameMaterializedViewColumn>) => void public readonly refreshMaterializedView: (...args: Parameters<mViews.RefreshMaterializedView>) => void public readonly sql: (...args: Parameters<other.Sql>) => void public readonly func: (sql: string) => PgLiteral public readonly db: DB private _steps: string[] private _REVERSE_MODE: boolean private _useTransaction: boolean constructor(db: DB, typeShorthands: ColumnDefinitions | undefined, shouldDecamelize: boolean, logger: Logger) { this._steps = [] this._REVERSE_MODE = false // by default, all migrations are wrapped in a transaction this._useTransaction = true // eslint-disable-next-line @typescript-eslint/no-explicit-any type OperationFn = (...args: any[]) => string | string[] type Operation = OperationFn & { reverse?: OperationFn } // this function wraps each operation within a function that either // calls the operation or its reverse, and appends the result (array of sql statements) // to the steps array const wrap = <T extends Operation>(operation: T) => (...args: Parameters<T>) => { if (this._REVERSE_MODE) { if (typeof operation.reverse !== 'function') { const name = `pgm.${operation.name}()` throw new Error(`Impossible to automatically infer down migration for "${name}"`) } this._steps = this._steps.concat(operation.reverse(...args)) } else { this._steps = this._steps.concat(operation(...args)) } } const options: MigrationOptions = { typeShorthands, schemalize: createSchemalize(shouldDecamelize, false), literal: createSchemalize(shouldDecamelize, true), logger, } // defines the methods that are accessible via pgm in each migrations // there are some convenience aliases to make usage easier this.createExtension = wrap(extensions.createExtension(options)) this.dropExtension = wrap(extensions.dropExtension(options)) this.addExtension = this.createExtension this.createTable = wrap(tables.createTable(options)) this.dropTable = wrap(tables.dropTable(options)) this.renameTable = wrap(tables.renameTable(options)) this.alterTable = wrap(tables.alterTable(options)) this.addColumns = wrap(tables.addColumns(options)) this.dropColumns = wrap(tables.dropColumns(options)) this.renameColumn = wrap(tables.renameColumn(options)) this.alterColumn = wrap(tables.alterColumn(options)) this.addColumn = this.addColumns this.dropColumn = this.dropColumns this.addConstraint = wrap(tables.addConstraint(options)) this.dropConstraint = wrap(tables.dropConstraint(options)) this.renameConstraint = wrap(tables.renameConstraint(options)) this.createConstraint = this.addConstraint this.createType = wrap(types.createType(options)) this.dropType = wrap(types.dropType(options)) this.addType = this.createType this.renameType = wrap(types.renameType(options)) this.renameTypeAttribute = wrap(types.renameTypeAttribute(options)) this.renameTypeValue = wrap(types.renameTypeValue(options)) this.addTypeAttribute = wrap(types.addTypeAttribute(options)) this.dropTypeAttribute = wrap(types.dropTypeAttribute(options)) this.setTypeAttribute = wrap(types.setTypeAttribute(options)) this.addTypeValue = wrap(types.addTypeValue(options)) this.createIndex = wrap(indexes.createIndex(options)) this.dropIndex = wrap(indexes.dropIndex(options)) this.addIndex = this.createIndex this.createRole = wrap(roles.createRole(options)) this.dropRole = wrap(roles.dropRole(options)) this.alterRole = wrap(roles.alterRole(options)) this.renameRole = wrap(roles.renameRole(options)) this.createFunction = wrap(functions.createFunction(options)) this.dropFunction = wrap(functions.dropFunction(options)) this.renameFunction = wrap(functions.renameFunction(options)) this.createTrigger = wrap(triggers.createTrigger(options)) this.dropTrigger = wrap(triggers.dropTrigger(options)) this.renameTrigger = wrap(triggers.renameTrigger(options)) this.createSchema = wrap(schemas.createSchema(options)) this.dropSchema = wrap(schemas.dropSchema(options)) this.renameSchema = wrap(schemas.renameSchema(options)) this.createDomain = wrap(domains.createDomain(options)) this.dropDomain = wrap(domains.dropDomain(options)) this.alterDomain = wrap(domains.alterDomain(options)) this.renameDomain = wrap(domains.renameDomain(options)) this.createSequence = wrap(sequences.createSequence(options)) this.dropSequence = wrap(sequences.dropSequence(options)) this.alterSequence = wrap(sequences.alterSequence(options)) this.renameSequence = wrap(sequences.renameSequence(options)) this.createOperator = wrap(operators.createOperator(options)) this.dropOperator = wrap(operators.dropOperator(options)) this.createOperatorClass = wrap(operators.createOperatorClass(options)) this.dropOperatorClass = wrap(operators.dropOperatorClass(options)) this.renameOperatorClass = wrap(operators.renameOperatorClass(options)) this.createOperatorFamily = wrap(operators.createOperatorFamily(options)) this.dropOperatorFamily = wrap(operators.dropOperatorFamily(options)) this.renameOperatorFamily = wrap(operators.renameOperatorFamily(options)) this.addToOperatorFamily = wrap(operators.addToOperatorFamily(options)) this.removeFromOperatorFamily = wrap(operators.removeFromOperatorFamily(options)) this.createPolicy = wrap(policies.createPolicy(options)) this.dropPolicy = wrap(policies.dropPolicy(options)) this.alterPolicy = wrap(policies.alterPolicy(options)) this.renamePolicy = wrap(policies.renamePolicy(options)) this.createView = wrap(views.createView(options)) this.dropView = wrap(views.dropView(options)) this.alterView = wrap(views.alterView(options)) this.alterViewColumn = wrap(views.alterViewColumn(options)) this.renameView = wrap(views.renameView(options)) this.createMaterializedView = wrap(mViews.createMaterializedView(options)) this.dropMaterializedView = wrap(mViews.dropMaterializedView(options)) this.alterMaterializedView = wrap(mViews.alterMaterializedView(options)) this.renameMaterializedView = wrap(mViews.renameMaterializedView(options)) this.renameMaterializedViewColumn = wrap(mViews.renameMaterializedViewColumn(options)) this.refreshMaterializedView = wrap(mViews.refreshMaterializedView(options)) this.sql = wrap(other.sql(options)) // Other utilities which may be useful // .func creates a string which will not be escaped // common uses are for PG functions, ex: { ... default: pgm.func('NOW()') } this.func = PgLiteral.create // expose DB so we can access database within transaction /* eslint-disable @typescript-eslint/no-explicit-any */ const wrapDB = <T extends any[], R>(operation: (...args: T) => R) => (...args: T) => { if (this._REVERSE_MODE) { throw new Error('Impossible to automatically infer down migration') } return operation(...args) } /* eslint-enable @typescript-eslint/no-explicit-any */ this.db = { query: wrapDB(db.query), select: wrapDB(db.select), } } enableReverseMode(): this { this._REVERSE_MODE = true return this } noTransaction(): this { this._useTransaction = false return this } isUsingTransaction(): boolean { return this._useTransaction } getSql(): string { return `${this.getSqlSteps().join('\n')}\n` } getSqlSteps(): string[] { // in reverse mode, we flip the order of the statements return this._REVERSE_MODE ? this._steps.slice().reverse() : this._steps } } /* eslint-enable security/detect-non-literal-fs-filename */
the_stack
import { isSport, PHASE } from "../../../common"; import { GameSim, allStar, finances, freeAgents, phase, player, season, team, trade, } from ".."; import loadTeams from "./loadTeams"; import updatePlayoffSeries from "./updatePlayoffSeries"; import writeGameStats from "./writeGameStats"; import writePlayerStats from "./writePlayerStats"; import writeTeamStats from "./writeTeamStats"; import { idb } from "../../db"; import { advStats, g, helpers, lock, logEvent, toUI, updatePlayMenu, updateStatus, recomputeLocalUITeamOvrs, local, } from "../../util"; import type { Conditions, ScheduleGame, UpdateEvents, } from "../../../common/types"; import allowForceTie from "../../../common/allowForceTie"; /** * Play one or more days of games. * * This also handles the case where there are no more games to be played by switching the phase to either the playoffs or before the draft, as appropriate. * * @memberOf core.game * @param {number} numDays An integer representing the number of days to be simulated. If numDays is larger than the number of days remaining, then all games will be simulated up until either the end of the regular season or the end of the playoffs, whichever happens first. * @param {boolean} start Is this a new request from the user to play games (true) or a recursive callback to simulate another day (false)? If true, then there is a check to make sure simulating games is allowed. Default true. * @param {number?} gidOneGame Game ID number if we just want to sim one game rather than the whole day. Must be defined if playByPlay is true. * @param {boolean?} playByPlay When true, an array of strings representing the play-by-play game simulation are included in the api.realtimeUpdate raw call. */ const play = async ( numDays: number, conditions: Conditions, start: boolean = true, gidOneGame?: number, playByPlay?: boolean, ) => { // This is called when there are no more games to play, either due to the user's request (e.g. 1 week) elapsing or at the end of the regular season const cbNoGames = async (playoffsOver: boolean = false) => { await updateStatus("Saving..."); await idb.cache.flush(); await updateStatus("Idle"); await lock.set("gameSim", false); // Check to see if the season is over if (g.get("phase") < PHASE.PLAYOFFS) { const schedule = await season.getSchedule(); if (schedule.length === 0) { await phase.newPhase( PHASE.PLAYOFFS, conditions, gidOneGame !== undefined, ); } else { const allStarNext = await allStar.nextGameIsAllStar(schedule); if (allStarNext && gidOneGame === undefined) { toUI( "realtimeUpdate", [[], helpers.leagueUrl(["all_star"])], conditions, ); } } } else if (playoffsOver) { await phase.newPhase( PHASE.DRAFT_LOTTERY, conditions, gidOneGame !== undefined, ); } await updatePlayMenu(); }; // Saves a vector of results objects for a day, as is output from cbSimGames const cbSaveResults = async (results: any[], dayOver: boolean) => { // Before writeGameStats, so LeagueTopBar can not update with game result if (gidOneGame !== undefined && playByPlay) { await toUI("updateLocal", [{ liveGameInProgress: true }]); } // Before writeGameStats, so injury is set correctly const { injuryTexts, pidsInjuredOneGameOrLess, stopPlay } = await writePlayerStats(results, conditions); const gidsFinished = await Promise.all( results.map(async result => { const att = await writeTeamStats(result); await writeGameStats(result, att, conditions); return result.gid; }), ); // Delete finished games from schedule for (const gid of gidsFinished) { if (typeof gid === "number") { await idb.cache.schedule.delete(gid); } } if (g.get("phase") === PHASE.PLAYOFFS) { // Update playoff series W/L await updatePlayoffSeries(results, conditions); } else { // Update clinchedPlayoffs, only if there are games left in the schedule. Otherwise, this would be inaccruate (not correctly accounting for tiebreakers) and redundant (going to be called again on phase change) const schedule = await season.getSchedule(); if (schedule.length > 0) { await team.updateClinchedPlayoffs(false, conditions); } } if (injuryTexts.length > 0) { logEvent( { type: "injuredList", text: injuryTexts.join("<br>"), showNotification: true, persistent: stopPlay, saveToDb: false, }, conditions, ); } const updateEvents: UpdateEvents = ["gameSim"]; if (dayOver) { const phase = g.get("phase"); if ( phase === PHASE.REGULAR_SEASON || phase === PHASE.AFTER_TRADE_DEADLINE ) { await freeAgents.decreaseDemands(); await freeAgents.autoSign(); } if (phase === PHASE.REGULAR_SEASON) { await trade.betweenAiTeams(); } // Budget is just for ticket prices await finances.updateRanks(["budget", "expenses", "revenues"]); local.minFractionDiffs = undefined; const healedTexts: string[] = []; // Injury countdown - This must be after games are saved, of there is a race condition involving new injury assignment in writeStats. Free agents are handled in decreaseDemands. const players = await idb.cache.players.indexGetAll("playersByTid", [ 0, Infinity, ]); for (const p of players) { let changed = false; if (p.injury.gamesRemaining > 0) { p.injury.gamesRemaining -= 1; changed = true; } // Is it already over? if (p.injury.type !== "Healthy" && p.injury.gamesRemaining <= 0) { const score = p.injury.score; p.injury = { type: "Healthy", gamesRemaining: 0, }; changed = true; const healedText = `${ p.ratings.at(-1)!.pos } <a href="${helpers.leagueUrl(["player", p.pid])}">${p.firstName} ${ p.lastName }</a>`; if ( p.tid === g.get("userTid") && !pidsInjuredOneGameOrLess.has(p.pid) ) { healedTexts.push(healedText); } logEvent( { type: "healed", text: `${healedText} has recovered from his injury.`, showNotification: false, pids: [p.pid], tids: [p.tid], score, }, conditions, ); } // Also check for gamesUntilTradable if (!p.hasOwnProperty("gamesUntilTradable")) { p.gamesUntilTradable = 0; // Initialize for old leagues changed = true; } else if (p.gamesUntilTradable > 0) { p.gamesUntilTradable -= 1; changed = true; } if (changed) { await idb.cache.players.put(p); } } if (healedTexts.length > 0) { logEvent( { type: "healedList", text: healedTexts.join("<br>"), showNotification: true, saveToDb: false, }, conditions, ); } // Tragic deaths only happen during the regular season! if ( g.get("phase") !== PHASE.PLAYOFFS && Math.random() < g.get("tragicDeathRate") ) { await player.killOne(conditions); if (g.get("stopOnInjury")) { await lock.set("stopGameSim", true); } updateEvents.push("playerMovement"); } } // More stuff for LeagueTopBar - update ovrs based on injuries await recomputeLocalUITeamOvrs(); await advStats(); const playoffsOver = g.get("phase") === PHASE.PLAYOFFS && (await season.newSchedulePlayoffsDay()); let raw; let url; // If there was a play by play done for one of these games, get it if (gidOneGame !== undefined && playByPlay) { for (let i = 0; i < results.length; i++) { if (results[i].playByPlay !== undefined) { raw = { gidOneGame, playByPlay: results[i].playByPlay, }; url = helpers.leagueUrl(["live_game"]); } } // This is not ideal... it means no event will be sent to other open tabs. But I don't have a way of saying "send this update to all tabs except X" currently await toUI("realtimeUpdate", [updateEvents, url, raw], conditions); } else { url = undefined; await toUI("realtimeUpdate", [updateEvents]); } if (numDays - 1 <= 0 || playoffsOver) { await cbNoGames(playoffsOver); } else { await play(numDays - 1, conditions, false); } }; const getResult = ({ gid, day, teams, doPlayByPlay = false, homeCourtFactor = 1, disableHomeCourtAdvantage = false, }: { gid: number; day: number | undefined; teams: [any, any]; doPlayByPlay?: boolean; homeCourtFactor?: number; disableHomeCourtAdvantage?: boolean; }) => { // In FBGM, need to do depth chart generation here (after deepCopy in forceWin case) to maintain referential integrity of players (same object in depth and team). for (const t of teams) { if (t.depth !== undefined) { t.depth = team.getDepthPlayers(t.depth, t.player); } } return new GameSim({ gid, day, teams, doPlayByPlay, homeCourtFactor, disableHomeCourtAdvantage, }).run(); }; // Simulates a day of games (whatever is in schedule) and passes the results to cbSaveResults const cbSimGames = async ( schedule: ScheduleGame[], teams: Record<number, any>, dayOver: boolean, ) => { const results: any[] = []; for (const game of schedule) { const doPlayByPlay = gidOneGame === game.gid && playByPlay; const teamsInput = [teams[game.homeTid], teams[game.awayTid]] as any; const forceTie = game.forceWin === "tie"; const invalidForceTie = forceTie && !allowForceTie({ homeTid: game.homeTid, awayTid: game.awayTid, ties: g.get("ties", "current"), phase: g.get("phase"), elam: g.get("elam"), elamASG: g.get("elamASG"), }); if (g.get("godMode") && game.forceWin !== undefined && !invalidForceTie) { const NUM_TRIES = 2000; const START_CHANGING_HOME_COURT_ADVANTAGE = NUM_TRIES / 4; const forceWinHome = game.forceWin === game.homeTid; let homeCourtFactor = 1; let found = false; let homeWonLastGame = false; let homeWonCounter = 0; for (let i = 0; i < NUM_TRIES; i++) { if (i >= START_CHANGING_HOME_COURT_ADVANTAGE) { if (!forceTie) { // Scale from 1x to 3x linearly, after staying at 1x for some time homeCourtFactor = 1 + (2 * (i - START_CHANGING_HOME_COURT_ADVANTAGE)) / (NUM_TRIES - START_CHANGING_HOME_COURT_ADVANTAGE); if (!forceWinHome) { homeCourtFactor = 1 / homeCourtFactor; } } else { // Keep track of homeWonCounter only after START_CHANGING_HOME_COURT_ADVANTAGE if (homeWonLastGame) { homeWonCounter += 1; } else { homeWonCounter -= 1; } // Scale from 1 to 3, where 3 happens when homeWonCounter is 1000 homeCourtFactor = 1 + Math.min(2, (Math.abs(homeWonCounter) * 2) / 1000); if (homeWonCounter > 0) { homeCourtFactor = 1 / homeCourtFactor; } } } const result = getResult({ gid: game.gid, day: game.day, teams: helpers.deepCopy(teamsInput), // So stats start at 0 each time doPlayByPlay, homeCourtFactor, }); let wonTid: number | undefined; if (result.team[0].stat.pts > result.team[1].stat.pts) { wonTid = result.team[0].id; homeWonLastGame = true; } else if (result.team[0].stat.pts < result.team[1].stat.pts) { wonTid = result.team[1].id; homeWonLastGame = false; } if ( (forceTie && wonTid === undefined) || (!forceTie && wonTid === game.forceWin) ) { found = true; (result as any).forceWin = i + 1; results.push(result); break; } } if (!found) { const teamInfoCache = g.get("teamInfoCache"); let suffix: string; if (game.forceWin === "tie") { suffix = `the ${teamInfoCache[game.homeTid].region} ${ teamInfoCache[game.homeTid].name } tied the ${teamInfoCache[game.awayTid].region} ${ teamInfoCache[game.awayTid].name }`; } else { const otherTid = forceWinHome ? game.awayTid : game.homeTid; suffix = `the ${teamInfoCache[game.forceWin].region} ${ teamInfoCache[game.forceWin].name } beat the ${teamInfoCache[otherTid].region} ${ teamInfoCache[otherTid].name }`; } logEvent( { type: "error", text: `Could not find a simulation in ${helpers.numberWithCommas( NUM_TRIES, )} tries where ${suffix}.`, showNotification: true, persistent: true, saveToDb: false, }, conditions, ); await lock.set("stopGameSim", true); } } else { let disableHomeCourtAdvantage = false; if (isSport("football") && g.get("phase") === PHASE.PLAYOFFS) { const numGamesPlayoffSeries = g.get( "numGamesPlayoffSeries", "current", ); const numFinalsGames = numGamesPlayoffSeries.at(-1); // If finals is 1 game, then no home court advantage if (numFinalsGames === 1) { const playoffSeries = await idb.cache.playoffSeries.get( g.get("season"), ); if ( playoffSeries && playoffSeries.currentRound === numGamesPlayoffSeries.length - 1 ) { disableHomeCourtAdvantage = true; } } } const result = getResult({ gid: game.gid, day: game.day, teams: teamsInput, doPlayByPlay, disableHomeCourtAdvantage, }); results.push(result); } } await cbSaveResults(results, dayOver); }; // Simulates a day of games. If there are no games left, it calls cbNoGames. // Promise is resolved after games are run const cbPlayGames = async () => { await updateStatus(`Playing (${helpers.daysLeft(false, numDays)})`); let schedule = await season.getSchedule(true); // If live game sim, only do that one game, not the whole day let dayOver = true; if (gidOneGame !== undefined) { const lengthBefore = schedule.length; schedule = schedule.filter(game => game.gid === gidOneGame); const lengthAfter = schedule.length; if (lengthBefore - lengthAfter > 0) { dayOver = false; } } if ( schedule.length > 0 && schedule[0].homeTid === -3 && schedule[0].awayTid === -3 ) { await idb.cache.schedule.delete(schedule[0].gid); await phase.newPhase(PHASE.AFTER_TRADE_DEADLINE, conditions); await toUI("deleteGames", [[schedule[0].gid]]); await play(numDays - 1, conditions, false); } else { // This should also call cbNoGames after the playoffs end, because g.get("phase") will have been incremented by season.newSchedulePlayoffsDay after the previous day's games if (schedule.length === 0 && g.get("phase") !== PHASE.PLAYOFFS) { return cbNoGames(); } const tids = new Set<number>(); // Will loop through schedule and simulate all games if (schedule.length === 0 && g.get("phase") === PHASE.PLAYOFFS) { // Sometimes the playoff schedule isn't made the day before, so make it now // This works because there should always be games in the playoffs phase. The next phase will start before reaching this point when the playoffs are over. await season.newSchedulePlayoffsDay(); schedule = await season.getSchedule(true); } for (const matchup of schedule) { tids.add(matchup.homeTid); tids.add(matchup.awayTid); } const teams = await loadTeams(Array.from(tids), conditions); // Play games await cbSimGames(schedule, teams, dayOver); } }; // This simulates a day, including game simulation and any other bookkeeping that needs to be done const cbRunDay = async () => { const userTeamSizeError = await team.checkRosterSizes("user"); if (!userTeamSizeError) { await updatePlayMenu(); if (numDays > 0) { // If we didn't just stop games, let's play // Or, if we are starting games (and already passed the lock), continue even if stopGameSim was just seen const stopGameSim = lock.get("stopGameSim"); if (start || !stopGameSim) { // If start is set, then reset stopGames if (stopGameSim) { await lock.set("stopGameSim", false); } if (g.get("phase") !== PHASE.PLAYOFFS) { await team.checkRosterSizes("other"); } await cbPlayGames(); } else { // Update UI if stopped await cbNoGames(); } } else { // Not sure why we get here sometimes, but we do const playoffsOver = g.get("phase") === PHASE.PLAYOFFS && (await season.newSchedulePlayoffsDay()); await cbNoGames(playoffsOver); } } else { await lock.set("gameSim", false); // Counteract auto-start in lock.canStartGames await updatePlayMenu(); await updateStatus("Idle"); logEvent( { type: "error", text: userTeamSizeError, saveToDb: false, }, conditions, ); } }; // If this is a request to start a new simulation... are we allowed to do // that? If so, set the lock and update the play menu if (start) { const canStartGames = await lock.canStartGames(); if (canStartGames) { await cbRunDay(); } } else { await cbRunDay(); } }; export default play;
the_stack
* For reference see https://github.com/graphql/graphql-js/blob/master/src/language/ast.js */ import type { ObjectTypeDefinitionNode, InputObjectTypeDefinitionNode, EnumTypeDefinitionNode, InterfaceTypeDefinitionNode, ScalarTypeDefinitionNode, UnionTypeDefinitionNode, FieldDefinitionNode, InputValueDefinitionNode, EnumValueDefinitionNode, DirectiveNode, StringValueNode, IntValueNode, FloatValueNode, BooleanValueNode, NullValueNode, ListValueNode, ObjectValueNode, ObjectFieldNode, ArgumentNode, NamedTypeNode, TypeNode, ValueNode, GraphQLInputType, NameNode, } from '../graphql'; import { GraphQLDirective, astFromValue } from '../graphql'; import type { ObjectTypeComposer } from '../ObjectTypeComposer'; import type { InputTypeComposer } from '../InputTypeComposer'; import type { EnumTypeComposer } from '../EnumTypeComposer'; import type { InterfaceTypeComposer, InterfaceTypeComposerThunked } from '../InterfaceTypeComposer'; import type { ScalarTypeComposer } from '../ScalarTypeComposer'; import type { UnionTypeComposer } from '../UnionTypeComposer'; import type { SchemaComposer } from '../SchemaComposer'; import type { AnyTypeComposer } from './typeHelpers'; import type { Directive, DirectiveArgs } from './definitions'; import { ThunkComposer } from '../ThunkComposer'; import { NonNullComposer } from '../NonNullComposer'; import { ListComposer } from '../ListComposer'; import { inspect } from './misc'; import { Kind } from 'graphql'; /** * Get astNode for ObjectTypeComposer. */ export function getObjectTypeDefinitionNode( tc: ObjectTypeComposer<any, any> ): ObjectTypeDefinitionNode { return { kind: Kind.OBJECT_TYPE_DEFINITION, name: getNameNode(tc.getTypeName()), description: getDescriptionNode(tc.getDescription()), directives: getDirectiveNodes(tc.getDirectives(), tc.schemaComposer), interfaces: getInterfaceNodes(tc.getInterfaces()), fields: getFieldDefinitionNodes(tc), }; } /** * Get astNode for InputTypeComposer. */ export function getInputObjectTypeDefinitionNode( tc: InputTypeComposer<any> ): InputObjectTypeDefinitionNode { return { kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, name: getNameNode(tc.getTypeName()), directives: getDirectiveNodes(tc.getDirectives(), tc.schemaComposer), description: getDescriptionNode(tc.getDescription()), fields: getInputValueDefinitionNodes(tc), }; } /** * Get astNode for EnumTypeComposer. */ export function getEnumTypeDefinitionNode(tc: EnumTypeComposer<any>): EnumTypeDefinitionNode { return { kind: Kind.ENUM_TYPE_DEFINITION, name: getNameNode(tc.getTypeName()), description: getDescriptionNode(tc.getDescription()), directives: getDirectiveNodes(tc.getDirectives(), tc.schemaComposer), values: getEnumValueDefinitionNodes(tc) || [], }; } /** * Get astNode for InterfaceTypeComposer. */ export function getInterfaceTypeDefinitionNode( tc: InterfaceTypeComposer<any, any> ): InterfaceTypeDefinitionNode { return { kind: Kind.INTERFACE_TYPE_DEFINITION, name: getNameNode(tc.getTypeName()), description: getDescriptionNode(tc.getDescription()), directives: getDirectiveNodes(tc.getDirectives(), tc.schemaComposer), fields: getFieldDefinitionNodes(tc), }; } /** * Get astNode for ScalarTypeComposer. */ export function getScalarTypeDefinitionNode(tc: ScalarTypeComposer<any>): ScalarTypeDefinitionNode { return { kind: Kind.SCALAR_TYPE_DEFINITION, name: getNameNode(tc.getTypeName()), description: getDescriptionNode(tc.getDescription()), directives: getDirectiveNodes(tc.getDirectives(), tc.schemaComposer), }; } /** * Get astNode for ScalarTypeComposer. */ export function getUnionTypeDefinitionNode( tc: UnionTypeComposer<any, any> ): UnionTypeDefinitionNode { return { kind: Kind.UNION_TYPE_DEFINITION, name: getNameNode(tc.getTypeName()), description: getDescriptionNode(tc.getDescription()), directives: getDirectiveNodes(tc.getDirectives(), tc.schemaComposer), types: tc.getTypeNames().map((value) => ({ kind: Kind.NAMED_TYPE, name: getNameNode(value), })), }; } export function getDescriptionNode(value?: string | null): StringValueNode | undefined { if (!value) return; return { kind: Kind.STRING, value, }; } /** * Maybe this function should be replaced by build-in `astFromValue(value, type)` function from graphql-js */ function toValueNode(value: any): ValueNode { switch (typeof value) { case 'string': // Will be good to add support for enum! // if (argType instanceof GraphQLEnumType) { // return { kind: Kind.ENUM, value }; // } return { kind: Kind.STRING, value } as StringValueNode; case 'number': if (Number.isInteger(value)) return { kind: Kind.INT, value: value.toString() } as IntValueNode; return { kind: Kind.FLOAT, value: value.toString() } as FloatValueNode; case 'boolean': return { kind: Kind.BOOLEAN, value } as BooleanValueNode; case 'object': if (value === null) { return { kind: Kind.NULL } as NullValueNode; } else if (Array.isArray(value)) { return { kind: Kind.LIST, values: value.map((v) => toValueNode(v)), } as ListValueNode; } else { return { kind: Kind.OBJECT, fields: Object.keys(value).map( (k) => ({ kind: Kind.OBJECT_FIELD, name: getNameNode(k), value: toValueNode(value[k]), } as ObjectFieldNode) ), } as ObjectValueNode; } default: // unsupported types // 'bigint' | 'symbol' | 'undefined' | 'function'; // As a fallback return null, should be fixed in future // Maybe better to throw an error. console.log(`Cannot determine astNode in toValueNode() method: ${inspect(value)}`); return { kind: Kind.NULL }; } } function getDirectiveArgumentNodes( data: DirectiveArgs, directive?: GraphQLDirective ): ReadonlyArray<ArgumentNode> | undefined { const keys = Object.keys(data); if (!keys.length) return; const args: Array<ArgumentNode> = []; keys.forEach((k) => { let argumentType: GraphQLInputType | undefined; if (directive) { argumentType = directive.args.find((d) => d.name === k)?.type; } const argNode = { kind: Kind.ARGUMENT, name: getNameNode(k), value: argumentType ? // `astFromValue` supports EnumString astFromValue(data[k], argumentType) || { kind: Kind.NULL } : // `toValueNode` is fallback which supports just primitive types toValueNode(data[k]), } as ArgumentNode; args.push(argNode); }); return args; } export function getDirectiveNodes( values: Directive[], sc: SchemaComposer<any> // Relax type definitions, because in Graphql@16 it became ConstDirectiveNode // was definition ReadonlyArray<DirectiveNode> | undefined ): ReadonlyArray<any> | undefined { if (!values || !values.length) return; return values.map( (v) => ({ kind: Kind.DIRECTIVE, name: getNameNode(v.name), arguments: v.args && getDirectiveArgumentNodes(v.args, sc._getDirective(v.name)), } as DirectiveNode) ); } export function getInterfaceNodes( ifaces: InterfaceTypeComposerThunked<any, any>[] ): ReadonlyArray<NamedTypeNode> { return ifaces .map((iface) => { if (!iface || !iface.getTypeName) return; return { kind: Kind.NAMED_TYPE, name: getNameNode(iface.getTypeName()), } as NamedTypeNode; }) .filter(Boolean) as any; } export function getTypeNode(atc: AnyTypeComposer<any>): TypeNode | undefined { if (atc instanceof ThunkComposer) { return getTypeNode(atc.ofType); } else if (atc instanceof ListComposer) { const subType = getTypeNode(atc.ofType); if (!subType) return; return { kind: Kind.LIST_TYPE, type: subType, }; } else if (atc instanceof NonNullComposer) { const subType = getTypeNode(atc.ofType); if (!subType) return; return { kind: Kind.NON_NULL_TYPE, type: subType as any, }; } else if (atc && atc.getTypeName) { return { kind: Kind.NAMED_TYPE, name: getNameNode(atc.getTypeName()), }; } return undefined; } export function getArgumentsDefinitionNodes( tc: ObjectTypeComposer<any, any> | InterfaceTypeComposer<any, any>, fieldName: string ): ReadonlyArray<InputValueDefinitionNode> | undefined { const argNames = tc.getFieldArgNames(fieldName); if (!argNames.length) return; return argNames .map((argName) => { const ac = tc.getFieldArg(fieldName, argName); const type = getTypeNode(ac.type); if (!type) return; return { kind: Kind.INPUT_VALUE_DEFINITION, name: getNameNode(argName), type, description: getDescriptionNode(ac.description), directives: getDirectiveNodes( tc.getFieldArgDirectives(fieldName, argName), tc.schemaComposer ), defaultValue: (ac.defaultValue !== undefined && astFromValue(ac.defaultValue, tc.getFieldArgType(fieldName, argName))) || undefined, } as InputValueDefinitionNode; }) .filter(Boolean) as any; } export function getFieldDefinitionNodes( tc: ObjectTypeComposer<any, any> | InterfaceTypeComposer<any, any> ): ReadonlyArray<FieldDefinitionNode> | undefined { const fieldNames = tc.getFieldNames(); if (!fieldNames.length) return; return fieldNames .map((fieldName) => { const fc = tc.getField(fieldName); const type = getTypeNode(fc.type); if (!type) return; return { kind: Kind.FIELD_DEFINITION, name: getNameNode(fieldName), type, arguments: getArgumentsDefinitionNodes(tc, fieldName), description: getDescriptionNode(fc.description), directives: getDirectiveNodes(tc.getFieldDirectives(fieldName), tc.schemaComposer), } as FieldDefinitionNode; }) .filter(Boolean) as any; } export function getInputValueDefinitionNodes( tc: InputTypeComposer<any> ): ReadonlyArray<InputValueDefinitionNode> | undefined { const fieldNames = tc.getFieldNames(); if (!fieldNames.length) return; return fieldNames .map((fieldName) => { const fc = tc.getField(fieldName); const type = getTypeNode(fc.type); if (!type) return; return { kind: Kind.INPUT_VALUE_DEFINITION, name: getNameNode(fieldName), type, description: getDescriptionNode(fc.description), directives: getDirectiveNodes(tc.getFieldDirectives(fieldName), tc.schemaComposer), defaultValue: (fc.defaultValue !== undefined && astFromValue(fc.defaultValue, tc.getFieldType(fieldName))) || undefined, } as InputValueDefinitionNode; }) .filter(Boolean) as any; } export function getNameNode(value: string): NameNode { return { kind: Kind.NAME, value }; } export function getEnumValueDefinitionNodes( tc: EnumTypeComposer<any> ): ReadonlyArray<EnumValueDefinitionNode> | undefined { const fieldNames = tc.getFieldNames(); if (!fieldNames.length) return; return fieldNames.map((fieldName) => { const fc = tc.getField(fieldName); return { kind: Kind.ENUM_VALUE_DEFINITION, name: getNameNode(fieldName), description: getDescriptionNode(fc.description), directives: getDirectiveNodes(tc.getFieldDirectives(fieldName), tc.schemaComposer), } as EnumValueDefinitionNode; }); } export function parseValueNode( ast: ValueNode, variables: Record<string, any> = {}, typeName?: string ): unknown { switch (ast.kind) { case Kind.STRING: case Kind.BOOLEAN: return ast.value; case Kind.INT: case Kind.FLOAT: return parseFloat(ast.value); case Kind.OBJECT: const value = Object.create(null); ast.fields.forEach((field) => { value[field.name.value] = parseValueNode(field.value, variables, typeName); }); return value; case Kind.LIST: return ast.values.map((n) => parseValueNode(n, variables, typeName)); case Kind.NULL: return null; case Kind.VARIABLE: return variables ? variables[ast.name.value] : undefined; default: throw new TypeError(`${typeName} cannot represent value: ${inspect(ast)}`); } }
the_stack
import * as THREE from "three"; import { GeoBox } from "../coordinates/GeoBox"; import { GeoCoordinates } from "../coordinates/GeoCoordinates"; import { GeoCoordinatesLike } from "../coordinates/GeoCoordinatesLike"; import { Box3Like, isBox3Like } from "../math/Box3Like"; import { MathUtils } from "../math/MathUtils"; import { isOrientedBox3Like, OrientedBox3Like } from "../math/OrientedBox3Like"; import { Vector3Like } from "../math/Vector3Like"; import { EarthConstants } from "./EarthConstants"; import { Projection, ProjectionType } from "./Projection"; /** * * https://en.wikipedia.org/wiki/Transverse_Mercator_projection * http://mathworld.wolfram.com/MercatorProjection.html * */ class TransverseMercatorProjection extends Projection { /** * Like in regular Mercator projection, there are two points on sphere * with radius about 5 degrees, that is out of projected space. * * * in regular Mercator these points are: * (90, any), (-90, any) * * and in transverse Mercator: * (0, 90), (0, -90) * * So, in transverse we need to compute distnce to poles, and clamp if * radius is exceeded */ static clampGeoPoint(geoPoint: GeoCoordinatesLike, _unitScale: number) { const lat = geoPoint.latitude; const lon = geoPoint.longitude; const r = TransverseMercatorUtils.POLE_RADIUS; const rsq = TransverseMercatorUtils.POLE_RADIUS_SQ; const nearestQuarter = Math.round(lon / 90); const deltaLon = nearestQuarter * 90 - lon; if (nearestQuarter % 2 === 0 || Math.abs(deltaLon) > r) { return geoPoint; } const deltaLat = lat - 0; const distanceToPoleSq = deltaLon * deltaLon + deltaLat * deltaLat; if (distanceToPoleSq < rsq) { const distanceToPole = Math.sqrt(distanceToPoleSq); const scale = (r - distanceToPole) / distanceToPole; // const quarter = ((nearestQuarter % 4) + 4) % 4; // const dir = quarter === 1 ? -1 : quarter === 3 ? 1 : 0; const dir = 1; const offsetLon = deltaLon === 0 && deltaLat === 0 ? r * dir : deltaLon; return new GeoCoordinates(lat + deltaLat * scale, lon + offsetLon * scale); } return geoPoint; } /** @override */ readonly type: ProjectionType = ProjectionType.Planar; private readonly m_phi0: number = 0; private readonly m_lambda0: number = 0; constructor(readonly unitScale: number) { super(unitScale); } /** @override */ getScaleFactor(worldPoint: Vector3Like): number { return Math.cosh((worldPoint.x / this.unitScale - 0.5) * 2 * Math.PI); } /** @override */ worldExtent<WorldBoundingBox extends Box3Like>( minAltitude: number, maxAltitude: number, result?: WorldBoundingBox ): WorldBoundingBox { if (!result) { result = (new THREE.Box3() as Box3Like) as WorldBoundingBox; } result.min.x = 0; result.min.y = 0; result.min.z = minAltitude; result.max.x = this.unitScale; result.max.y = this.unitScale; result.max.z = maxAltitude; return result; } /** @override */ projectPoint<WorldCoordinates extends Vector3Like>( geoPoint: GeoCoordinatesLike, result?: WorldCoordinates ): WorldCoordinates { if (!result) { result = { x: 0, y: 0, z: 0 } as WorldCoordinates; } const clamped = TransverseMercatorProjection.clampGeoPoint(geoPoint, this.unitScale); const normalLon = clamped.longitude / 360 + 0.5; const offset = normalLon === 1 ? 0 : Math.floor(normalLon); const phi = THREE.MathUtils.degToRad(clamped.latitude); const lambda = THREE.MathUtils.degToRad(clamped.longitude - offset * 360) - this.m_lambda0; const B = Math.cos(phi) * Math.sin(lambda); // result.x = 1/2 * Math.log((1 + B) / (1 - B)); result.x = Math.atanh(B); result.y = Math.atan2(Math.tan(phi), Math.cos(lambda)) - this.m_phi0; const outScale = 0.5 / Math.PI; result.x = this.unitScale * (THREE.MathUtils.clamp(result.x * outScale + 0.5, 0, 1) + offset); result.y = this.unitScale * THREE.MathUtils.clamp(result.y * outScale + 0.5, 0, 1); result.z = geoPoint.altitude ?? 0; return result; } /** @override */ unprojectPoint(worldPoint: Vector3Like): GeoCoordinates { const tau = Math.PI * 2; const nx = worldPoint.x / this.unitScale; const ny = worldPoint.y / this.unitScale; const offset = nx === 1 ? 0 : Math.floor(nx); const x = tau * (nx - 0.5 - offset); const y = tau * (ny - 0.5); const z = worldPoint.z || 0; const D = y + this.m_phi0; const phi = Math.asin(Math.sin(D) / Math.cosh(x)); const lambda = this.m_lambda0 + Math.atan2(Math.sinh(x), Math.cos(D)) + offset * tau; const geoPoint = GeoCoordinates.fromRadians(phi, lambda, z); return geoPoint; } /** @override */ projectBox<WorldBoundingBox extends Box3Like | OrientedBox3Like>( geoBox: GeoBox, result?: WorldBoundingBox ): WorldBoundingBox { const { north, south, east, west } = geoBox; const pointsToCheck = [ geoBox.center, geoBox.northEast, geoBox.southWest, new GeoCoordinates(south, east), new GeoCoordinates(north, west) ]; const E = TransverseMercatorUtils.POLE_EDGE_DEG; const containsWestCut = west < -90 && east > -90; const containsEastCut = west < 90 && east > 90; const containsCenterX = west < 0 && east > 0; const containsCenterY = west < E && east > -E && north > 0 && south < 0; if (containsWestCut) { pointsToCheck.push(new GeoCoordinates(north, -90)); pointsToCheck.push(new GeoCoordinates(south, -90)); } if (containsEastCut) { pointsToCheck.push(new GeoCoordinates(north, 90)); pointsToCheck.push(new GeoCoordinates(south, 90)); } if (containsCenterX) { pointsToCheck.push(new GeoCoordinates(north, 0)); pointsToCheck.push(new GeoCoordinates(south, 0)); } if (containsCenterY) { pointsToCheck.push(new GeoCoordinates(0, west)); pointsToCheck.push(new GeoCoordinates(0, east)); } TransverseMercatorUtils.alignLatitude(pointsToCheck, pointsToCheck[0]); const projected = pointsToCheck.map(p => this.projectPoint(p)); const vx = projected.map(p => p.x); const vy = projected.map(p => p.y); const vz = projected.map(p => p.z); const minX = Math.min(...vx); const minY = Math.min(...vy); const minZ = Math.min(...vz); const maxX = Math.max(...vx); const maxY = Math.max(...vy); const maxZ = Math.max(...vz); if (!result) { result = (new THREE.Box3() as Box3Like) as WorldBoundingBox; } if (isBox3Like(result)) { result.min.x = minX; result.min.y = minY; result.min.z = minZ; result.max.x = maxX; result.max.y = maxY; result.max.z = maxZ; } else if (isOrientedBox3Like(result)) { MathUtils.newVector3(1, 0, 0, result.xAxis); MathUtils.newVector3(0, 1, 0, result.yAxis); MathUtils.newVector3(0, 0, 1, result.zAxis); result.position.x = (minX + maxX) / 2; result.position.y = (minY + maxY) / 2; result.position.z = (minZ + maxZ) / 2; result.extents.x = (maxX - minX) / 2; result.extents.y = (maxY - minY) / 2; result.extents.z = (maxZ - minZ) / 2; } else { throw new Error("invalid bounding box"); } return result; } /** * There are 8 sub-regions on entire projection space * where both longitude and latitude preserve direction. * If bounding box hits more than one region, it should be splitted * into sub-boxes by regions, (un)projected and then united again. * * * directions in form [latitude / longitude]: * 1 ┌─────────|─────────┐ * │ dr / dl | dl / ul │ * 0.75 ----------|---------- * │ ur / dr | ul / ur │ * 0.5 ----------|---------- * │ ul / ur | ur / dr │ * 0.25 ----------|---------- * │ dl / ul | dr / dl │ * └─────────|─────────┘ * 0 0.5 1 * @override */ unprojectBox(worldBox: Box3Like): GeoBox { const s = this.unitScale; const min = worldBox.min; const max = worldBox.max; const pointsToCheck = [ { x: (min.x + max.x) / 2, y: (min.y + max.y) / 2, z: 0 }, min, max, { x: min.x, y: max.y, z: 0 }, { x: max.x, y: min.y, z: 0 } ]; const center = 0.5 * s; const lowerQ = 0.25 * s; const upperQ = 0.75 * s; const containsCenterX = min.x < center && max.x > center; const containsCenterY = min.y < center && max.y > center; const containsLowerQY = min.y < lowerQ && max.y > lowerQ; const containsUpperQY = min.y < upperQ && max.y > upperQ; if (containsCenterY) { pointsToCheck.push({ x: min.x, y: center, z: 0 }); pointsToCheck.push({ x: max.x, y: center, z: 0 }); if (containsCenterX) { pointsToCheck.push({ x: center, y: center, z: 0 }); } } if (containsLowerQY) { pointsToCheck.push({ x: min.x, y: lowerQ, z: 0 }); pointsToCheck.push({ x: max.x, y: lowerQ, z: 0 }); if (containsCenterX) { pointsToCheck.push({ x: center, y: lowerQ, z: 0 }); } } if (containsUpperQY) { pointsToCheck.push({ x: min.x, y: upperQ, z: 0 }); pointsToCheck.push({ x: max.x, y: upperQ, z: 0 }); if (containsCenterX) { pointsToCheck.push({ x: center, y: upperQ, z: 0 }); } } const geoPoints = pointsToCheck.map(p => this.unprojectPoint(p)); TransverseMercatorUtils.alignLongitude(geoPoints, geoPoints[0]); const latitudes = geoPoints.map(g => g.latitude); const longitudes = geoPoints.filter(g => Math.abs(g.latitude) < 90).map(g => g.longitude); const altitudes = geoPoints.map(g => g.altitude ?? 0); const minGeo = new GeoCoordinates( Math.min(...latitudes), Math.min(...longitudes), Math.min(...altitudes) ); const maxGeo = new GeoCoordinates( Math.max(...latitudes), Math.max(...longitudes), Math.max(...altitudes) ); const geoBox = GeoBox.fromCoordinates(minGeo, maxGeo); return geoBox; } /** @override */ unprojectAltitude(worldPoint: Vector3Like): number { return worldPoint.z; } /** @override */ groundDistance(worldPoint: Vector3Like): number { return worldPoint.z; } /** @override */ scalePointToSurface(worldPoint: Vector3Like): Vector3Like { worldPoint.z = 0; return worldPoint; } /** @override */ surfaceNormal(_worldPoint: Vector3Like, normal?: Vector3Like) { if (normal === undefined) { normal = { x: 0, y: 0, z: -1 }; } else { normal.x = 0; normal.y = 0; normal.z = -1; } return normal; } } export class TransverseMercatorUtils { static POLE_EDGE: number = 1.4844222297453323; static POLE_EDGE_DEG: number = THREE.MathUtils.radToDeg(TransverseMercatorUtils.POLE_EDGE); static POLE_RADIUS: number = 90 - TransverseMercatorUtils.POLE_EDGE_DEG; static POLE_RADIUS_SQ: number = Math.pow(TransverseMercatorUtils.POLE_RADIUS, 2); /** * There are two regions on projected space that have same geo coordinates, * it's the entire lines { x: [0..1], y: 0 } and { x: [0..1], y: 1 } * they both have geo coordinates of (0, [-90..+90]) * and should be aligned somehow to fall into first or second region * to make proper bounding boxes, tile bounds, etc. */ static alignLatitude(points: GeoCoordinatesLike[], referencePoint: GeoCoordinatesLike): void { const EPSILON = 1e-9; for (const point of points) { if (point.latitude === 0) { point.latitude = referencePoint.latitude * EPSILON; } } } /** * There are two regions on projected plane, * { x: 0.5, y: [0..0.25] } and { x: 0.5, y: [0.75..1] } * that represent longitude edge where -180 and +180 met. * Points falling in this regions should be aligned to get proper boxes etc. */ static alignLongitude(points: GeoCoordinatesLike[], referencePoint: GeoCoordinatesLike): void { const bad = referencePoint.longitude < 0 ? 180 : -180; const good = referencePoint.longitude < 0 ? -180 : 180; for (const point of points) { if (point.longitude === bad) { point.longitude = good; } } } } /** * Transverse Mercator {@link Projection} used to convert geo coordinates to world coordinates * and vice versa. */ export const transverseMercatorProjection: Projection = new TransverseMercatorProjection( EarthConstants.EQUATORIAL_CIRCUMFERENCE );
the_stack
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { of, Observable, MonoTypeOperatorFunction, from as fromPromise, iif, throwError } from 'rxjs'; import { catchError, retryWhen, flatMap, timeout, delay as delayOperator, debounceTime, concatMap } from 'rxjs/operators'; import { Buffer } from 'buffer'; import { blake2b } from 'blakejs'; import { sign as naclSign } from 'tweetnacl'; import * as Bs58check from 'bs58check'; import * as bip39 from 'bip39'; import Big from 'big.js'; import { localForger } from '@taquito/local-forging'; import { CONSTANTS } from '../../../environments/environment'; import { ErrorHandlingPipe } from '../../pipes/error-handling.pipe'; import * as elliptic from 'elliptic'; import { instantiateSecp256k1, hexToBin, binToHex } from '@bitauth/libauth'; import { TokenService } from '../token/token.service'; import { isEqual } from 'lodash'; const httpOptions = { headers: { 'Content-Type': 'application/json' } }; export interface KeyPair { sk: string | null; pk: string | null; pkh: string; } @Injectable() export class OperationService { nodeURL = CONSTANTS.NODE_URL; prefix = { tz1: new Uint8Array([6, 161, 159]), tz2: new Uint8Array([6, 161, 161]), tz3: new Uint8Array([6, 161, 164]), edpk: new Uint8Array([13, 15, 37, 217]), sppk: new Uint8Array([3, 254, 226, 86]), edsk: new Uint8Array([43, 246, 78, 7]), spsk: new Uint8Array([17, 162, 224, 201]), edsig: new Uint8Array([9, 245, 205, 134, 18]), spsig: new Uint8Array([13, 115, 101, 19, 63]), sig: new Uint8Array([4, 130, 43]), o: new Uint8Array([5, 116]), B: new Uint8Array([1, 52]), TZ: new Uint8Array([3, 99, 29]), KT: new Uint8Array([2, 90, 121]) }; microTez = new Big(1000000); feeHardCap = 10; //tez constructor( private http: HttpClient, private errorHandlingPipe: ErrorHandlingPipe, private tokenService: TokenService ) { } /* Returns an observable for the activation of an ICO identity */ activate(pkh: string, secret: string): Observable<any> { return this.getHeader() .pipe(flatMap((header: any) => { const fop: any = { branch: header.hash, contents: [{ kind: 'activate_account', pkh: pkh, secret: secret }] }; return this.postRpc('chains/main/blocks/head/helpers/forge/operations', fop) .pipe(flatMap((opbytes: any) => { const sopbytes: string = opbytes + Array(129).join('0'); fop.protocol = header.protocol; fop.signature = 'edsigtXomBKi5CTRf5cjATJWSyaRvhfYNHqSUGrn4SdbYRcGwQrUGjzEfQDTuqHhuA8b2d8NarZjz8TRf65WkpQmo423BtomS8Q'; return this.postRpc('chains/main/blocks/head/helpers/preapply/operations', [fop]) .pipe(flatMap((preApplyResult: any) => { console.log(JSON.stringify(preApplyResult)); return this.postRpc('injection/operation', JSON.stringify(sopbytes)).pipe(flatMap((final: any) => { return this.opCheck(final); })); })); })); })).pipe(catchError(err => this.errHandler(err))); } opCheck(final: any, newPkh: string = null): Observable<any> { if (typeof (final) === 'string' && final.length === 51) { return of( { success: true, payload: { opHash: final, newPkh: newPkh } }); } else { return of( { success: false, payload: { opHash: null, msg: final } }); } } /* Returns an observable for the origination of new accounts. */ originate(origination: any, fee: number = 0, keys: KeyPair): Observable<any> { console.log(fee, origination); return this.getHeader() .pipe(flatMap((header: any) => { return this.getRpc(`chains/main/blocks/head/context/contracts/${keys.pkh}/counter`) .pipe(flatMap((actions: number) => { return this.getRpc(`chains/main/blocks/head/context/contracts/${keys.pkh}/manager_key`) .pipe(flatMap((manager: any) => { if (fee >= this.feeHardCap) { throw new Error('TooHighFee'); } const counter: number = Number(actions); const fop = this.createOriginationObject(header.hash, counter, manager, origination, fee, keys.pk, keys.pkh); return this.operation(fop, header, keys, true); })); })); })).pipe(catchError(err => this.errHandler(err))); } createOriginationObject(hash: string, counter: number, manager: string, origination: any, fee: number, pk: string, pkh: string): any { const fop: any = { branch: hash, contents: [] }; const gas_limit = origination.gasLimit.toString(); const storage_limit = origination.storageLimit.toString(); if (manager === null) { // Reveal fop.contents.push({ kind: 'reveal', source: pkh, fee: '0', counter: (++counter).toString(), gas_limit: '1000', storage_limit: '0', public_key: pk }); } fop.contents.push({ kind: 'origination', source: pkh, fee: this.microTez.times(fee).toString(), counter: (++counter).toString(), gas_limit, storage_limit, balance: this.microTez.times(origination.balance).toString(), script: origination.script }); return fop; } /* Returns an observable for the transaction of tez. */ transfer(from: string, transactions: any, fee: number, keys: KeyPair, tokenTransfer: string = ''): Observable<any> { return this.getHeader() .pipe(flatMap((header: any) => { return this.getRpc(`chains/main/blocks/head/context/contracts/${keys.pkh}/counter`) .pipe(flatMap((actions: any) => { return this.getRpc(`chains/main/blocks/head/context/contracts/${keys.pkh}/manager_key`) .pipe(flatMap((manager: any) => { if (fee >= this.feeHardCap) { throw new Error('TooHighFee'); } const counter: number = Number(actions); const fop = this.createTransactionObject(header.hash, counter, manager, transactions, keys.pkh, keys.pk, from, fee, tokenTransfer); return this.operation(fop, header, keys); })); })); })).pipe(catchError(err => this.errHandler(err))); } createTransactionObject(hash: string, counter: number, manager: string, transactions: any, pkh: string, pk: string, from: string, fee: number, tokenTransfer: string): any { const fop: any = { branch: hash, contents: [] }; if (manager === null) { // Reveal fop.contents.push({ kind: 'reveal', source: pkh, fee: '0', counter: (++counter).toString(), gas_limit: '1000', storage_limit: '0', public_key: pk }); } for (let i = 0; i < transactions.length; i++) { const currentFee = i === transactions.length - 1 ? this.microTez.times(fee).toString() : '0'; const gasLimit = transactions[i].gasLimit.toString(); const storageLimit = transactions[i].storageLimit.toString(); if (tokenTransfer) { console.log('Invoke contract: ' + tokenTransfer); let invocation: any; const { kind, decimals, contractAddress, id } = this.tokenService.getAsset(tokenTransfer); const txAmount = Big(10 ** decimals).times(transactions[i].amount); if (!txAmount.mod(1).eq(0)) { throw new Error(`the amount ${transactions[i].amount} is not within ${decimals} decimals`); } if (kind === 'FA1.2') { invocation = this.getFA12Transaction(pkh, transactions[i].destination, txAmount.toFixed(0)); } else if (kind === 'FA2') { invocation = this.getFA2Transaction(pkh, transactions[i].destination, txAmount.toFixed(0), id); } else { throw new Error('Unrecognized token kind'); } fop.contents.push({ kind: 'transaction', source: pkh, fee: currentFee, counter: (++counter).toString(), gas_limit: gasLimit, storage_limit: storageLimit, amount: '0', destination: contractAddress, parameters: invocation }); } else if (from.slice(0, 2) === 'tz') { const transactionOp: any = { kind: 'transaction', source: from, fee: currentFee, counter: (++counter).toString(), gas_limit: gasLimit, storage_limit: storageLimit, amount: this.microTez.times(transactions[i].amount).toString(), destination: transactions[i].destination, }; if (transactions[i].parameters) { transactionOp.parameters = transactions[i].parameters; } fop.contents.push(transactionOp); } else if (from.slice(0, 2) === 'KT') { if (transactions[i].destination.slice(0, 2) === 'tz') { const managerTransaction = this.getContractPkhTransaction(transactions[i].destination, this.microTez.times(transactions[i].amount).toString()); fop.contents.push({ kind: 'transaction', source: pkh, fee: currentFee, counter: (++counter).toString(), gas_limit: gasLimit, storage_limit: storageLimit, amount: '0', destination: from, parameters: managerTransaction }); } else if (transactions[i].destination.slice(0, 2) === 'KT') { const managerTransaction = this.getContractKtTransaction(transactions[i].destination, this.microTez.times(transactions[i].amount).toString()); fop.contents.push({ kind: 'transaction', source: pkh, fee: currentFee, counter: (++counter).toString(), gas_limit: gasLimit, storage_limit: storageLimit, amount: '0', destination: from, parameters: managerTransaction }); } } } return fop; } /* Returns an observable for the delegation of baking rights. */ delegate(from: string, to: string, fee: number = 0, keys: KeyPair): Observable<any> { return this.getHeader() .pipe(flatMap((header: any) => { return this.getRpc(`chains/main/blocks/head/context/contracts/${keys.pkh}/counter`) .pipe(flatMap((actions: any) => { return this.getRpc(`chains/main/blocks/head/context/contracts/${keys.pkh}/manager_key`) .pipe(flatMap((manager: any) => { if (fee >= this.feeHardCap) { throw new Error('TooHighFee'); } let counter: number = Number(actions); let delegationOp: any; if (from.slice(0, 2) === 'tz') { delegationOp = { kind: 'delegation', source: from, fee: this.microTez.times(fee).toString(), counter: (++counter).toString(), gas_limit: '1000', storage_limit: '0', }; if (to !== '') { delegationOp.delegate = to; } } else if (from.slice(0, 2) === 'KT') { delegationOp = { kind: 'transaction', source: keys.pkh, fee: this.microTez.times(fee).toString(), counter: (++counter).toString(), gas_limit: '4380', storage_limit: '0', amount: '0', destination: from, parameters: (to !== '') ? this.getContractDelegation(to) : this.getContractUnDelegation() }; } const fop: any = { branch: header.hash, contents: [ delegationOp ] }; if (manager === null) { fop.contents[1] = fop.contents[0]; fop.contents[0] = { kind: 'reveal', source: keys.pkh, fee: '0', counter: (counter).toString(), gas_limit: '1000', storage_limit: '0', public_key: keys.pk }; fop.contents[1].counter = (Number(fop.contents[1].counter) + 1).toString(); } return this.operation(fop, header, keys); })); })); })).pipe(catchError(err => this.errHandler(err))); } /* Help function for operations */ operation(fop: any, header: any, keys: KeyPair, origination: boolean = false): Observable<any> { console.log('fop to send: ' + JSON.stringify(fop)); return this.postRpc('chains/main/blocks/head/helpers/forge/operations', fop) .pipe(flatMap((opbytes: any) => { return this.localForge(fop) .pipe(flatMap((localOpbytes: string) => { if (opbytes !== localOpbytes) { throw new Error('ValidationError'); } if (!keys.sk) { fop.signature = 'edsigtXomBKi5CTRf5cjATJWSyaRvhfYNHqSUGrn4SdbYRcGwQrUGjzEfQDTuqHhuA8b2d8NarZjz8TRf65WkpQmo423BtomS8Q'; return this.postRpc('chains/main/blocks/head/helpers/scripts/run_operation', { operation: fop, chain_id: header.chain_id }) .pipe(flatMap((applied: any) => { console.log('applied: ' + JSON.stringify(applied)); this.checkApplied([applied]); return of( { success: true, payload: { unsignedOperation: opbytes } }); })); } else { fop.protocol = header.protocol; const signed = this.sign('03' + opbytes, keys.sk); const sopbytes = signed.sbytes; fop.signature = signed.edsig; return this.postRpc('chains/main/blocks/head/helpers/preapply/operations', [fop]) .pipe(flatMap((applied: any) => { console.log('applied: ' + JSON.stringify(applied)); this.checkApplied(applied); console.log('sop: ' + sopbytes); return this.postRpc('injection/operation', JSON.stringify(sopbytes)) .pipe( timeout(30000) ) .pipe(flatMap((final: any) => { let newPkh = null; if (origination) { newPkh = applied[0].contents[fop.contents.length - 1]. metadata.operation_result.originated_contracts[0]; } return this.opCheck(final, newPkh); })); })); } })); })); } /* Broadcast a signed operation to the network */ broadcast(sopbytes: string): Observable<any> { console.log('Broadcast...'); const opbytes = sopbytes.slice(0, sopbytes.length - 128); const edsig = this.sig2edsig(sopbytes.slice(sopbytes.length - 128)); return fromPromise(localForger.parse(opbytes)).pipe(flatMap((fop: any) => { fop.signature = edsig; return this.getHeader().pipe(flatMap((header: any) => { fop.protocol = header.protocol; return this.postRpc('chains/main/blocks/head/helpers/preapply/operations', [fop]) .pipe(flatMap((parsed: any) => { let newPkh = null; for (let i = 0; i < parsed[0].contents.length; i++) { if (parsed[0].contents[i].kind === 'origination') { newPkh = parsed[0].contents[i].metadata.operation_result.originated_contracts[0]; } } return this.postRpc('injection/operation', JSON.stringify(sopbytes)) .pipe(flatMap((final: any) => { return this.opCheck(final, newPkh); })); })); })); })).pipe(catchError(err => this.errHandler(err))); } torusKeyLookup(tz2address: string): Observable<any> { // Make it into Promise // Zero padding if (tz2address.length !== 36 || tz2address.slice(0, 3) !== 'tz2') { throw new Error('InvalidTorusAddress'); } return this.getRpc(`chains/main/blocks/head/context/contracts/${tz2address}/manager_key`) .pipe(flatMap((manager: any) => { if (manager === null) { return of({ noReveal: true }); } else { return fromPromise(this.decompress(manager)).pipe(flatMap((pk: any) => { const torusReq = { jsonrpc: '2.0', method: 'KeyLookupRequest', id: 10, params: { pub_key_X: pk.X, pub_key_Y: pk.Y } }; const url = CONSTANTS.NETWORK === 'mainnet' ? 'https://torus-19.torusnode.com/jrpc' : 'https://teal-15-1.torusnode.com/jrpc'; return this.http.post(url, JSON.stringify(torusReq), httpOptions) .pipe(flatMap((ans: any) => { try { if (ans.result.PublicKey.X === pk.X && ans.result.PublicKey.Y === pk.Y) { return of(ans); } else { return of(null); } } catch { return of(null); } })); })); } })); } checkApplied(applied: any) { let failed = false; for (let i = 0; i < applied[0].contents.length; i++) { if (applied[0].contents[i].metadata.operation_result.status !== 'applied') { failed = true; if (applied[0].contents[i].metadata.operation_result.errors) { console.log('Error in operation_result'); throw applied[0].contents[i].metadata.operation_result.errors[ applied[0].contents[i].metadata.operation_result.errors.length - 1 ]; } else if (applied[0].contents[i].metadata.internal_operation_results && applied[0].contents[i].metadata.internal_operation_results[0].result.errors) { console.log('Error in internal_operation_results'); throw applied[0].contents[i].metadata.internal_operation_results[0].result.errors[ applied[0].contents[i].metadata.internal_operation_results[0].result.errors.length - 1 ]; } } } if (failed) { throw new Error('Uncaught error in preapply'); } } errHandler(error: any): Observable<any> { if (error.error && typeof error.error === 'string') { // parsing errors error = error.error; const lines = error.split('\n').map((line: string) => { return line.trim(); }); if (lines?.length) { for (const i in lines) { if (lines[i].startsWith('At /') && !lines[i].startsWith('At /kind')) { const n = Number(i) + 1; if (lines[n]) { error = `${lines[i]} ${lines[n]}`; } } } } } if (error.error && error.error[0]) { error = error.error[0]; } if (error.message) { error = this.errorHandlingPipe.transform(error.message); } else if (error.id) { if (error.with) { error = this.errorHandlingPipe.transform(error.id, error.with); } else if (error.id === 'failure' && error.msg) { error = this.errorHandlingPipe.transform(error.msg); } else { error = this.errorHandlingPipe.transform(error.id); } } else if (error.statusText) { error = error.statusText; } else if (typeof error === 'string') { error = this.errorHandlingPipe.transform(error); } else { console.warn('Error not categorized', error); error = 'Unrecogized error'; } return of( { success: false, payload: { msg: error } } ); } // Local forge with Taquito localForge(operation: any): Observable<string> { return fromPromise(localForger.forge(operation)).pipe(flatMap((localForgedBytes: string) => { return of(localForgedBytes); })); } getHeader(): Observable<any> { return this.getRpc(`chains/main/blocks/head~3/header`); } getBalance(pkh: string): Observable<any> { return this.getRpc(`chains/main/blocks/head/context/contracts/${pkh}/balance`) .pipe(flatMap((balance: any) => { return of( { success: true, payload: { balance: balance } } ); })).pipe(catchError(err => this.errHandler(err))); } getDelegate(pkh: string): Observable<any> { return this.getRpc(`chains/main/blocks/head/context/contracts/${pkh}`) .pipe(flatMap((contract: any) => { let delegate = ''; if (contract.delegate) { delegate = contract.delegate; } return of( { success: true, payload: { delegate: delegate } } ); })).pipe(catchError(err => this.errHandler(err))); } getVotingRights(): Observable<any> { return this.getRpc(`chains/main/blocks/head/votes/listings`) .pipe(flatMap((listings: any) => { return of( { success: true, payload: listings } ); })).pipe(catchError(err => this.errHandler(err))); } isRevealed(pkh: string): Observable<boolean> { return this.getRpc(`chains/main/blocks/head/context/contracts/${pkh}/manager_key`) .pipe(flatMap((manager: any) => { if (manager === null) { return of(false); } else { return of(true); } } )).pipe(catchError(err => { return of(true); })); // conservative action } getManager(pkh: string): Observable<string> { return this.getRpc(`chains/main/blocks/head/context/contracts/${pkh}/manager_key`) .pipe(flatMap((pk: string) => { return of(pk ?? ''); })); } getAccount(pkh: string): Observable<any> { return this.getRpc(`chains/main/blocks/head/context/contracts/${pkh}`) .pipe(flatMap((contract: any) => { let delegate = ''; if (contract.delegate) { delegate = contract.delegate; } return of( { success: true, payload: { balance: contract.balance, manager: contract.manager, delegate: delegate, counter: contract.counter } } ); })).pipe(catchError(err => this.errHandler(err))); } getVerifiedOpBytes(operationLevel, operationHash, pkh, pk): Observable<string> { return this.getRpc(`chains/main/blocks/${operationLevel}/operation_hashes`) .pipe(flatMap((opHashes: any) => { const opIndex = opHashes[3].findIndex(a => a === operationHash); return this.getRpc(`chains/main/blocks/${operationLevel}/operations`) .pipe(flatMap((op: any) => { let ans = ''; op = op[3][opIndex]; const sig = op.signature; delete op.chain_id; delete op.signature; delete op.hash; delete op.protocol; for (let i = 0; i < op.contents.length; i++) { delete op.contents[i].metadata; if (op.contents[i].managerPubkey) { // Fix for mainnet op.contents[i].manager_pubkey = op.contents[i].managerPubkey; delete op.contents[i].managerPubkey; } } return this.postRpc('chains/main/blocks/head/helpers/forge/operations', op) .pipe(flatMap((opBytes: any) => { if (this.pk2pkh(pk) === pkh) { if (this.verify(opBytes, sig, pk)) { ans = opBytes + this.buf2hex(this.b58cdecode(sig, this.prefix.sig)); } else { throw new Error('InvalidSignature'); } } else { throw new Error('InvalidPublicKey'); } return of(ans); })); })); })); } getConstants(): Observable<any> { return this.getRpc(`chains/main/blocks/head/context/constants`); } seed2keyPair(seed: Buffer): KeyPair { if (!seed) { throw new Error('NullSeed'); } const keyPair = naclSign.keyPair.fromSeed(seed); return { sk: this.b58cencode(keyPair.secretKey, this.prefix.edsk), pk: this.b58cencode(keyPair.publicKey, this.prefix.edpk), pkh: this.b58cencode(blake2b(keyPair.publicKey, null, 20), this.prefix.tz1) }; } mnemonic2seed(mnemonic: string, passphrase: string = '') { if (!this.validMnemonic(mnemonic)) { throw new Error('InvalidMnemonic'); } return (bip39.mnemonicToSeedSync(mnemonic, passphrase)).slice(0, 32); } mnemonic2entropy(mnemonic: string, passphrase: string = '') { if (!this.validMnemonic(mnemonic)) { throw new Error('InvalidMnemonic'); } return bip39.mnemonicToEntropy(mnemonic); } validMnemonic(mnemonic: string) { return bip39.validateMnemonic(mnemonic); } validAddress(address: string) { try { this.b58cdecode(address, this.prefix.tz1); return true; } catch (e) { return false; } } pk2pkh(pk: string): string { if (pk.length === 54 && pk.slice(0, 4) === 'edpk') { const pkDecoded = this.b58cdecode(pk, this.prefix.edpk); return this.b58cencode(blake2b(pkDecoded, null, 20), this.prefix.tz1); } else if (pk.length === 55 && pk.slice(0, 4) === 'sppk') { const pkDecoded = this.b58cdecode(pk, this.prefix.edpk); return this.b58cencode(blake2b(pkDecoded, null, 20), this.prefix.tz2); } throw new Error('Invalid public key'); } spPrivKeyToKeyPair(secretKey: string) { let sk; if (secretKey.match(/^[0-9a-f]{64}$/g)) { sk = this.b58cencode(this.hex2buf(secretKey), this.prefix.spsk); } else if (secretKey.match(/^spsk[1-9a-km-zA-HJ-NP-Z]{50}$/g)) { sk = secretKey; } else { throw new Error('Invalid private key'); } const keyPair = (new elliptic.ec('secp256k1')).keyFromPrivate( new Uint8Array(this.b58cdecode(sk, this.prefix.spsk)) ); const yArray = keyPair.getPublic().getY().toArray(); const prefixVal = yArray[yArray.length - 1] % 2 ? 3 : 2; // Y odd / even const pad = new Array(32).fill(0); // Zero-padding const publicKey = new Uint8Array( [prefixVal].concat(pad.concat(keyPair.getPublic().getX().toArray()).slice(-32) )); const pk = this.b58cencode(publicKey, this.prefix.sppk); if (yArray.length < 32 && prefixVal === 3 && this.isInvertedPk(pk)) { return this.spPrivKeyToKeyPair(this.invertSpsk(sk)); } const pkh = this.pk2pkh(pk); return { sk, pk, pkh }; } isInvertedPk(pk: string): boolean { /* Detect keys with flipped sign and correct them. */ const invertedPks = [ 'sppk7cqh7BbgUMFh4yh95mUwEeg5aBPG1MBK1YHN7b9geyygrUMZByr', // test variable 'sppk7bMTva1MwF7cXjrcfoj6XVfcYgjrVaR9JKP3JxvPB121Ji5ftHT', 'sppk7bLtXf9CAVZh5jjDACezPnuwHf9CgVoAneNXQFgHknNtCyE5k8A' ]; return invertedPks.includes(pk); } invertSpsk(sk: string) { const x = new Uint8Array([...(new Uint8Array(32).fill(0)), ...this.b58cdecode(sk, this.prefix.spsk)]).slice(-32); const p = this.hex2buf('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141'.toLowerCase()); let inv = []; // p - x let remainder = 0; for (let i = 31; i >= 0; i--) { let sub = p[i] - x[i] - remainder; if (sub < 0) { sub += 256; remainder = 1; } else { remainder = 0; } inv.push(sub); } if (remainder) { throw new Error('Invalid X'); } inv = inv.reverse(); return this.buf2hex(inv); } spPointsToPkh(pubX: string, pubY: string): string { const key = (new elliptic.ec('secp256k1')).keyFromPublic({ x: pubX, y: pubY }); const yArray = key.getPublic().getY().toArray(); const prefixVal = yArray[yArray.length - 1] % 2 ? 3 : 2; const pad = new Array(32).fill(0); let publicKey = new Uint8Array( [prefixVal].concat(pad.concat(key.getPublic().getX().toArray()).slice(-32) )); let pk = this.b58cencode(publicKey, this.prefix.sppk); if (yArray.length < 32 && prefixVal === 3 && this.isInvertedPk(pk)) { publicKey = new Uint8Array( [2].concat(pad.concat(key.getPublic().getX().toArray()).slice(-32) )); pk = this.b58cencode(publicKey, this.prefix.sppk); } const pkh = this.pk2pkh(pk); return pkh; } async decompress(pk: string): Promise<any> { const decodedPk = this.b58cdecode(pk, this.prefix.sppk); const hexPk = this.buf2hex(decodedPk); const secp256k1 = await instantiateSecp256k1(); const compressed = hexToBin(hexPk); const uncompressed = secp256k1.uncompressPublicKey(compressed); const xy = binToHex(uncompressed).slice(2); return { X: xy.slice(0, 64), Y: xy.slice(64, 128) }; } hex2pk(hex: string): string { return this.b58cencode(this.hex2buf(hex.slice(2, 66)), this.prefix.edpk); } hex2buf(hex) { return new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) { return parseInt(h, 16); })); } buf2hex(buffer) { const byteArray = new Uint8Array(buffer), hexParts = []; for (let i = 0; i < byteArray.length; i++) { const hex = byteArray[i].toString(16); const paddedHex = ('00' + hex).slice(-2); hexParts.push(paddedHex); } return hexParts.join(''); } b58cencode(payload: any, prefixx?: Uint8Array) { const n = new Uint8Array(prefixx.length + payload.length); n.set(prefixx); n.set(payload, prefixx.length); return Bs58check.encode(Buffer.from(this.buf2hex(n), 'hex')); } b58cdecode(enc, prefixx) { let n = Bs58check.decode(enc); n = n.slice(prefixx.length); return n; } ledgerPreHash(opbytes: string): string { return this.buf2hex(blake2b(this.hex2buf(opbytes), null, 32)); } sign(bytes: string, sk: string): any { if (!['03', '05'].includes(bytes.slice(0, 2))) { throw new Error('Invalid prefix'); } if (sk.slice(0, 4) === 'spsk') { const hash = blake2b(this.hex2buf(bytes), null, 32); bytes = bytes.slice(2); const key = (new elliptic.ec('secp256k1')).keyFromPrivate(new Uint8Array(this.b58cdecode(sk, this.prefix.spsk))); let sig = key.sign(hash, { canonical: true }); const pad = new Array(32).fill(0); const r = pad.concat(sig.r.toArray()).slice(-32); const s = pad.concat(sig.s.toArray()).slice(-32); sig = new Uint8Array(r.concat(s)); const spsig = this.b58cencode(sig, this.prefix.spsig); const sbytes = bytes + this.buf2hex(sig); return { bytes: bytes, sig: sig, edsig: spsig, sbytes: sbytes, }; } else { const hash = blake2b(this.hex2buf(bytes), null, 32); bytes = bytes.slice(2); const sig = naclSign.detached(hash, this.b58cdecode(sk, this.prefix.edsk)); const edsig = this.b58cencode(sig, this.prefix.edsig); const sbytes = bytes + this.buf2hex(sig); return { bytes: bytes, sig: sig, edsig: edsig, sbytes: sbytes, }; } } hexsigToEdsig(hex: string): string { return this.b58cencode(this.hex2buf(hex), this.prefix.edsig); } verify(bytes: string, sig: string, pk: string): Boolean { console.log('bytes', bytes); const hash = blake2b(this.hex2buf(bytes), null, 32); const signature = this.b58cdecode(sig, this.prefix.edsig); const publicKey = this.b58cdecode(pk, this.prefix.edpk); return naclSign.detached.verify(signature, hash, publicKey); } sig2edsig(sig: string): any { return this.b58cencode(this.hex2buf(sig), this.prefix.edsig); } decodeString(bytes: string): string { return Buffer.from(this.hex2buf(bytes)).toString('utf-8'); } zarithDecode(hex: string): any { let count = 0; let value = 0; while (1) { const byte = Number('0x' + hex.slice(0 + count * 2, 2 + count * 2)); value += ((byte & 127) * (128 ** count)); count++; if ((byte & 128) !== 128) { break; } } return { value: value, count: count }; } zarithDecodeInt(hex: string): any { let count = 0; let value = Big(0); while (1) { const byte = Number('0x' + hex.slice(0 + count * 2, 2 + count * 2)); if (count === 0) { value = Big(((byte & 63) * (128 ** count))).add(value); } else { value = Big(((byte & 127) * 2) >> 1).times(64 * 128 ** (count - 1)).add(value); } count++; if ((byte & 128) !== 128) { break; } } return { value: value, count: count }; } getContractDelegation(pkh: string) { return { entrypoint: 'do', value: [{ prim: 'DROP' }, { prim: 'NIL', args: [{ prim: 'operation' }] }, { prim: 'PUSH', args: [{ prim: 'key_hash' }, { string: pkh }] }, { prim: 'SOME' }, { prim: 'SET_DELEGATE' }, { prim: 'CONS' }] }; } getContractUnDelegation() { return { entrypoint: 'do', value: [{ prim: 'DROP' }, { prim: 'NIL', args: [{ prim: 'operation' }], }, { prim: 'NONE', args: [{ prim: 'key_hash' }], }, { prim: 'SET_DELEGATE' }, { prim: 'CONS' }] }; } getContractPkhTransaction(to: string, amount: string) { return { entrypoint: 'do', value: [{ prim: 'DROP' }, { prim: 'NIL', args: [{ prim: 'operation' }] }, { prim: 'PUSH', args: [{ prim: 'key_hash' }, { string: to }] }, { prim: 'IMPLICIT_ACCOUNT' }, { prim: 'PUSH', args: [{ prim: 'mutez' }, { 'int': amount }] }, { prim: 'UNIT' }, { prim: 'TRANSFER_TOKENS' }, { prim: 'CONS' }] }; } getContractKtTransaction(to: string, amount: string) { return { entrypoint: 'do', value: [{ prim: 'DROP' }, { prim: 'NIL', args: [{ prim: 'operation' }] }, { prim: 'PUSH', args: [{ prim: 'address' }, { string: to }] }, { prim: 'CONTRACT', args: [{ prim: 'unit' }] }, [{ prim: 'IF_NONE', args: [[[{ prim: 'UNIT' }, { prim: 'FAILWITH' }]], []] }], { prim: 'PUSH', args: [{ prim: 'mutez' }, { 'int': amount }] }, { prim: 'UNIT' }, { prim: 'TRANSFER_TOKENS' }, { prim: 'CONS' }] }; } getManagerScript(pkh: string) { let pkHex: string; if (pkh.slice(0, 2) === 'tz') { pkHex = '00' + this.buf2hex(this.b58cdecode(pkh, this.prefix.tz1)); } else { pkHex = pkh; } return { code: [ { prim: 'parameter', args: [ { prim: 'or', args: [ { prim: 'lambda', args: [ { prim: 'unit' }, { prim: 'list', args: [ { prim: 'operation' } ] } ], annots: [ '%do' ] }, { prim: 'unit', annots: [ '%default' ] } ] } ] }, { prim: 'storage', args: [ { prim: 'key_hash' } ] }, { prim: 'code', args: [ [ [ [ { prim: 'DUP' }, { prim: 'CAR' }, { prim: 'DIP', args: [ [ { prim: 'CDR' } ] ] } ] ], { prim: 'IF_LEFT', args: [ [ { prim: 'PUSH', args: [ { prim: 'mutez' }, { 'int': '0' } ] }, { prim: 'AMOUNT' }, [ [ { prim: 'COMPARE' }, { prim: 'EQ' } ], { prim: 'IF', args: [ [ ], [ [ { prim: 'UNIT' }, { prim: 'FAILWITH' } ] ] ] } ], [ { prim: 'DIP', args: [ [ { prim: 'DUP' } ] ] }, { prim: 'SWAP' } ], { prim: 'IMPLICIT_ACCOUNT' }, { prim: 'ADDRESS' }, { prim: 'SENDER' }, [ [ { prim: 'COMPARE' }, { prim: 'EQ' } ], { prim: 'IF', args: [ [ ], [ [ { prim: 'UNIT' }, { prim: 'FAILWITH' } ] ] ] } ], { prim: 'UNIT' }, { prim: 'EXEC' }, { prim: 'PAIR' } ], [ { prim: 'DROP' }, { prim: 'NIL', args: [ { prim: 'operation' } ] }, { prim: 'PAIR' } ] ] } ] ] } ], storage: { bytes: pkHex } }; } getFA12Transaction(from: string, to: string, amount: string) { return { entrypoint: 'transfer', value: { args: [ { string: from }, { args: [ { string: to }, { int: amount } ], prim: 'Pair' } ], prim: 'Pair' } }; } getFA2Transaction(from: string, to: string, amount: string, id: number) { let stringId: string; // skeles hotfix if (id > Number.MAX_SAFE_INTEGER) { const map = import('../../../assets/js/KT1HZVd9Cjc2CMe3sQvXgbxhpJkdena21pih.json'); stringId = map[id] as any; } return { entrypoint: 'transfer', value: [ { prim: 'Pair', args: [ { string: from }, [ { prim: 'Pair', args: [ { string: to }, { prim: 'Pair', args: [ { 'int': stringId ?? id.toString() }, { 'int': amount } ] } ] } ] ] } ] }; } parseTokenTransfer(op: any): { tokenId: string, to: string, amount: string } { const opJson = JSON.stringify(op.parameters); const addresses = opJson.match(/\{\"string\":\"[^\"]*/g)?.map(s => { return s.slice(11); }); const amounts = opJson.match(/\{\"int\":\"[^\"]*/g)?.map(i => { return i.slice(8); }); if (!addresses || !amounts) { return null; } if (addresses.length === 2) { if (amounts.length === 1) { const fa12ref = this.getFA12Transaction(addresses[0], addresses[1], amounts[0]); if (isEqual(fa12ref, op.parameters)) { return { tokenId: `${op.destination}:0`, to: addresses[1], amount: amounts[0] }; } } else if (amounts.length === 2) { const fa2ref = this.getFA2Transaction(addresses[0], addresses[1], amounts[1], Number(amounts[0])); if (isEqual(fa2ref, op.parameters)) { return { tokenId: `${op.destination}:${amounts[0]}`, to: addresses[1], amount: amounts[1] }; } } } return null; } postRpc(path: string, payload: any): Observable<any> { return this.http.post(`${this.nodeURL}/${path}`, payload, httpOptions).pipe(this.retryPipeline(path)) } getRpc(path: string): Observable<any> { return this.http.get(`${this.nodeURL}/${path}`).pipe(this.retryPipeline(path)) } private retryPipeline(path: string, retries: number = 3): MonoTypeOperatorFunction<unknown> { const retryWithWarning = (i, e) => { if (i < retries) { console.warn(`Retry ${i + 1}: ${path}`, e); } return of(e).pipe(delayOperator(250)) }; return retryWhen(errors => errors.pipe( concatMap((e, i) => iif( () => (i >= retries || !(e?.name === 'HttpErrorResponse')), throwError(e), retryWithWarning(i, e) ) ) )); } }
the_stack
declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zza { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zza>; public asBinder(): globalAndroid.os.IBinder; public constructor(param0: string); public onTransact(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzaa extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzy<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzaa>; public size(): number; public get(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzab<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzu<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzab<any>>; public get(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzac<K, V> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzac<any,any>>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzad<K, V> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzad<any,any>>; public getOrDefault(param0: any, param1: V): V; public get(param0: any): V; public hashCode(): number; public containsKey(param0: any): boolean; public clear(): void; public put(param0: K, param1: V): V; public remove(param0: any): V; public toString(): string; public isEmpty(): boolean; public equals(param0: any): boolean; public containsValue(param0: any): boolean; public putAll(param0: java.util.Map<any,any>): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzae<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzy<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzae<any>>; public size(): number; public get(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzaf<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzz<any>*/ implements java.util.Set<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzaf<any>>; public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzag<K, V> extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzaf<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzag<any,any>>; public contains(param0: any): boolean; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzah<K, V> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzad<any,any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzah<any,any>>; public get(param0: any): any; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzai<K> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzaf<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzai<any>>; public contains(param0: any): boolean; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzaj extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzy<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzaj>; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzak { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzak>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzal extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzy<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzal>; public size(): number; public get(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzam<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzan<any>*/ implements java.util.ListIterator<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzam<any>>; public constructor(); public set(param0: any): void; public add(param0: any): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzan<E> extends java.util.Iterator<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzan<any>>; public constructor(); public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzaq { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzaq>; } export module zzaq { export class zza extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzat { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzaq.zza>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzas { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzas>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzat { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzat>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzau extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzat { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzau>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzav extends java.lang.ref.WeakReference<java.lang.Throwable> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzav>; public hashCode(): number; public equals(param0: any): boolean; public constructor(param0: java.lang.Throwable, param1: java.lang.ref.ReferenceQueue<java.lang.Throwable>); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzaw extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzat { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzaw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzax { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzax>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzay { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay>; } export module zzay { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zza,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zza>; public isInitialized(): boolean; } export module zza { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zza,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zza.zza>; public isInitialized(): boolean; } } export class zzaa extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa.zzc>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa>; public isInitialized(): boolean; } export module zzaa { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa.zza>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa.zza>*/; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa.zzb>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa.zzb>*/; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa.zzc>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa.zzc>; public isInitialized(): boolean; } } export class zzab extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzab,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzab.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzab>; public isInitialized(): boolean; } export module zzab { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzab,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzab.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzab.zza>; public isInitialized(): boolean; } } export class zzac extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzac,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzac.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzac>; public isInitialized(): boolean; } export module zzac { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzac,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzac.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzac.zza>; public isInitialized(): boolean; } } export class zzad extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzad,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzad.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzad>; public isInitialized(): boolean; } export module zzad { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzad,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzad.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzad.zza>; public isInitialized(): boolean; } } export class zzae extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae>; public isInitialized(): boolean; } export module zzae { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zza,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zza>; public isInitialized(): boolean; } export module zza { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zza,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zza.zza>; public isInitialized(): boolean; } } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzb>; public isInitialized(): boolean; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzc>; public isInitialized(): boolean; } export module zzc { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzc.zza>; public isInitialized(): boolean; } } export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzd,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzd.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzd>; public isInitialized(): boolean; } export module zzd { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzd,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzd.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzae.zzd.zza>; public isInitialized(): boolean; } } } export class zzaf extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaf,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaf.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaf>; public isInitialized(): boolean; } export module zzaf { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaf,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaf.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaf.zza>; public isInitialized(): boolean; } } export class zzag extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzag,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzag.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzag>; public isInitialized(): boolean; } export module zzag { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzag.zza>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzag.zza>*/; public toString(): string; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzag,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzag.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzag.zzb>; public isInitialized(): boolean; } } export class zzah extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzah,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzah.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzah>; public isInitialized(): boolean; } export module zzah { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzah,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzah.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzah.zza>; public isInitialized(): boolean; } } export class zzai extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzai,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzai.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzai>; public isInitialized(): boolean; } export module zzai { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzai,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzai.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzai.zza>; public isInitialized(): boolean; } } export class zzaj extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj>; public isInitialized(): boolean; } export module zzaj { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zzb>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zzb>*/; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zzc>; public isInitialized(): boolean; } export module zzc { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zzc.zza>; public isInitialized(): boolean; } } } export class zzak extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzak,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzak.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzak>; public isInitialized(): boolean; } export module zzak { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzak,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzak.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzak.zza>; public isInitialized(): boolean; } } export class zzal extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzal,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzal.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzal>; public isInitialized(): boolean; } export module zzal { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzal.zza>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzal.zza>*/; public toString(): string; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzal,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzal.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzal.zzb>; public isInitialized(): boolean; } } export class zzam extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzam,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzam.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzam>; public isInitialized(): boolean; } export module zzam { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzam,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzam.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzam.zza>; public isInitialized(): boolean; } } export class zzan extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzan,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzan.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzan>; public isInitialized(): boolean; } export module zzan { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzan,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzan.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzan.zza>; public isInitialized(): boolean; } } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzb>; public isInitialized(): boolean; } export module zzb { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzb.zza>; public isInitialized(): boolean; } } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzc>; public isInitialized(): boolean; } export module zzc { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzc,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzc.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzc.zza>; public isInitialized(): boolean; } } export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzd,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzd.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzd>; public isInitialized(): boolean; } export module zzd { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzd,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzd.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzd.zza>; public isInitialized(): boolean; } } export class zze extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zze,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zze.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zze>; public isInitialized(): boolean; } export module zze { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zze.zza>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zze.zza>*/; public toString(): string; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zze,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zze.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zze.zzb>; public isInitialized(): boolean; } } export class zzf extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzf,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzf.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzf>; public isInitialized(): boolean; } export module zzf { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzf,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzf.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzf.zza>; public isInitialized(): boolean; } } export class zzg extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzg,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzg.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzg>; public isInitialized(): boolean; } export module zzg { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzg,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzg.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzg.zza>; public isInitialized(): boolean; } } export class zzh extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzh,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzh.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzh>; public isInitialized(): boolean; } export module zzh { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzh,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzh.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzh.zza>; public isInitialized(): boolean; } } export class zzi extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzi,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzi.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzi>; public isInitialized(): boolean; } export module zzi { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzi,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzi.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzi.zza>; public isInitialized(): boolean; } } export class zzj extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzj,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzj.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzj>; public isInitialized(): boolean; } export module zzj { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzj,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzj.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzj.zza>; public isInitialized(): boolean; } } export class zzk extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzk,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzk.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzk>; public isInitialized(): boolean; } export module zzk { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzk,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzk.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzk.zza>; public isInitialized(): boolean; } } export class zzl extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzl,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzl.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzl>; public isInitialized(): boolean; } export module zzl { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzl,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzl.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzl.zza>; public isInitialized(): boolean; } } export class zzm extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzm,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzm.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzm>; public isInitialized(): boolean; } export module zzm { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzm,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzm.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzm.zza>; public isInitialized(): boolean; } } export class zzn extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzn,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzn.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzn>; public isInitialized(): boolean; } export module zzn { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzn,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzn.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzn.zza>; public isInitialized(): boolean; } } export class zzo extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzo,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzo.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzo>; public isInitialized(): boolean; } export module zzo { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzo,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzo.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzo.zza>; public isInitialized(): boolean; } } export class zzp extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp>; public isInitialized(): boolean; } export module zzp { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zzb>; public isInitialized(): boolean; } export module zzb { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zzb.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zzb.zzb>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zzb.zzb>*/; } } } export class zzq extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzq,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzq.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzq>; public isInitialized(): boolean; } export module zzq { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzq,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzq.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzq.zza>; public isInitialized(): boolean; } } export class zzr extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr>; public isInitialized(): boolean; } export module zzr { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zzb>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zzb>*/; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zzc>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zzc>*/; public toString(): string; } export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zzd>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zzd>*/; } export class zze extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zze>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zze>*/; } } export class zzs extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzs,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzs.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzs>; public isInitialized(): boolean; } export module zzs { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzs,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzs.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzs.zza>; public isInitialized(): boolean; } } export class zzt extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzt,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzt.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzt>; public isInitialized(): boolean; } export module zzt { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzt,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzt.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzt.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzt.zzb>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzt.zzb>*/; public toString(): string; } } export class zzu extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzu,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzu.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzu>; public isInitialized(): boolean; } export module zzu { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzu,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzu.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzu.zza>; public isInitialized(): boolean; } } export class zzv extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzv,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzv.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzv>; public isInitialized(): boolean; } export module zzv { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzv,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzv.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzv.zza>; public isInitialized(): boolean; } } export class zzw extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzw,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzw.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzw>; public isInitialized(): boolean; } export module zzw { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzw.zza>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzw.zza>*/; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzw,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzw.zzb>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzw.zzb>; public isInitialized(): boolean; } } export class zzx extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx>; public isInitialized(): boolean; } export module zzx { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx.zzb>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx.zzb>*/; public toString(): string; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx.zzc>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx.zzc>*/; } } export class zzy extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy>; public isInitialized(): boolean; } export module zzy { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy.zzb>; public isInitialized(): boolean; } export module zzb { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzy.zzb.zza>; public isInitialized(): boolean; } } } export class zzz extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzz,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzz.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzz>; public isInitialized(): boolean; } export module zzz { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzz,com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzz.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzz.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzz.zzb>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzz.zzb>*/; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzaz extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzaz>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzb { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzb>; public constructor(param0: globalAndroid.os.IBinder, param1: string); public asBinder(): globalAndroid.os.IBinder; public obtainAndWriteInterfaceToken(): globalAndroid.os.Parcel; public transactOneway(param0: number, param1: globalAndroid.os.Parcel): void; public transactAndReadExceptionReturnVoid(param0: number, param1: globalAndroid.os.Parcel): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzba extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzba>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zze.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzp.zzb.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbc>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbd extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbd>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbe extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbe>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbf extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbg>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbf>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbg extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbg>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbg>*/; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbh extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbh>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbh>*/; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbi extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbi>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbj extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbk extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbh>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbk>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbl extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbm extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbn extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbn>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbo extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zzc>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbo>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbp extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zzd>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbp>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbq extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbr extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbs extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzr.zze>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbs>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbt extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzt.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbt>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbu extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbu>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbv extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbv>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbw extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzw.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbx extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbx>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzby extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzby>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzbz extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzbz>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzc>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzc interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzca extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzx.zzc>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzca>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzcb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzz.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzcb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzcc extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzcc>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzcd extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzcd>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzce extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzce>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzcf extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzcf>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzcg extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzcg>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzch extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzch>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzci extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaa.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzci>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzcj extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzcj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzck extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzag.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzck>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzcl extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzaj.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzcl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzcm extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzcm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzcn extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzcn>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzco extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzay.zzal.zza>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzco>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzd>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdj { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj>; } export module zzdj { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zza,com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zza>; public isInitialized(): boolean; } export module zza { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zza,com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zza.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zza.zza>; public isInitialized(): boolean; } } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb>; public isInitialized(): boolean; } export module zzb { export class zza extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb,com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zza>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zza>; public isInitialized(): boolean; } export class zzb extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zzb>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zzb>*/; public toString(): string; } export class zzc extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zzc>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zzc>*/; public toString(): string; } export class zzd extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zzd>; public toString(): string; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zzd>*/; } } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdl { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdm extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdn extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zzb>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdn>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdo extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdo>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdp extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdp>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdq extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zzc>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdr extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdj.zzb.zzd>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzds extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzds>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzds>*/; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdt extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdt>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdu extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdu>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdv extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<com.google.android.gms.internal.firebase_ml_naturallanguage.zzds>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdv>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzdw<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgo*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdw<any,any>>; public constructor(); public isInitialized(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzdx<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdx<any,any>>; public constructor(); public isInitialized(): boolean; public toByteArray(): native.Array<number>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzdy<E> extends java.util.AbstractList<any> implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfp<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdy<any>>; public addAll(param0: number, param1: java.util.Collection<any>): boolean; public remove(param0: number): any; public set(param0: number, param1: any): any; public add(param0: any): boolean; public hashCode(): number; public remove(param0: any): boolean; public removeAll(param0: java.util.Collection<any>): boolean; public add(param0: number, param1: any): void; public clear(): void; public equals(param0: any): boolean; public addAll(param0: java.util.Collection<any>): boolean; public retainAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzdz<MessageType> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzdz<any>>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzea { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzea>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzeb { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzeb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzec extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzee { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzec>; public nextByte(): number; public hasNext(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzed extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzed>; public size(): number; public hashCode(): number; public toString(): string; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzee extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzei { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzee>; public nextByte(): number; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzef extends java.lang.Object /* java.util.Comparator<com.google.android.gms.internal.firebase_ml_naturallanguage.zzed>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzef>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzeg extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzen { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzeg>; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzeh { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzeh>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzei extends java.util.Iterator<java.lang.Byte> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzei>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzei interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { nextByte(): number; }); public constructor(); public nextByte(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzej { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzej>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzej interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzek extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzed { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzek>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzel { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzel>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzem { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzem>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzen extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzek { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzen>; public bytes: native.Array<number>; public size(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzeo { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzeo>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzep { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzep>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzeq extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzea { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzeq>; } export module zzeq { export class zza extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzeq { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzeq.zza>; } export class zzb { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzeq.zzb>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzer extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzep { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzer>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzes { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzes>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzet extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzio { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzet>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzeu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzeu>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzev { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzev>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzew extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzex<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzew>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzex<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzex<any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzey<FieldDescriptorType> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzey<any>>; public iterator(): java.util.Iterator<java.util.Map.Entry<FieldDescriptorType,any>>; public hashCode(): number; public equals(param0: any): boolean; public isInitialized(): boolean; public isImmutable(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzez { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzez>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfa<T> extends java.lang.Comparable<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfa<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzfa<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzag(): number; zzei(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzii*/; zzej(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzip*/; zzek(): boolean; zzel(): boolean; zza(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgo*/, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgo*/; zza(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgv*/, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgv*/): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgv*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfb { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfc { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfc>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfd>; public id(): number; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfd>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfe extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzgm { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfe>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzff { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzff>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzff>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzfg<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzdx<any,any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<any,any>>; public constructor(); public hashCode(): number; public toString(): string; public equals(param0: any): boolean; public isInitialized(): boolean; } export module zzfg { export class zza<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzdw<any,any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza<any,any>>; public constructor(param0: any); public isInitialized(): boolean; public constructor(); } export abstract class zzb<MessageType, BuilderType> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg<any,any>*/ implements any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zzb<any,any>>; public isInitialized(): boolean; public constructor(); } export class zzc<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzdz<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zzc<any>>; public constructor(param0: any); public constructor(); } export class zzd extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zzd>; public static values$50KLMJ33DTMIUPRFDTJMOP9FE1P6UT3FC9QMCBQ7CLN6ASJ1EHIM8JB5EDPM2PR59HKN8P949LIN8Q3FCHA6UIBEEPNMMP9R0(): native.Array<number>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfh extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzdy<java.lang.Integer> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfh>; public addAll(param0: number, param1: java.util.Collection<any>): boolean; public remove(param0: number): any; public size(): number; public hashCode(): number; public remove(param0: any): boolean; public equals(param0: any): boolean; public removeRange(param0: number, param1: number): void; public getInt(param0: number): number; public addAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfi { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzfi interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzag(): number; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfj { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfj>; public static hashCode(param0: native.Array<number>): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzfk interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfl<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfm<F, T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfm<any,any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzfm<any,any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfn extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfp<java.lang.Integer> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfn>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzfn interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzdk(): void; zzdj(): boolean; zzae(param0: number): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfp<any>*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfo { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfo>; public constructor(param0: string); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfp<E> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfp<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzfp<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzdk(): void; zzdj(): boolean; zzae(param0: number): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfp<E>*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfq { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfq>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfq>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfr extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfo { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfr>; public constructor(param0: string); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfs { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfs>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzft extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzft>; public hashCode(): number; public toString(): string; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfu<K> extends java.util.Iterator<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfu<any>>; public constructor(param0: java.util.Iterator<java.util.Map.Entry<any,any>>); public hasNext(): boolean; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfv<K> extends java.util.Map.Entry<any,any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfv<any>>; public getValue(): any; public getKey(): any; public setValue(param0: any): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfw extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzdy<string>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfw>; public constructor(); public addAll(param0: number, param1: java.util.Collection<any>): boolean; public size(): number; public getRaw(param0: number): any; public clear(): void; public constructor(param0: number); public addAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfx>; public constructor(); public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzfy { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfy>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzfz { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzfz>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzfz interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getRaw(param0: number): any; zzc(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzed*/): void; zzfd(): java.util.List<any>; zzfe(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfz*/; }); public constructor(); public getRaw(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzga extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfy { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzga>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgb { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgc extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzdy<java.lang.Long> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgc>; public addAll(param0: number, param1: java.util.Collection<any>): boolean; public remove(param0: number): any; public size(): number; public hashCode(): number; public remove(param0: any): boolean; public equals(param0: any): boolean; public removeRange(param0: number, param1: number): void; public getLong(param0: number): number; public addAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgd extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzfy { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgd>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzge extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzgm { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzge>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgf extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzhf { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgf>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgg<K, V> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgg<any,any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgh extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzgm { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgh>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgi { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgi>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzgi interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzh(param0: any): java.util.Map<any,any>; zzi(param0: any): any; zzj(param0: any): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgg<any,any>*/; zzd(param0: any, param1: any): any; zzb(param0: number, param1: any, param2: any): number; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgj<K, V> extends java.util.LinkedHashMap<any,any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgj<any,any>>; public entrySet(): java.util.Set<java.util.Map.Entry<any,any>>; public hashCode(): number; public remove(param0: any): any; public clear(): void; public isMutable(): boolean; public put(param0: any, param1: any): any; public equals(param0: any): boolean; public putAll(param0: java.util.Map<any,any>): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgk>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgl extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzgi { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgm { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgm>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzgm interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zza(param0: java.lang.Class<any>): boolean; zzb(param0: java.lang.Class<any>): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgn*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgn { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgn>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzgn interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzfn(): number; zzfo(): boolean; zzfp(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgo extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgo>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzgo interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzer(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/; zzeq(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/; zza(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgo*/; zzes(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/; isInitialized(): boolean; }); public constructor(); public isInitialized(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgp extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzb(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzeq*/): void; zzeu(): number; zzdh(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzed*/; zzex(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgo*/; zzes(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/; isInitialized(): boolean; }); public constructor(); public isInitialized(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgq { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgr { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzgr interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzes(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/; isInitialized(): boolean; }); public constructor(); public isInitialized(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgs<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzhc<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgs<any>>; public hashCode(param0: any): number; public equals(param0: any, param1: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgt<T> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzhc<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgt<any>>; public hashCode(param0: any): number; public equals(param0: any, param1: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgu>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzgu interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgv extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgv>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzgv interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzfq(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgv*/; zzb(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzeq*/): void; zzeu(): number; zzdh(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzed*/; zzex(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgo*/; zzes(): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/; isInitialized(): boolean; }); public constructor(); public isInitialized(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgw { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgx extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzgu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgx>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgy { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgy>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzgy interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzgz<MessageType> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzgz<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzgz<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzha<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzdy<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzha<any>>; public remove(param0: number): any; public set(param0: number, param1: any): any; public add(param0: any): boolean; public size(): number; public remove(param0: any): boolean; public add(param0: number, param1: any): void; public get(param0: number): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhb { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhb>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhc<T> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhc<any>>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzhc<any> interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zza(param0: T, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzio*/): void; zze(param0: T): void; zzl(param0: T): boolean; equals(param0: T, param1: T): boolean; hashCode(param0: T): number; zze(param0: T, param1: T): void; zzm(param0: T): number; }); public constructor(); public equals(param0: T, param1: T): boolean; public hashCode(param0: T): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhd extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzgn { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhd>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhe { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhe>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhf { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhf>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzhf interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzd(param0: java.lang.Class): any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzhc<any>*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhg extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzhh<any,any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhg>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhh<K, V> extends java.util.AbstractMap<any,any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhh<any,any>>; public get(param0: any): any; public entrySet(): java.util.Set<java.util.Map.Entry<any,any>>; public size(): number; public hashCode(): number; public remove(param0: any): any; public containsKey(param0: any): boolean; public clear(): void; public equals(param0: any): boolean; public isImmutable(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhi extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzho*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhi>; public iterator(): java.util.Iterator<java.util.Map.Entry<any,any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhj extends java.util.Iterator<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhj>; public hasNext(): boolean; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhk extends java.util.Iterator<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhk>; public hasNext(): boolean; public remove(): void; public next(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhl { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhm extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhm>; public getValue(): any; public hashCode(): number; public toString(): string; public setValue(param0: any): any; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhn extends java.lang.Iterable<any> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhn>; public iterator(): java.util.Iterator<any>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzho extends java.util.AbstractSet<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzho>; public contains(param0: any): boolean; public size(): number; public remove(param0: any): boolean; public clear(): void; public iterator(): java.util.Iterator<java.util.Map.Entry<any,any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhp extends java.util.Iterator<java.util.Map.Entry<any,any>> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhp>; public hasNext(): boolean; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhq { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhr extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzgn { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhs { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhs>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzhs interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { size(): number; zzj(param0: number): number; }); public constructor(); public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzht extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzhs { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzht>; public size(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzhu<T, B> extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhu<any,any>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhv { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhv>; public constructor(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgp*/); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhw extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzhu<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhx,com.google.android.gms.internal.firebase_ml_naturallanguage.zzhx>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhx>; public hashCode(): number; public equals(param0: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhy extends java.util.ListIterator<string> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhy>; public previousIndex(): number; public nextIndex(): number; public hasNext(): boolean; public remove(): void; public hasPrevious(): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzhz extends java.util.AbstractList<string> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzhz>; public listIterator(param0: number): java.util.ListIterator<string>; public iterator(): java.util.Iterator<string>; public size(): number; public getRaw(param0: number): any; public constructor(param0: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzfz*/); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzia { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzia>; } export module zzia { export class zza extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzia.zzd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzia.zza>; } export class zzb extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzia.zzd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzia.zzb>; } export class zzc extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzia.zzd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzia.zzc>; } export abstract class zzd { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzia.zzd>; } } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzib extends java.util.Iterator<string> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzib>; public hasNext(): boolean; public remove(): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzic extends java.security.PrivilegedExceptionAction<sun.misc.Unsafe> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzic>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzid { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzid>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzie extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzif { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzie>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzif { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzif>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzig extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzif { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzig>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzih { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzih>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzii { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzii>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzii>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzij { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzij>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzik extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzii { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzik>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzil extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzii { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzil>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzim extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzii { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzim>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzin extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzii { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzin>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzio { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzio>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzio interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzdy(): number; zzp(param0: number, param1: number): void; zzi(param0: number, param1: number): void; zzj(param0: number, param1: number): void; zza(param0: number, param1: number): void; zza(param0: number, param1: number): void; zzq(param0: number, param1: number): void; zza(param0: number, param1: number): void; zzf(param0: number, param1: number): void; zzc(param0: number, param1: number): void; zzi(param0: number, param1: number): void; zza(param0: number, param1: boolean): void; zza(param0: number, param1: string): void; zza(param0: number, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzed*/): void; zzg(param0: number, param1: number): void; zzh(param0: number, param1: number): void; zzb(param0: number, param1: number): void; zza(param0: number, param1: any, param2: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzhc<any>*/): void; zzb(param0: number, param1: any, param2: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzhc<any>*/): void; zzaa(param0: number): void; zzab(param0: number): void; zza(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzb(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzc(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void; zzd(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void; zze(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void; zzf(param0: number, param1: java.util.List<java.lang.Float>, param2: boolean): void; zzg(param0: number, param1: java.util.List<java.lang.Double>, param2: boolean): void; zzh(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzi(param0: number, param1: java.util.List<java.lang.Boolean>, param2: boolean): void; zza(param0: number, param1: java.util.List<string>): void; zzb(param0: number, param1: any /* java.util.List<com.google.android.gms.internal.firebase_ml_naturallanguage.zzed>*/): void; zzj(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzk(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzl(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void; zzm(param0: number, param1: java.util.List<java.lang.Integer>, param2: boolean): void; zzn(param0: number, param1: java.util.List<java.lang.Long>, param2: boolean): void; zza(param0: number, param1: java.util.List<any>, param2: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzhc<any>*/): void; zzb(param0: number, param1: java.util.List<any>, param2: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzhc<any>*/): void; zza(param0: number, param1: any): void; zza(param0: number, param1: any /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzgg<any,any>*/, param2: java.util.Map): void; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzip { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzip>; public static values(): any /* native.Array<com.google.android.gms.internal.firebase_ml_naturallanguage.zzip>*/; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzj { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzj>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml_naturallanguage.zzj interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzk>; public constructor(); public constructor(param0: globalAndroid.os.Looper, param1: globalAndroid.os.Handler.Callback); public dispatchMessage(param0: globalAndroid.os.Message): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzl { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzl>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzm { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzm>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzn { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzn>; public static UTF_8: java.nio.charset.Charset; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzo { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzo>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzp { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzp>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzq { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzr { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzr>; public toString(): string; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzs { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzs>; public static checkNotNull(param0: any): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzt extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzm { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzt>; public static equal(param0: any, param1: any): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzu<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzam<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzu<any>>; public constructor(); public previousIndex(): number; public constructor(param0: number, param1: number); public previous(): any; public nextIndex(): number; public hasNext(): boolean; public get(param0: number): any; public hasPrevious(): boolean; public next(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzv { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzv>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzw { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzw>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export class zzx { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzx>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzy<E> extends java.lang.Object /* com.google.android.gms.internal.firebase_ml_naturallanguage.zzz<any>*/ { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzy<any>>; public addAll(param0: number, param1: java.util.Collection<any>): boolean; public contains(param0: any): boolean; public set(param0: number, param1: any): any; public remove(param0: number): any; public add(param0: any): boolean; public lastIndexOf(param0: any): number; public hashCode(): number; public remove(param0: any): boolean; public add(param0: number, param1: any): void; public indexOf(param0: any): number; public equals(param0: any): boolean; public addAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml_naturallanguage { export abstract class zzz<E> extends java.util.AbstractCollection<any> implements java.io.Serializable { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml_naturallanguage.zzz<any>>; public contains(param0: any): boolean; public add(param0: any): boolean; public remove(param0: any): boolean; public removeAll(param0: java.util.Collection<any>): boolean; public toArray(param0: native.Array<any>): native.Array<any>; public clear(): void; public toArray(): native.Array<any>; public addAll(param0: java.util.Collection<any>): boolean; public retainAll(param0: java.util.Collection<any>): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class ReplyContextElement { public static class: java.lang.Class<com.google.android.gms.predictondevice.ReplyContextElement>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.ReplyContextElement>; public getTimeDeltaMs(): number; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public getText(): string; public getUserId(): number; } export module ReplyContextElement { export class zza { public static class: java.lang.Class<com.google.android.gms.predictondevice.ReplyContextElement.zza>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class ReplyParams { public static class: java.lang.Class<com.google.android.gms.predictondevice.ReplyParams>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.ReplyParams>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: number, param1: number); } export module ReplyParams { export class zza { public static class: java.lang.Class<com.google.android.gms.predictondevice.ReplyParams.zza>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class SmartReply { public static class: java.lang.Class<com.google.android.gms.predictondevice.SmartReply>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.SmartReply>; public getResponse(): string; public constructor(param0: string, param1: number, param2: number); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public toString(): string; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class SmartReplyOptions { public static class: java.lang.Class<com.google.android.gms.predictondevice.SmartReplyOptions>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.SmartReplyOptions>; public getLocaleObjs(): java.util.List<java.util.Locale>; public constructor(param0: java.util.List<java.util.Locale>, param1: string); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public equals(param0: any): boolean; public hashCode(): number; } export module SmartReplyOptions { export class zza { public static class: java.lang.Class<com.google.android.gms.predictondevice.SmartReplyOptions.zza>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class SmartReplyResult { public static class: java.lang.Class<com.google.android.gms.predictondevice.SmartReplyResult>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.SmartReplyResult>; public static STATUS_SUCCESS: number; public static STATUS_SENSITIVE_TOPIC: number; public static STATUS_QUALITY_THRESHOLDED: number; public static STATUS_ERROR: number; public constructor(); public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: number, param1: native.Array<com.google.android.gms.predictondevice.SmartReply>); public getResponses(): native.Array<com.google.android.gms.predictondevice.SmartReply>; public getStatus(): number; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export module internal { export class IPredictOnDeviceCallbacks { public static class: java.lang.Class<com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks>; /** * Constructs a new instance of the com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { onModelLoaded(param0: com.google.android.gms.common.api.Status): void; onSmartReplied(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.predictondevice.SmartReplyResult): void; onModelUnloaded(param0: com.google.android.gms.common.api.Status): void; }); public constructor(); public onModelUnloaded(param0: com.google.android.gms.common.api.Status): void; public onModelLoaded(param0: com.google.android.gms.common.api.Status): void; public onSmartReplied(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.predictondevice.SmartReplyResult): void; } export module IPredictOnDeviceCallbacks { export abstract class zza extends com.google.android.gms.internal.firebase_ml_naturallanguage.zza implements com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks { public static class: java.lang.Class<com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks.zza>; public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; public onSmartReplied(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.predictondevice.SmartReplyResult): void; public constructor(); public constructor(param0: string); public onModelLoaded(param0: com.google.android.gms.common.api.Status): void; public onModelUnloaded(param0: com.google.android.gms.common.api.Status): void; } } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export module internal { export class PredictOnDeviceOptions { public static class: java.lang.Class<com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions>; public static CREATOR: globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions>; public writeToParcel(param0: globalAndroid.os.Parcel, param1: number): void; public constructor(param0: com.google.android.gms.predictondevice.SmartReplyOptions); public getSmartReplyOptions(): com.google.android.gms.predictondevice.SmartReplyOptions; public getApi(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export module internal { export class zza extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzb implements com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks { public static class: java.lang.Class<com.google.android.gms.predictondevice.internal.zza>; public onModelUnloaded(param0: com.google.android.gms.common.api.Status): void; public onModelLoaded(param0: com.google.android.gms.common.api.Status): void; public onSmartReplied(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.predictondevice.SmartReplyResult): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export module internal { export abstract class zzb extends com.google.android.gms.internal.firebase_ml_naturallanguage.zza implements com.google.android.gms.predictondevice.internal.zzc { public static class: java.lang.Class<com.google.android.gms.predictondevice.internal.zzb>; public constructor(); public loadModel(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; public reportUserReply(param0: java.util.List<com.google.android.gms.predictondevice.ReplyContextElement>, param1: com.google.android.gms.predictondevice.ReplyContextElement, param2: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; public constructor(param0: string); public unloadModel(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; public smartReply(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: java.util.List<com.google.android.gms.predictondevice.ReplyContextElement>, param2: com.google.android.gms.predictondevice.ReplyParams, param3: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; public dispatchTransaction(param0: number, param1: globalAndroid.os.Parcel, param2: globalAndroid.os.Parcel, param3: number): boolean; } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export module internal { export class zzc { public static class: java.lang.Class<com.google.android.gms.predictondevice.internal.zzc>; /** * Constructs a new instance of the com.google.android.gms.predictondevice.internal.zzc interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { loadModel(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; smartReply(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: java.util.List<com.google.android.gms.predictondevice.ReplyContextElement>, param2: com.google.android.gms.predictondevice.ReplyParams, param3: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; unloadModel(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; reportUserReply(param0: java.util.List<com.google.android.gms.predictondevice.ReplyContextElement>, param1: com.google.android.gms.predictondevice.ReplyContextElement, param2: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; }); public constructor(); public loadModel(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; public reportUserReply(param0: java.util.List<com.google.android.gms.predictondevice.ReplyContextElement>, param1: com.google.android.gms.predictondevice.ReplyContextElement, param2: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; public unloadModel(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; public smartReply(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: java.util.List<com.google.android.gms.predictondevice.ReplyContextElement>, param2: com.google.android.gms.predictondevice.ReplyParams, param3: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export module internal { export class zzd extends java.lang.Object /* com.google.android.gms.common.internal.GmsClient<com.google.android.gms.predictondevice.internal.zzc>*/ { public static class: java.lang.Class<com.google.android.gms.predictondevice.internal.zzd>; public getLocalStartServiceAction(): string; public constructor(param0: globalAndroid.content.Context, param1: globalAndroid.os.Looper, param2: com.google.android.gms.common.internal.ClientSettings, param3: com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks, param4: com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener); public getStartServicePackage(): string; public getStartServiceAction(): string; public getMinApkVersion(): number; public requiresGooglePlayServices(): boolean; public getServiceDescriptor(): string; public getRequiredFeatures(): native.Array<com.google.android.gms.common.Feature>; } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export module internal { export class zze extends com.google.android.gms.internal.firebase_ml_naturallanguage.zzb implements com.google.android.gms.predictondevice.internal.zzc { public static class: java.lang.Class<com.google.android.gms.predictondevice.internal.zze>; public loadModel(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; public reportUserReply(param0: java.util.List<com.google.android.gms.predictondevice.ReplyContextElement>, param1: com.google.android.gms.predictondevice.ReplyContextElement, param2: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; public unloadModel(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; public smartReply(param0: com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks, param1: java.util.List<com.google.android.gms.predictondevice.ReplyContextElement>, param2: com.google.android.gms.predictondevice.ReplyParams, param3: com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export module internal { export class zzf extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.internal.PredictOnDeviceOptions> { public static class: java.lang.Class<com.google.android.gms.predictondevice.internal.zzf>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zza extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.ReplyContextElement> { public static class: java.lang.Class<com.google.android.gms.predictondevice.zza>; public constructor(); } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzb extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.ReplyParams> { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzb>; public constructor(); } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzc { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzc>; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzd extends com.google.android.gms.common.api.Api.AbstractClientBuilder<com.google.android.gms.predictondevice.internal.zzd,com.google.android.gms.predictondevice.SmartReplyOptions> { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzd>; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zze extends com.google.android.gms.common.api.GoogleApi<com.google.android.gms.predictondevice.SmartReplyOptions> { public static class: java.lang.Class<com.google.android.gms.predictondevice.zze>; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzf extends com.google.android.gms.predictondevice.zzm { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzf>; public onModelUnloaded(param0: com.google.android.gms.common.api.Status): void; public onModelLoaded(param0: com.google.android.gms.common.api.Status): void; public onSmartReplied(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.predictondevice.SmartReplyResult): void; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzg extends com.google.android.gms.common.api.internal.TaskApiCall<com.google.android.gms.predictondevice.internal.zzd,java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzg>; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzh extends com.google.android.gms.predictondevice.zzm { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzh>; public onModelUnloaded(param0: com.google.android.gms.common.api.Status): void; public onModelLoaded(param0: com.google.android.gms.common.api.Status): void; public onSmartReplied(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.predictondevice.SmartReplyResult): void; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzi extends com.google.android.gms.common.api.internal.TaskApiCall<com.google.android.gms.predictondevice.internal.zzd,com.google.android.gms.predictondevice.SmartReplyResult> { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzi>; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzj extends com.google.android.gms.predictondevice.zzm { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzj>; public onModelUnloaded(param0: com.google.android.gms.common.api.Status): void; public onModelLoaded(param0: com.google.android.gms.common.api.Status): void; public onSmartReplied(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.predictondevice.SmartReplyResult): void; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzk extends com.google.android.gms.common.api.internal.TaskApiCall<com.google.android.gms.predictondevice.internal.zzd,java.lang.Void> { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzk>; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzl extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.SmartReply> { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzl>; public constructor(); } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzm extends com.google.android.gms.predictondevice.internal.IPredictOnDeviceCallbacks.zza { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzm>; public onModelUnloaded(param0: com.google.android.gms.common.api.Status): void; public onModelLoaded(param0: com.google.android.gms.common.api.Status): void; public onSmartReplied(param0: com.google.android.gms.common.api.Status, param1: com.google.android.gms.predictondevice.SmartReplyResult): void; } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzn extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.SmartReplyOptions> { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzn>; public constructor(); } } } } } } declare module com { export module google { export module android { export module gms { export module predictondevice { export class zzo extends globalAndroid.os.Parcelable.Creator<com.google.android.gms.predictondevice.SmartReplyResult> { public static class: java.lang.Class<com.google.android.gms.predictondevice.zzo>; public constructor(); } } } } } } //Generics information: //com.google.android.gms.internal.firebase_ml_naturallanguage.zzab:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzac:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzad:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzae:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzaf:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzag:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzah:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzai:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzam:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzan:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzdw:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzdx:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzdy:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzdz:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzex:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzey:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzfa:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zza:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zzb:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzfg.zzc:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzfl:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzfm:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzfp:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzfu:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzfv:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzgg:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzgj:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzgs:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzgt:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzgz:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzha:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzhc:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzhh:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzhu:2 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzu:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzy:1 //com.google.android.gms.internal.firebase_ml_naturallanguage.zzz:1
the_stack
import {cssClasses as listCssClasses} from '../../mdc-list/constants'; import {MDCListFoundation} from '../../mdc-list/foundation'; import {numbers} from '../../mdc-menu-surface/constants'; import {verifyDefaultAdapter} from '../../../testing/helpers/foundation'; import {setUpFoundationTest, setUpMdcTestEnvironment} from '../../../testing/helpers/setup'; import {cssClasses, DefaultFocusState, strings} from '../constants'; import {numbers as menuNumbers} from '../constants'; import {MDCMenuFoundation} from '../foundation'; function setupTest() { const {foundation, mockAdapter} = setUpFoundationTest(MDCMenuFoundation); return {foundation, mockAdapter}; } const listClasses = MDCListFoundation.cssClasses; describe('MDCMenuFoundation', () => { setUpMdcTestEnvironment(); it('defaultAdapter returns a complete adapter implementation', () => { verifyDefaultAdapter(MDCMenuFoundation, [ 'addClassToElementAtIndex', 'removeClassFromElementAtIndex', 'addAttributeToElementAtIndex', 'removeAttributeFromElementAtIndex', 'getAttributeFromElementAtIndex', 'elementContainsClass', 'closeSurface', 'getElementIndex', 'getSelectedSiblingOfItemAtIndex', 'isSelectableItemAtIndex', 'notifySelected', 'getMenuItemCount', 'focusItemAtIndex', 'focusListRoot', ]); }); it('exports strings', () => { expect(MDCMenuFoundation.strings).toEqual(strings); }); it('exports cssClasses', () => { expect(MDCMenuFoundation.cssClasses).toEqual(cssClasses); }); it('exports numbers', () => { expect(MDCMenuFoundation.numbers).toEqual(menuNumbers); }); it('destroy does not throw error', () => { const {foundation} = setupTest(); expect(() => foundation.destroy).not.toThrow(); }); it('destroy does not throw error if destroyed immediately after keydown', () => { const {foundation, mockAdapter} = setupTest(); const event = { key: 'Space', target: 'My Element', preventDefault: jasmine.createSpy('preventDefault') } as unknown as KeyboardEvent; mockAdapter.elementContainsClass .withArgs(event.target, listClasses.LIST_ITEM_CLASS) .and.returnValue(true); mockAdapter.getElementIndex.withArgs(event.target).and.returnValue(0); foundation.handleKeydown(event); expect(() => { foundation.destroy(); }).not.toThrow(); }); it('destroy closes surface', () => { const {foundation, mockAdapter} = setupTest(); expect(() => { foundation.destroy(); }).not.toThrow(); expect(mockAdapter.closeSurface).toHaveBeenCalledTimes(1); }); it('handleKeydown does nothing if key is not space, enter, or tab', () => { const {foundation, mockAdapter} = setupTest(); const event = {key: 'N'} as KeyboardEvent; foundation.handleKeydown(event); expect(mockAdapter.closeSurface).not.toHaveBeenCalled(); expect(mockAdapter.elementContainsClass) .not.toHaveBeenCalledWith(jasmine.anything()); }); it('handleKeydown tab key causes the menu to close', () => { const {foundation, mockAdapter} = setupTest(); const event = {key: 'Tab'} as KeyboardEvent; foundation.handleKeydown(event); expect(mockAdapter.closeSurface) .toHaveBeenCalledWith(/** skipRestoreFocus */ true); expect(mockAdapter.closeSurface).toHaveBeenCalledTimes(1); expect(mockAdapter.elementContainsClass) .not.toHaveBeenCalledWith(jasmine.anything()); }); it('handleItemAction item action closes the menu', () => { const {foundation, mockAdapter} = setupTest(); const itemEl = document.createElement('li'); mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(0); foundation.handleItemAction(itemEl); expect(mockAdapter.closeSurface).toHaveBeenCalledTimes(1); }); it('handleItemAction item action emits selected event', () => { const {foundation, mockAdapter} = setupTest(); const itemEl = document.createElement('li'); mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(0); foundation.handleItemAction(itemEl); expect(mockAdapter.notifySelected).toHaveBeenCalledWith({index: 0}); expect(mockAdapter.notifySelected).toHaveBeenCalledTimes(1); }); it('handleKeydown space/enter key inside an input does not prevent default on the event', () => { const {foundation, mockAdapter} = setupTest(); const event = { key: 'Space', target: {tagName: 'input'}, preventDefault: jasmine.createSpy('preventDefault') } as unknown as KeyboardEvent; mockAdapter.elementContainsClass .withArgs(event.target, listClasses.LIST_ITEM_CLASS) .and.returnValue(true); mockAdapter.getElementIndex.withArgs(event.target).and.returnValue(0); foundation.handleKeydown(event); (event as any).key = 'Enter'; foundation.handleKeydown(event); expect(event.preventDefault).not.toHaveBeenCalled(); }); it('handleItemAction item action event inside of a selection group ' + 'with additional markup does not cause loop', () => { // This test will timeout of there is an endless loop in the selection // group logic. const {foundation, mockAdapter} = setupTest(); const itemEl = document.createElement('li'); mockAdapter.elementContainsClass .withArgs(itemEl, listClasses.LIST_ITEM_CLASS) .and.returnValue(true); mockAdapter.elementContainsClass .withArgs(jasmine.anything(), listClasses.ROOT) .and.returnValue(false); mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(0); mockAdapter.elementContainsClass .withArgs(jasmine.anything(), cssClasses.MENU_SELECTION_GROUP) .and.returnValue(false); foundation.handleItemAction(itemEl); jasmine.clock().tick(numbers.TRANSITION_CLOSE_DURATION); expect(mockAdapter.closeSurface).toHaveBeenCalledTimes(1); }); it('handleItemAction item action event inside of a selection group with another element selected', () => { const {foundation, mockAdapter} = setupTest(); const itemEl = document.createElement('li'); mockAdapter.elementContainsClass .withArgs(itemEl, listClasses.LIST_ITEM_CLASS) .and.returnValue(true); mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(0); mockAdapter.elementContainsClass .withArgs(itemEl, cssClasses.MENU_SELECTION_GROUP) .and.returnValue(true); mockAdapter.isSelectableItemAtIndex.withArgs(0).and.returnValue(true); mockAdapter.getSelectedSiblingOfItemAtIndex.withArgs(0).and.returnValue( 1); mockAdapter.getMenuItemCount.and.returnValue(5); foundation.handleItemAction(itemEl); jasmine.clock().tick(numbers.TRANSITION_CLOSE_DURATION); expect(mockAdapter.removeClassFromElementAtIndex) .toHaveBeenCalledWith(1, cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.removeClassFromElementAtIndex) .toHaveBeenCalledTimes(1); expect(mockAdapter.addClassToElementAtIndex) .toHaveBeenCalledWith(0, cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.addClassToElementAtIndex).toHaveBeenCalledTimes(1); }); it('handleItemAction item action event inside of a selection group with no element selected', () => { const {foundation, mockAdapter} = setupTest(); const itemEl = document.createElement('li'); mockAdapter.elementContainsClass .withArgs(itemEl, listClasses.LIST_ITEM_CLASS) .and.returnValue(true); mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(0); mockAdapter.elementContainsClass .withArgs(itemEl, cssClasses.MENU_SELECTION_GROUP) .and.returnValue(true); mockAdapter.isSelectableItemAtIndex.withArgs(0).and.returnValue(true); mockAdapter.getSelectedSiblingOfItemAtIndex.withArgs(0).and.returnValue( -1); mockAdapter.getMenuItemCount.and.returnValue(5); foundation.handleItemAction(itemEl); jasmine.clock().tick(numbers.TRANSITION_CLOSE_DURATION); expect(mockAdapter.removeClassFromElementAtIndex) .not.toHaveBeenCalledWith( jasmine.any(Number), cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.addClassToElementAtIndex) .toHaveBeenCalledWith(0, cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.addClassToElementAtIndex).toHaveBeenCalledTimes(1); }); it('handleItemAction item action event inside of a child element of a list item in a selection group with no ' + 'element selected', () => { const {foundation, mockAdapter} = setupTest(); const itemEl = document.createElement('li'); mockAdapter.elementContainsClass .withArgs(itemEl, listClasses.LIST_ITEM_CLASS) .and.returnValue(true); mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(0); mockAdapter.elementContainsClass .withArgs(itemEl, cssClasses.MENU_SELECTION_GROUP) .and.returnValues(false, true); mockAdapter.isSelectableItemAtIndex.withArgs(0).and.returnValue(true); mockAdapter.getMenuItemCount.and.returnValue(5); foundation.handleItemAction(itemEl); jasmine.clock().tick(numbers.TRANSITION_CLOSE_DURATION); expect(mockAdapter.removeClassFromElementAtIndex) .not.toHaveBeenCalledWith( jasmine.any(Number), cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.addClassToElementAtIndex) .toHaveBeenCalledWith(0, cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.addClassToElementAtIndex).toHaveBeenCalledTimes(1); }); it('handleItemAction item action event inside of a child element of a selection group (but not a list item) with ' + 'no element selected', () => { const {foundation, mockAdapter} = setupTest(); const itemEl = document.createElement('li'); mockAdapter.elementContainsClass .withArgs(itemEl, listClasses.LIST_ITEM_CLASS) .and.returnValue(true); mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(0); mockAdapter.elementContainsClass .withArgs(itemEl, cssClasses.MENU_SELECTION_GROUP) .and.returnValue(false); mockAdapter.elementContainsClass.withArgs(itemEl, listClasses.ROOT) .and.returnValues(false, true); mockAdapter.isSelectableItemAtIndex.withArgs(0).and.returnValue(false); mockAdapter.getMenuItemCount.and.returnValue(5); foundation.handleItemAction(itemEl); jasmine.clock().tick(numbers.TRANSITION_CLOSE_DURATION); expect(mockAdapter.removeClassFromElementAtIndex) .not.toHaveBeenCalledWith( jasmine.any(Number), cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.addClassToElementAtIndex) .not.toHaveBeenCalledWith( jasmine.any(Number), cssClasses.MENU_SELECTED_LIST_ITEM); }); it('handleItemAction adds class to the correct child element of a selection group when menu has mutated', () => { const {foundation, mockAdapter} = setupTest(); const itemEl = document.createElement('li'); mockAdapter.elementContainsClass .withArgs(itemEl, listClasses.LIST_ITEM_CLASS) .and.returnValue(true); mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(1); mockAdapter.elementContainsClass .withArgs(itemEl, cssClasses.MENU_SELECTION_GROUP) .and.returnValue(true); mockAdapter.isSelectableItemAtIndex.withArgs(1).and.returnValue(true); mockAdapter.getSelectedSiblingOfItemAtIndex.withArgs(1).and.returnValue( -1); mockAdapter.getMenuItemCount.and.returnValue(2); foundation.handleItemAction(itemEl); // Element at index 1 is now at index 0 mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(0); mockAdapter.isSelectableItemAtIndex.withArgs(0).and.returnValue(true); mockAdapter.getSelectedSiblingOfItemAtIndex.withArgs(0).and.returnValue( -1); mockAdapter.getMenuItemCount.and.returnValue(1); jasmine.clock().tick(numbers.TRANSITION_CLOSE_DURATION); expect(mockAdapter.addClassToElementAtIndex) .toHaveBeenCalledWith(0, cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.addClassToElementAtIndex).toHaveBeenCalledTimes(1); }); it('handleMenuSurfaceOpened menu focuses the list root element by default on menu surface opened', () => { const {foundation, mockAdapter} = setupTest(); foundation.handleMenuSurfaceOpened(); expect(mockAdapter.focusListRoot).toHaveBeenCalledTimes(1); }); it('handleMenuSurfaceOpened menu focuses the first menu item when DefaultFocusState is set to FIRST_ITEM on menu ' + 'surface opened', () => { const {foundation, mockAdapter} = setupTest(); foundation.setDefaultFocusState(DefaultFocusState.FIRST_ITEM); foundation.handleMenuSurfaceOpened(); expect(mockAdapter.focusItemAtIndex).toHaveBeenCalledWith(0); expect(mockAdapter.focusItemAtIndex).toHaveBeenCalledTimes(1); }); it('handleMenuSurfaceOpened focuses the list root element when DefaultFocusState is set to LIST_ROOT', () => { const {foundation, mockAdapter} = setupTest(); foundation.setDefaultFocusState(DefaultFocusState.LIST_ROOT); foundation.handleMenuSurfaceOpened(); expect(mockAdapter.focusListRoot).toHaveBeenCalledTimes(1); }); it('handleMenuSurfaceOpened focuses the last item when DefaultFocusState is set to LAST_ITEM', () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getMenuItemCount.and.returnValue(5); foundation.setDefaultFocusState(DefaultFocusState.LAST_ITEM); foundation.handleMenuSurfaceOpened(); expect(mockAdapter.focusItemAtIndex).toHaveBeenCalledWith(4); expect(mockAdapter.focusItemAtIndex).toHaveBeenCalledTimes(1); }); it('handleMenuSurfaceOpened does not focus anything when DefaultFocusState is set to NONE', () => { const {foundation, mockAdapter} = setupTest(); foundation.setDefaultFocusState(DefaultFocusState.NONE); foundation.handleMenuSurfaceOpened(); expect(mockAdapter.focusItemAtIndex) .not.toHaveBeenCalledWith(jasmine.anything()); expect(mockAdapter.focusListRoot).not.toHaveBeenCalled(); }); it('#getSelectedIndex returns correct index', () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.isSelectableItemAtIndex.withArgs(1).and.returnValue(true); const listItemEl = document.createElement('div'); mockAdapter.elementContainsClass .withArgs(listItemEl, cssClasses.MENU_SELECTION_GROUP) .and.returnValue(true); mockAdapter.getSelectedSiblingOfItemAtIndex.withArgs(1).and.returnValue(-1); mockAdapter.getMenuItemCount.and.returnValue(2); expect(foundation.getSelectedIndex()).not.toBe(1); foundation.setSelectedIndex(1); expect(foundation.getSelectedIndex()).toBe(1); }); it('setSelectedIndex calls addClass and addAttribute only', () => { const {foundation, mockAdapter} = setupTest(); const listItemEl = document.createElement('div'); mockAdapter.isSelectableItemAtIndex.withArgs(0).and.returnValue(true); mockAdapter.elementContainsClass .withArgs(listItemEl, cssClasses.MENU_SELECTION_GROUP) .and.returnValue(true); mockAdapter.getSelectedSiblingOfItemAtIndex.withArgs(0).and.returnValue(-1); mockAdapter.getMenuItemCount.and.returnValue(2); foundation.setSelectedIndex(0); expect(mockAdapter.removeClassFromElementAtIndex) .not.toHaveBeenCalledWith( jasmine.any(Number), cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.removeAttributeFromElementAtIndex) .not.toHaveBeenCalledWith(strings.ARIA_CHECKED_ATTR); expect(mockAdapter.addClassToElementAtIndex) .toHaveBeenCalledWith(0, cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.addAttributeToElementAtIndex) .toHaveBeenCalledWith(0, strings.ARIA_CHECKED_ATTR, 'true'); expect(mockAdapter.addAttributeToElementAtIndex).toHaveBeenCalledTimes(1); }); it('setSelectedIndex remove class and attribute, and adds class and attribute to newly selected item', () => { const {foundation, mockAdapter} = setupTest(); const listItemEl = document.createElement('div'); mockAdapter.isSelectableItemAtIndex.withArgs(0).and.returnValue(true); mockAdapter.elementContainsClass .withArgs(listItemEl, cssClasses.MENU_SELECTION_GROUP) .and.returnValue(true); mockAdapter.getMenuItemCount.and.returnValue(2); mockAdapter.getSelectedSiblingOfItemAtIndex.withArgs(0).and.returnValue( 1); foundation.setSelectedIndex(0); expect(mockAdapter.removeClassFromElementAtIndex) .toHaveBeenCalledWith(1, cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.removeClassFromElementAtIndex) .toHaveBeenCalledTimes(1); expect(mockAdapter.removeAttributeFromElementAtIndex) .toHaveBeenCalledWith(1, strings.ARIA_CHECKED_ATTR); expect(mockAdapter.removeAttributeFromElementAtIndex) .toHaveBeenCalledTimes(1); expect(mockAdapter.addClassToElementAtIndex) .toHaveBeenCalledWith(0, cssClasses.MENU_SELECTED_LIST_ITEM); expect(mockAdapter.addClassToElementAtIndex).toHaveBeenCalledTimes(1); expect(mockAdapter.addAttributeToElementAtIndex) .toHaveBeenCalledWith(0, strings.ARIA_CHECKED_ATTR, 'true'); expect(mockAdapter.addAttributeToElementAtIndex) .toHaveBeenCalledTimes(1); }); it('setSelectedIndex throws error if index is not in range', () => { const {foundation} = setupTest(); try { foundation.setSelectedIndex(5); } catch (e) { expect(e.message).toEqual( 'MDCMenuFoundation: No list item at specified index.'); } }); it('setEnabled calls addClass and addAttribute', () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getMenuItemCount.and.returnValue(2); foundation.setEnabled(0, false); expect(mockAdapter.addClassToElementAtIndex) .toHaveBeenCalledWith(0, listCssClasses.LIST_ITEM_DISABLED_CLASS); expect(mockAdapter.addClassToElementAtIndex).toHaveBeenCalledTimes(1); expect(mockAdapter.addAttributeToElementAtIndex) .toHaveBeenCalledWith(0, strings.ARIA_DISABLED_ATTR, 'true'); expect(mockAdapter.addAttributeToElementAtIndex).toHaveBeenCalledTimes(1); }); it('setEnabled calls removeClass and removeAttribute', () => { const {foundation, mockAdapter} = setupTest(); mockAdapter.getMenuItemCount.and.returnValue(2); foundation.setEnabled(0, true); expect(mockAdapter.removeClassFromElementAtIndex) .toHaveBeenCalledWith(0, listCssClasses.LIST_ITEM_DISABLED_CLASS); expect(mockAdapter.removeClassFromElementAtIndex).toHaveBeenCalledTimes(1); expect(mockAdapter.addAttributeToElementAtIndex) .toHaveBeenCalledWith(0, strings.ARIA_DISABLED_ATTR, 'false'); expect(mockAdapter.addAttributeToElementAtIndex).toHaveBeenCalledTimes(1); }); // Item Action it('Item action event causes the menu to close', () => { const {foundation, mockAdapter} = setupTest(); const itemEl = document.createElement('li'); mockAdapter.elementContainsClass .withArgs(itemEl, listClasses.LIST_ITEM_CLASS) .and.returnValue(true); mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(0); foundation.handleItemAction(itemEl); expect(mockAdapter.closeSurface).toHaveBeenCalledTimes(1); expect(mockAdapter.closeSurface).toHaveBeenCalledWith(false); }); it('closes the menu (with indication to not restore focus) on item action based on DOM attribute', () => { const {foundation, mockAdapter} = setupTest(); const itemEl = document.createElement('li'); mockAdapter.elementContainsClass .withArgs(itemEl, listClasses.LIST_ITEM_CLASS) .and.returnValue(true); mockAdapter.getElementIndex.withArgs(itemEl).and.returnValue(0); mockAdapter.getAttributeFromElementAtIndex .withArgs(0, strings.SKIP_RESTORE_FOCUS) .and.returnValue('true'); foundation.handleItemAction(itemEl); expect(mockAdapter.closeSurface).toHaveBeenCalledTimes(1); expect(mockAdapter.closeSurface).toHaveBeenCalledWith(true); }); });
the_stack
import { Event } from 'vs/base/common/event'; import { Registry } from 'vs/platform/registry/common/platform'; import { ResourceMap } from 'vs/base/common/map'; import { createDecorator, IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IEditorFactoryRegistry, IFileEditorInput, IUntypedEditorInput, IUntypedFileEditorInput, EditorExtensions, isResourceDiffEditorInput, isResourceSideBySideEditorInput, IUntitledTextResourceEditorInput, DEFAULT_EDITOR_ASSOCIATION } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { INewUntitledTextEditorOptions, IUntitledTextEditorService } from 'vs/workbench/services/untitled/common/untitledTextEditorService'; import { Schemas } from 'vs/base/common/network'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { SideBySideEditorInput } from 'vs/workbench/common/editor/sideBySideEditorInput'; import { TextResourceEditorInput } from 'vs/workbench/common/editor/textResourceEditorInput'; import { UntitledTextEditorInput } from 'vs/workbench/services/untitled/common/untitledTextEditorInput'; import { IUntitledTextEditorModel } from 'vs/workbench/services/untitled/common/untitledTextEditorModel'; import { basename } from 'vs/base/common/resources'; import { URI } from 'vs/base/common/uri'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { IFileService } from 'vs/platform/files/common/files'; import { IEditorResolverService, RegisteredEditorPriority } from 'vs/workbench/services/editor/common/editorResolverService'; import { Disposable } from 'vs/base/common/lifecycle'; import { registerSingleton } from 'vs/platform/instantiation/common/extensions'; export const ITextEditorService = createDecorator<ITextEditorService>('textEditorService'); export interface ITextEditorService { readonly _serviceBrand: undefined; /** * A way to create text editor inputs from an untyped editor input. Depending * on the passed in input this will be: * - a `IFileEditorInput` for file resources * - a `UntitledEditorInput` for untitled resources * - a `TextResourceEditorInput` for virtual resources * * @param input the untyped editor input to create a typed input from */ createTextEditor(input: IUntypedEditorInput): EditorInput; createTextEditor(input: IUntypedFileEditorInput): IFileEditorInput; } export class TextEditorService extends Disposable implements ITextEditorService { declare readonly _serviceBrand: undefined; private readonly editorInputCache = new ResourceMap<TextResourceEditorInput | IFileEditorInput | UntitledTextEditorInput>(); private readonly fileEditorFactory = Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).getFileEditorFactory(); constructor( @IUntitledTextEditorService private readonly untitledTextEditorService: IUntitledTextEditorService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService, @IFileService private readonly fileService: IFileService, @IEditorResolverService private readonly editorResolverService: IEditorResolverService ) { super(); // Register the default editor to the editor resolver // service so that it shows up in the editors picker this.registerDefaultEditor(); } private registerDefaultEditor(): void { this._register(this.editorResolverService.registerEditor( '*', { id: DEFAULT_EDITOR_ASSOCIATION.id, label: DEFAULT_EDITOR_ASSOCIATION.displayName, detail: DEFAULT_EDITOR_ASSOCIATION.providerDisplayName, priority: RegisteredEditorPriority.builtin }, {}, editor => ({ editor: this.createTextEditor(editor) }), untitledEditor => ({ editor: this.createTextEditor(untitledEditor) }), diffEditor => ({ editor: this.createTextEditor(diffEditor) }) )); } createTextEditor(input: IUntypedEditorInput): EditorInput; createTextEditor(input: IUntypedFileEditorInput): IFileEditorInput; createTextEditor(input: IUntypedEditorInput | IUntypedFileEditorInput): EditorInput | IFileEditorInput { // Diff Editor Support if (isResourceDiffEditorInput(input)) { const original = this.createTextEditor({ ...input.original }); const modified = this.createTextEditor({ ...input.modified }); return this.instantiationService.createInstance(DiffEditorInput, input.label, input.description, original, modified, undefined); } // Side by Side Editor Support if (isResourceSideBySideEditorInput(input)) { const primary = this.createTextEditor({ ...input.primary }); const secondary = this.createTextEditor({ ...input.secondary }); return this.instantiationService.createInstance(SideBySideEditorInput, input.label, input.description, secondary, primary); } // Untitled text file support const untitledInput = input as IUntitledTextResourceEditorInput; if (untitledInput.forceUntitled || !untitledInput.resource || (untitledInput.resource.scheme === Schemas.untitled)) { const untitledOptions: Partial<INewUntitledTextEditorOptions> = { languageId: untitledInput.languageId, initialValue: untitledInput.contents, encoding: untitledInput.encoding }; // Untitled resource: use as hint for an existing untitled editor let untitledModel: IUntitledTextEditorModel; if (untitledInput.resource?.scheme === Schemas.untitled) { untitledModel = this.untitledTextEditorService.create({ untitledResource: untitledInput.resource, ...untitledOptions }); } // Other resource: use as hint for associated filepath else { untitledModel = this.untitledTextEditorService.create({ associatedResource: untitledInput.resource, ...untitledOptions }); } return this.createOrGetCached(untitledModel.resource, () => { // Factory function for new untitled editor const input = this.instantiationService.createInstance(UntitledTextEditorInput, untitledModel); // We dispose the untitled model once the editor // is being disposed. Even though we may have not // created the model initially, the lifecycle for // untitled is tightly coupled with the editor // lifecycle for now. Event.once(input.onWillDispose)(() => untitledModel.dispose()); return input; }); } // Text File/Resource Editor Support const textResourceEditorInput = input as IUntypedFileEditorInput; if (textResourceEditorInput.resource instanceof URI) { // Derive the label from the path if not provided explicitly const label = textResourceEditorInput.label || basename(textResourceEditorInput.resource); // We keep track of the preferred resource this input is to be created // with but it may be different from the canonical resource (see below) const preferredResource = textResourceEditorInput.resource; // From this moment on, only operate on the canonical resource // to ensure we reduce the chance of opening the same resource // with different resource forms (e.g. path casing on Windows) const canonicalResource = this.uriIdentityService.asCanonicalUri(preferredResource); return this.createOrGetCached(canonicalResource, () => { // File if (textResourceEditorInput.forceFile || this.fileService.hasProvider(canonicalResource)) { return this.fileEditorFactory.createFileEditor(canonicalResource, preferredResource, textResourceEditorInput.label, textResourceEditorInput.description, textResourceEditorInput.encoding, textResourceEditorInput.languageId, textResourceEditorInput.contents, this.instantiationService); } // Resource return this.instantiationService.createInstance(TextResourceEditorInput, canonicalResource, textResourceEditorInput.label, textResourceEditorInput.description, textResourceEditorInput.languageId, textResourceEditorInput.contents); }, cachedInput => { // Untitled if (cachedInput instanceof UntitledTextEditorInput) { return; } // Files else if (!(cachedInput instanceof TextResourceEditorInput)) { cachedInput.setPreferredResource(preferredResource); if (textResourceEditorInput.label) { cachedInput.setPreferredName(textResourceEditorInput.label); } if (textResourceEditorInput.description) { cachedInput.setPreferredDescription(textResourceEditorInput.description); } if (textResourceEditorInput.encoding) { cachedInput.setPreferredEncoding(textResourceEditorInput.encoding); } if (textResourceEditorInput.languageId) { cachedInput.setPreferredLanguageId(textResourceEditorInput.languageId); } if (typeof textResourceEditorInput.contents === 'string') { cachedInput.setPreferredContents(textResourceEditorInput.contents); } } // Resources else { if (label) { cachedInput.setName(label); } if (textResourceEditorInput.description) { cachedInput.setDescription(textResourceEditorInput.description); } if (textResourceEditorInput.languageId) { cachedInput.setPreferredLanguageId(textResourceEditorInput.languageId); } if (typeof textResourceEditorInput.contents === 'string') { cachedInput.setPreferredContents(textResourceEditorInput.contents); } } }); } throw new Error(`ITextEditorService: Unable to create texteditor from ${JSON.stringify(input)}`); } private createOrGetCached( resource: URI, factoryFn: () => TextResourceEditorInput | IFileEditorInput | UntitledTextEditorInput, cachedFn?: (input: TextResourceEditorInput | IFileEditorInput | UntitledTextEditorInput) => void ): TextResourceEditorInput | IFileEditorInput | UntitledTextEditorInput { // Return early if already cached let input = this.editorInputCache.get(resource); if (input) { cachedFn?.(input); return input; } // Otherwise create and add to cache input = factoryFn(); this.editorInputCache.set(resource, input); Event.once(input.onWillDispose)(() => this.editorInputCache.delete(resource)); return input; } } registerSingleton(ITextEditorService, TextEditorService, false /* do not change: https://github.com/microsoft/vscode/issues/137675 */);
the_stack
import { HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Actions, Effect, ofType } from '@ngrx/effects'; import { B2BApprovalProcess, B2BUnit, B2BUser, EntitiesModel, normalizeHttpError, StateUtils, } from '@spartacus/core'; import { from, Observable, of } from 'rxjs'; import { catchError, groupBy, map, mergeMap, switchMap } from 'rxjs/operators'; import { OrgUnitConnector } from '../../connectors/org-unit/org-unit.connector'; import { B2BUnitNode } from '../../model/unit-node.model'; import { B2BUserActions, OrganizationActions, OrgUnitActions, } from '../actions/index'; @Injectable() export class OrgUnitEffects { @Effect() loadOrgUnit$: Observable< | OrgUnitActions.LoadOrgUnitSuccess | OrgUnitActions.LoadAddressSuccess | OrgUnitActions.LoadAddressesSuccess | OrgUnitActions.LoadOrgUnitFail > = this.actions$.pipe( ofType(OrgUnitActions.LOAD_ORG_UNIT), map((action: OrgUnitActions.LoadOrgUnit) => action.payload), switchMap(({ userId, orgUnitId }) => { return this.orgUnitConnector.get(userId, orgUnitId).pipe( switchMap((orgUnit: B2BUnit) => { const { values, page } = StateUtils.normalizeListPage( { values: orgUnit.addresses }, 'id' ); return [ new OrgUnitActions.LoadOrgUnitSuccess([orgUnit]), new OrgUnitActions.LoadAddressSuccess(values), new OrgUnitActions.LoadAddressesSuccess({ page, orgUnitId }), ]; }), catchError((error: HttpErrorResponse) => of( new OrgUnitActions.LoadOrgUnitFail({ orgUnitId, error: normalizeHttpError(error), }) ) ) ); }) ); @Effect() loadAvailableOrgUnits$: Observable< OrgUnitActions.LoadOrgUnitNodesSuccess | OrgUnitActions.LoadOrgUnitNodesFail > = this.actions$.pipe( ofType(OrgUnitActions.LOAD_UNIT_NODES), map((action: OrgUnitActions.LoadOrgUnitNodes) => action.payload), switchMap((payload) => this.orgUnitConnector.getList(payload.userId).pipe( map( (orgUnitsList: B2BUnitNode[]) => new OrgUnitActions.LoadOrgUnitNodesSuccess(orgUnitsList) ), catchError((error: HttpErrorResponse) => of( new OrgUnitActions.LoadOrgUnitNodesFail({ error: normalizeHttpError(error), }) ) ) ) ) ); @Effect() createUnit$: Observable< | OrgUnitActions.CreateUnitFail | OrgUnitActions.CreateUnitSuccess | OrganizationActions.OrganizationClearData > = this.actions$.pipe( ofType(OrgUnitActions.CREATE_ORG_UNIT), map((action: OrgUnitActions.CreateUnit) => action.payload), switchMap((payload) => this.orgUnitConnector.create(payload.userId, payload.unit).pipe( switchMap((data) => [ new OrgUnitActions.CreateUnitSuccess(data), new OrganizationActions.OrganizationClearData(), ]), catchError((error: HttpErrorResponse) => from([ new OrgUnitActions.CreateUnitFail({ unitCode: payload.unit.uid, error: normalizeHttpError(error), }), new OrganizationActions.OrganizationClearData(), ]) ) ) ) ); @Effect() updateUnit$: Observable< | OrgUnitActions.UpdateUnitSuccess | OrgUnitActions.UpdateUnitFail | OrganizationActions.OrganizationClearData > = this.actions$.pipe( ofType(OrgUnitActions.UPDATE_ORG_UNIT), map((action: OrgUnitActions.UpdateUnit) => action.payload), switchMap((payload) => this.orgUnitConnector .update(payload.userId, payload.unitCode, payload.unit) .pipe( switchMap((_data) => [ // Workaround for empty response new OrgUnitActions.UpdateUnitSuccess(payload.unit), new OrganizationActions.OrganizationClearData(), ]), catchError((error: HttpErrorResponse) => from([ new OrgUnitActions.UpdateUnitFail({ unitCode: payload.unit.uid, error: normalizeHttpError(error), }), new OrganizationActions.OrganizationClearData(), ]) ) ) ) ); @Effect() loadTree$: Observable< OrgUnitActions.LoadTreeSuccess | OrgUnitActions.LoadTreeFail > = this.actions$.pipe( ofType(OrgUnitActions.LOAD_UNIT_TREE), map((action: OrgUnitActions.LoadOrgUnit) => action.payload), switchMap(({ userId }) => { return this.orgUnitConnector.getTree(userId).pipe( map( (orgUnit: B2BUnitNode) => new OrgUnitActions.LoadTreeSuccess(orgUnit) ), catchError((error: HttpErrorResponse) => of( new OrgUnitActions.LoadTreeFail({ error: normalizeHttpError(error), }) ) ) ); }) ); @Effect() loadApprovalProcesses$: Observable< | OrgUnitActions.LoadApprovalProcessesSuccess | OrgUnitActions.LoadApprovalProcessesFail > = this.actions$.pipe( ofType(OrgUnitActions.LOAD_APPROVAL_PROCESSES), map((action: OrgUnitActions.LoadOrgUnit) => action.payload), switchMap(({ userId }) => { return this.orgUnitConnector.getApprovalProcesses(userId).pipe( map( (approvalProcesses: B2BApprovalProcess[]) => new OrgUnitActions.LoadApprovalProcessesSuccess(approvalProcesses) ), catchError((error: HttpErrorResponse) => of( new OrgUnitActions.LoadApprovalProcessesFail({ error: normalizeHttpError(error), }) ) ) ); }) ); @Effect() loadUsers$: Observable< | OrgUnitActions.LoadAssignedUsersSuccess | OrgUnitActions.LoadAssignedUsersFail | B2BUserActions.LoadB2BUserSuccess > = this.actions$.pipe( ofType(OrgUnitActions.LOAD_ASSIGNED_USERS), map((action: OrgUnitActions.LoadAssignedUsers) => action.payload), groupBy(({ orgUnitId, roleId, params }) => StateUtils.serializeParams([orgUnitId, roleId], params) ), mergeMap((group) => group.pipe( switchMap(({ userId, orgUnitId, roleId, params }) => { return this.orgUnitConnector .getUsers(userId, orgUnitId, roleId, params) .pipe( switchMap((users: EntitiesModel<B2BUser>) => { const { values, page } = StateUtils.normalizeListPage( users, 'customerId' ); return [ new B2BUserActions.LoadB2BUserSuccess(values), new OrgUnitActions.LoadAssignedUsersSuccess({ orgUnitId, roleId, page, params, }), ]; }), catchError((error: HttpErrorResponse) => of( new OrgUnitActions.LoadAssignedUsersFail({ orgUnitId, roleId, params, error: normalizeHttpError(error), }) ) ) ); }) ) ) ); @Effect() assignRoleToUser: Observable< OrgUnitActions.AssignRoleSuccess | OrgUnitActions.AssignRoleFail > = this.actions$.pipe( ofType(OrgUnitActions.ASSIGN_ROLE), map((action: OrgUnitActions.AssignRole) => action.payload), switchMap(({ userId, orgCustomerId, roleId }) => this.orgUnitConnector.assignRole(userId, orgCustomerId, roleId).pipe( map( () => new OrgUnitActions.AssignRoleSuccess({ uid: orgCustomerId, roleId, selected: true, }) ), catchError((error: HttpErrorResponse) => of( new OrgUnitActions.AssignRoleFail({ orgCustomerId, error: normalizeHttpError(error), }) ) ) ) ) ); @Effect() unassignRoleToUser$: Observable< OrgUnitActions.UnassignRoleSuccess | OrgUnitActions.UnassignRoleFail > = this.actions$.pipe( ofType(OrgUnitActions.UNASSIGN_ROLE), map((action: OrgUnitActions.UnassignRole) => action.payload), switchMap(({ userId, orgCustomerId, roleId }) => this.orgUnitConnector.unassignRole(userId, orgCustomerId, roleId).pipe( map( () => new OrgUnitActions.UnassignRoleSuccess({ uid: orgCustomerId, roleId, selected: false, }) ), catchError((error: HttpErrorResponse) => of( new OrgUnitActions.UnassignRoleFail({ orgCustomerId, error: normalizeHttpError(error), }) ) ) ) ) ); @Effect() assignApprover: Observable< | OrgUnitActions.AssignApproverSuccess | OrgUnitActions.AssignApproverFail | OrganizationActions.OrganizationClearData > = this.actions$.pipe( ofType(OrgUnitActions.ASSIGN_APPROVER), map((action: OrgUnitActions.AssignApprover) => action.payload), mergeMap(({ userId, orgUnitId, orgCustomerId, roleId }) => this.orgUnitConnector .assignApprover(userId, orgUnitId, orgCustomerId, roleId) .pipe( switchMap(() => [ new OrgUnitActions.AssignApproverSuccess({ uid: orgCustomerId, roleId, selected: true, }), new OrganizationActions.OrganizationClearData(), ]), catchError((error: HttpErrorResponse) => from([ new OrgUnitActions.AssignApproverFail({ orgCustomerId, error: normalizeHttpError(error), }), new OrganizationActions.OrganizationClearData(), ]) ) ) ) ); @Effect() unassignApprover: Observable< | OrgUnitActions.UnassignApproverSuccess | OrgUnitActions.UnassignApproverFail | OrganizationActions.OrganizationClearData > = this.actions$.pipe( ofType(OrgUnitActions.UNASSIGN_APPROVER), map((action: OrgUnitActions.UnassignApprover) => action.payload), mergeMap(({ userId, orgUnitId, orgCustomerId, roleId }) => this.orgUnitConnector .unassignApprover(userId, orgUnitId, orgCustomerId, roleId) .pipe( switchMap(() => [ new OrgUnitActions.UnassignApproverSuccess({ uid: orgCustomerId, roleId, selected: false, }), new OrganizationActions.OrganizationClearData(), ]), catchError((error: HttpErrorResponse) => from([ new OrgUnitActions.UnassignApproverFail({ orgCustomerId, error: normalizeHttpError(error), }), new OrganizationActions.OrganizationClearData(), ]) ) ) ) ); @Effect() createAddress$: Observable< | OrgUnitActions.CreateAddressSuccess | OrgUnitActions.CreateAddressFail | OrganizationActions.OrganizationClearData > = this.actions$.pipe( ofType(OrgUnitActions.CREATE_ADDRESS), map((action: OrgUnitActions.CreateAddress) => action.payload), switchMap((payload) => this.orgUnitConnector .createAddress(payload.userId, payload.orgUnitId, payload.address) .pipe( switchMap((data) => [ new OrgUnitActions.CreateAddressSuccess(data), new OrgUnitActions.CreateAddressSuccess({ id: null }), new OrganizationActions.OrganizationClearData(), ]), catchError((error: HttpErrorResponse) => from([ new OrgUnitActions.CreateAddressFail({ addressId: payload.address.id, error: normalizeHttpError(error), }), new OrganizationActions.OrganizationClearData(), ]) ) ) ) ); @Effect() updateAddress$: Observable< | OrgUnitActions.UpdateAddressSuccess | OrgUnitActions.UpdateAddressFail | OrganizationActions.OrganizationClearData > = this.actions$.pipe( ofType(OrgUnitActions.UPDATE_ADDRESS), map((action: OrgUnitActions.UpdateAddress) => action.payload), switchMap(({ userId, orgUnitId, addressId, address }) => this.orgUnitConnector .updateAddress(userId, orgUnitId, addressId, address) .pipe( switchMap(() => [ // commented out due to no response from backend on PATCH request // new OrgUnitActions.UpdateAddressSuccess(data), new OrgUnitActions.UpdateAddressSuccess(address), new OrganizationActions.OrganizationClearData(), ]), catchError((error: HttpErrorResponse) => from([ new OrgUnitActions.UpdateAddressFail({ addressId: address.id, error: normalizeHttpError(error), }), new OrganizationActions.OrganizationClearData(), ]) ) ) ) ); @Effect() deleteAddress$: Observable< | OrgUnitActions.DeleteAddressSuccess | OrgUnitActions.DeleteAddressFail | OrganizationActions.OrganizationClearData > = this.actions$.pipe( ofType(OrgUnitActions.DELETE_ADDRESS), map((action: OrgUnitActions.DeleteAddress) => action.payload), switchMap((payload) => this.orgUnitConnector .deleteAddress(payload.userId, payload.orgUnitId, payload.addressId) .pipe( switchMap(() => [ new OrgUnitActions.DeleteAddressSuccess({ id: payload.addressId }), new OrganizationActions.OrganizationClearData(), ]), catchError((error: HttpErrorResponse) => from([ new OrgUnitActions.DeleteAddressFail({ addressId: payload.addressId, error: normalizeHttpError(error), }), new OrganizationActions.OrganizationClearData(), ]) ) ) ) ); // @Effect() // loadAddress$: Observable< // | OrgUnitActions.LoadAddressSuccess // | OrgUnitActions.LoadAddressesSuccess // | OrgUnitActions.LoadAddressesFail // > = this.actions$.pipe( // ofType(OrgUnitActions.LOAD_ADDRESSES), // map((action: OrgUnitActions.LoadAddresses) => action.payload), // switchMap(({ userId, orgUnitId }) => { // return this.orgUnitConnector.getAddresses(userId, orgUnitId).pipe( // switchMap((addresses: EntitiesModel<B2BAddress>) => { // const { values, page } = StateUtils.normalizeListPage(addresses, 'id'); // return [ // new OrgUnitActions.LoadAddressSuccess(values), // new OrgUnitActions.LoadAddressesSuccess({ page, orgUnitId }), // ]; // }), // catchError(error => // of( // new OrgUnitActions.LoadAddressesFail({ // orgUnitId, // error: normalizeHttpError(error), // }) // ) // ) // ); // }) // ); constructor( private actions$: Actions, private orgUnitConnector: OrgUnitConnector ) {} }
the_stack
import {Rank, Tensor, Tensor3D, Tensor4D, Tensor5D} from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import * as tfOps from '@tensorflow/tfjs-core/dist/ops/ops_for_converter'; import {NamedTensorsMap} from '../../data/types'; import {ExecutionContext} from '../../executor/execution_context'; import {InternalOpExecutor, Node} from '../types'; import {getPadding, getParamValue} from './utils'; function fusedConvAndDepthWiseParams( node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext) { const [extraOp, activationFunc] = (getParamValue('fusedOps', node, tensorMap, context) as string[]); const isBiasAdd = extraOp === 'biasadd'; const noBiasAdd = !isBiasAdd; const isPrelu = activationFunc === 'prelu'; const isBatchNorm = extraOp === 'fusedbatchnorm'; const numArgs = (getParamValue('numArgs', node, tensorMap, context) as number); if (isBiasAdd) { if (isPrelu && numArgs !== 2) { throw new Error( 'FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu ' + 'must have two extra arguments: bias and alpha.'); } if (!isPrelu && isBiasAdd && numArgs !== 1) { throw new Error( 'FusedConv2d and DepthwiseConv2d with BiasAdd must have ' + 'one extra argument: bias.'); } } if (isBatchNorm) { throw new Error( 'FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported'); } const stride = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getPadding(node, tensorMap, context); const dataFormat = (getParamValue('dataFormat', node, tensorMap, context) as string) .toUpperCase(); const dilations = getParamValue('dilations', node, tensorMap, context) as number[]; let [biasArg, preluArg] = getParamValue('args', node, tensorMap, context) as Tensor[]; if (noBiasAdd) { preluArg = biasArg; biasArg = undefined; } const leakyreluAlpha = getParamValue('leakyreluAlpha', node, tensorMap, context) as number; return { stride, pad, dataFormat, dilations, biasArg, preluArg, activationFunc, leakyreluAlpha }; } export const executeOp: InternalOpExecutor = (node: Node, tensorMap: NamedTensorsMap, context: ExecutionContext): Tensor[] => { switch (node.op) { case 'Conv1D': { const stride = getParamValue('stride', node, tensorMap, context) as number; const pad = getParamValue('pad', node, tensorMap, context); const dataFormat = (getParamValue('dataFormat', node, tensorMap, context) as string) .toUpperCase(); const dilation = getParamValue('dilation', node, tensorMap, context) as number; return [tfOps.conv1d( getParamValue('x', node, tensorMap, context) as Tensor3D, getParamValue('filter', node, tensorMap, context) as Tensor3D, stride, pad as 'valid' | 'same', dataFormat as 'NWC' | 'NCW', dilation)]; } case 'Conv2D': { const stride = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getPadding(node, tensorMap, context); const dataFormat = (getParamValue('dataFormat', node, tensorMap, context) as string) .toUpperCase(); const dilations = getParamValue('dilations', node, tensorMap, context) as number[]; return [tfOps.conv2d( getParamValue('x', node, tensorMap, context) as Tensor3D | Tensor4D, getParamValue('filter', node, tensorMap, context) as Tensor4D, [stride[1], stride[2]], pad as 'valid' | 'same', dataFormat as 'NHWC' | 'NCHW', [dilations[1], dilations[2]])]; } case '_FusedConv2D': { const { stride, pad, dataFormat, dilations, biasArg, preluArg, activationFunc, leakyreluAlpha } = fusedConvAndDepthWiseParams(node, tensorMap, context); return [tfOps.fused.conv2d({ x: getParamValue('x', node, tensorMap, context) as Tensor3D | Tensor4D, filter: getParamValue('filter', node, tensorMap, context) as Tensor4D, strides: [stride[1], stride[2]], pad: pad as 'valid' | 'same', dataFormat: dataFormat as 'NHWC' | 'NCHW', dilations: [dilations[1], dilations[2]], bias: biasArg, activation: activationFunc as tfOps.fused.Activation, preluActivationWeights: preluArg, leakyreluAlpha })]; } case 'FusedDepthwiseConv2dNative': { const { stride, pad, dataFormat, dilations, biasArg, preluArg, activationFunc, leakyreluAlpha, } = fusedConvAndDepthWiseParams(node, tensorMap, context); return [tfOps.fused.depthwiseConv2d({ x: getParamValue('x', node, tensorMap, context) as Tensor3D | Tensor4D, filter: getParamValue('filter', node, tensorMap, context) as Tensor4D, strides: [stride[1], stride[2]], pad: pad as 'valid' | 'same', dataFormat: dataFormat as 'NHWC' | 'NCHW', dilations: [dilations[1], dilations[2]], bias: biasArg, activation: activationFunc as tfOps.fused.Activation, preluActivationWeights: preluArg, leakyreluAlpha })]; } case 'Conv2DBackpropInput': case 'Conv2dTranspose': { const shape = getParamValue( 'outputShape', node, tensorMap, context) as [number, number, number] | [number, number, number, number]; const stride = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getPadding(node, tensorMap, context); return [tfOps.conv2dTranspose( getParamValue('x', node, tensorMap, context) as Tensor3D | Tensor4D, getParamValue('filter', node, tensorMap, context) as Tensor4D, shape, [stride[1], stride[2]], pad as 'valid' | 'same')]; } case 'DepthwiseConv2dNative': case 'DepthwiseConv2d': { const stride = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getPadding(node, tensorMap, context); const dilations = getParamValue('dilations', node, tensorMap, context) as number[]; const dataFormat = (getParamValue('dataFormat', node, tensorMap, context) as string) .toUpperCase(); return [tfOps.depthwiseConv2d( getParamValue('input', node, tensorMap, context) as Tensor3D | Tensor4D, getParamValue('filter', node, tensorMap, context) as Tensor4D, [stride[1], stride[2]], pad as 'valid' | 'same', dataFormat as 'NHWC' | 'NCHW', [dilations[1], dilations[2]])]; } case 'Conv3D': { const stride = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getParamValue('pad', node, tensorMap, context); const dataFormat = (getParamValue('dataFormat', node, tensorMap, context) as string) .toUpperCase(); const dilations = getParamValue('dilations', node, tensorMap, context) as number[]; return [tfOps.conv3d( getParamValue('x', node, tensorMap, context) as Tensor4D | Tensor<Rank.R5>, getParamValue('filter', node, tensorMap, context) as Tensor<Rank.R5>, [stride[1], stride[2], stride[3]], pad as 'valid' | 'same', dataFormat as 'NDHWC' | 'NCDHW', [dilations[1], dilations[2], dilations[3]])]; } case 'AvgPool': { const stride = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getParamValue('pad', node, tensorMap, context); const kernelSize = getParamValue('kernelSize', node, tensorMap, context) as number[]; return [tfOps.avgPool( getParamValue('x', node, tensorMap, context) as Tensor3D | Tensor4D, [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad as 'valid' | 'same')]; } case 'MaxPool': { const stride = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getParamValue('pad', node, tensorMap, context); const kernelSize = getParamValue('kernelSize', node, tensorMap, context) as number[]; return [tfOps.maxPool( getParamValue('x', node, tensorMap, context) as Tensor3D | Tensor4D, [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad as 'valid' | 'same')]; } case 'MaxPoolWithArgmax': { const stride = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getParamValue('pad', node, tensorMap, context); const kernelSize = getParamValue('kernelSize', node, tensorMap, context) as number[]; const includeBatchInIndex = getParamValue('includeBatchInIndex', node, tensorMap, context) as boolean; const {result, indexes} = tfOps.maxPoolWithArgmax( getParamValue('x', node, tensorMap, context) as Tensor4D, [kernelSize[1], kernelSize[2]], [stride[1], stride[2]], pad as 'valid' | 'same', includeBatchInIndex); return [result, indexes]; } case 'AvgPool3D': { const stride = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getParamValue('pad', node, tensorMap, context); const kernelSize = getParamValue('kernelSize', node, tensorMap, context) as number[]; return [tfOps.avgPool3d( getParamValue('x', node, tensorMap, context) as Tensor5D, [kernelSize[1], kernelSize[2], kernelSize[3]], [stride[1], stride[2], stride[3]], pad as 'valid' | 'same')]; } case 'MaxPool3D': { const stride = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getParamValue('pad', node, tensorMap, context); const kernelSize = getParamValue('kernelSize', node, tensorMap, context) as number[]; return [tfOps.maxPool3d( getParamValue('x', node, tensorMap, context) as Tensor5D, [kernelSize[1], kernelSize[2], kernelSize[3]], [stride[1], stride[2], stride[3]], pad as 'valid' | 'same')]; } case 'Dilation2D': { const strides = getParamValue('strides', node, tensorMap, context) as number[]; const pad = getParamValue('pad', node, tensorMap, context); const dilations = getParamValue('dilations', node, tensorMap, context) as number[]; // strides: [1, stride_height, stride_width, 1]. const strideHeight = strides[1]; const strideWidth = strides[2]; // dilations: [1, dilation_height, dilation_width, 1]. const dilationHeight = dilations[1]; const dilationWidth = dilations[2]; return [tfOps.dilation2d( getParamValue('x', node, tensorMap, context) as Tensor3D | Tensor4D, getParamValue('filter', node, tensorMap, context) as Tensor3D, [strideHeight, strideWidth], pad as 'valid' | 'same', [dilationHeight, dilationWidth], 'NHWC' /* dataFormat */)]; } default: throw TypeError(`Node type ${node.op} is not implemented`); } }; export const CATEGORY = 'convolution';
the_stack
import path from 'path'; import fs from 'fs-extra'; import { loggerSpy } from '../testhelpers/loggerSpy'; import { importConfiguration, YAMLConfiguration } from '../../src/import'; import { Configuration } from '../../src/fshtypes'; describe('importConfiguration', () => { let minYAML: YAMLConfiguration; beforeEach(() => { minYAML = { id: 'fhir.us.minimal', canonical: 'http://hl7.org/fhir/us/minimal', name: 'MinimalIG', status: 'draft', version: '1.0.0', fhirVersion: ['4.0.1'], copyrightYear: '2020+', releaseLabel: 'Build CI', template: 'hl7.fhir.template#0.0.5' }; loggerSpy.reset(); }); it('should import minimal config', () => { const yamlPath = path.join(__dirname, 'fixtures', 'minimal-config.yaml'); const yaml = fs.readFileSync(yamlPath, 'utf8'); const actual = importConfiguration(yaml, yamlPath); const expected: Configuration = { filePath: yamlPath, id: 'fhir.us.minimal', canonical: 'http://hl7.org/fhir/us/minimal', url: 'http://hl7.org/fhir/us/minimal/ImplementationGuide/fhir.us.minimal', name: 'MinimalIG', status: 'draft', version: '1.0.0', fhirVersion: ['4.0.1'], parameters: [ { code: 'copyrightyear', value: '2020+' }, { code: 'releaselabel', value: 'Build CI' } ], packageId: 'fhir.us.minimal', FSHOnly: false, applyExtensionMetadataToRoot: true, instanceOptions: { setMetaProfile: 'always', setId: 'always' } }; expect(actual).toEqual(expected); expect(loggerSpy.getAllLogs('error')).toHaveLength(0); }); it('should import example config', () => { const yamlPath = path.join(__dirname, 'fixtures', 'example-config.yaml'); const yaml = fs.readFileSync(yamlPath, 'utf8'); const actual = importConfiguration(yaml, yamlPath); const expected: Configuration = { filePath: yamlPath, id: 'fhir.us.example', canonical: 'http://hl7.org/fhir/us/example', url: 'http://hl7.org/fhir/us/example/ImplementationGuide/fhir.us.example', name: 'ExampleIG', title: 'HL7 FHIR Implementation Guide: Example IG Release 1 - US Realm | STU1', description: 'Example IG exercises many of the fields in a SUSHI configuration.', status: 'active', packageId: 'fhir.us.example', license: 'CC0-1.0', date: '2020-02-26', version: '1.0.0', fhirVersion: ['4.0.1'], template: 'hl7.fhir.template#0.0.5', publisher: 'HL7 FHIR Management Group', contact: [ { name: 'HL7 FHIR Management Group', telecom: [ { system: 'url', value: 'http://www.hl7.org/Special/committees/fhirmg' }, { system: 'email', value: 'fmg@lists.HL7.org' } ] }, { name: 'Bob Smith', telecom: [{ system: 'email', value: 'bobsmith@example.org', use: 'work' }] } ], jurisdiction: [ { coding: [ { code: 'US', system: 'urn:iso:std:iso:3166', display: 'United States of America' } ] } ], dependencies: [ { packageId: 'hl7.fhir.us.core', version: '3.1.0' }, { id: 'mcode', packageId: 'hl7.fhir.us.mcode', uri: 'http://hl7.org/fhir/us/mcode/ImplementationGuide/hl7.fhir.us.mcode', version: '1.0.0' } ], global: [ { type: 'Patient', profile: 'http://example.org/fhir/StructureDefinition/my-patient-profile' }, { type: 'Encounter', profile: 'http://example.org/fhir/StructureDefinition/my-encounter-profile' } ], resources: [ { reference: { reference: 'Patient/my-example-patient' }, name: 'My Example Patient', description: 'An example Patient', exampleBoolean: true }, { reference: { reference: 'Patient/bad-example' }, omit: true } ], groups: [ { id: 'GroupA', name: 'Group A', description: 'The Alpha Group', resources: ['StructureDefinition/animal-patient', 'StructureDefinition/arm-procedure'] }, { id: 'GroupB', name: 'Group B', description: 'The Beta Group', resources: ['StructureDefinition/bark-control', 'StructureDefinition/bee-sting'] } ], pages: [ { nameUrl: 'index.md', title: 'Example Home' }, { nameUrl: 'implementation.xml' }, { nameUrl: 'examples.xml', title: 'Examples Overview', page: [{ nameUrl: 'simpleExamples.xml' }, { nameUrl: 'complexExamples.xml' }] } ], menu: [ { name: 'Home', url: 'index.html' }, { name: 'Artifacts', subMenu: [ { name: 'Profiles', url: 'artifacts.html#2' }, { name: 'Extensions', url: 'artifacts.html#3' }, { name: 'Value Sets', url: 'artifacts.html#4' } ] }, { name: 'Downloads', url: 'downloads.html' }, { name: 'History', url: 'http://hl7.org/fhir/us/example/history.html' }, { name: 'FHIR Spec', url: 'http://hl7.org/fhir/R4/index.html', openInNewTab: true } ], parameters: [ { code: 'copyrightyear', value: '2019+' }, { code: 'releaselabel', value: 'STU1' }, { code: 'excludettl', value: 'true' }, { code: 'validation', value: 'allow-any-extensions' }, { code: 'validation', value: 'no-broken-links' } ], history: { 'package-id': 'fhir.us.example', canonical: 'http://hl7.org/fhir/us/example', title: 'HL7 FHIR Implementation Guide: Example IG Release 1 - US Realm | STU1', introduction: 'Example IG exercises many of the fields in a SUSHI configuration.', list: [ { version: 'current', desc: 'Continuous Integration Build (latest in version control)', path: 'https://build.fhir.org/ig/HL7/example-ig/', status: 'ci-build', current: true }, { version: '1.0.0', fhirversion: '4.0.1', date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', sequence: 'STU 1', current: true }, { version: '0.9.1', fhirversion: '4.0.0', date: '2019-06-10', desc: 'Initial STU ballot (Sep 2019 Ballot)', path: 'https://hl7.org/fhir/us/example/2019Sep/', status: 'ballot', sequence: 'STU 1' } ] }, indexPageContent: 'Example Index Page Content', FSHOnly: false, applyExtensionMetadataToRoot: true, instanceOptions: { setMetaProfile: 'always', setId: 'always' } }; expect(actual).toEqual(expected); expect(loggerSpy.getAllLogs('error')).toHaveLength(0); }); it('should report an error and throw on an invalid YAML config', () => { expect(() => importConfiguration('foo', 'foo-config.yaml')).toThrow( 'Invalid configuration YAML' ); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration is not a valid YAML object\.\s*File: foo-config\.yaml/ ); }); it('should report an error and throw on a YAML file with invalid entries', () => { const yamlPath = path.join(__dirname, 'fixtures', 'invalid-config.yaml'); const invalidYaml = fs.readFileSync(yamlPath, 'utf8'); expect(() => importConfiguration(invalidYaml, 'invalid-config.yaml')).toThrow( 'Invalid configuration YAML' ); expect(loggerSpy.getLastMessage('error')).toMatch( /Error parsing configuration: Map keys must be unique; "releaseLabel" is repeated\.\s*File: invalid-config\.yaml/ ); }); describe('#id', () => { it('should import id as-is', () => { minYAML.id = 'my-id'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.id).toBe('my-id'); }); it('should report an error and throw if id is missing when FSHOnly is false', () => { delete minYAML.id; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to generate an IG: canonical, fhirVersion, id, name, status, copyrightYear, releaseLabel\.\s*File: test-config\.yaml/ ); }); it('should not report an error and throw if id is missing when FSHOnly is true', () => { delete minYAML.id; minYAML.FSHOnly = true; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.id).toBeUndefined(); }); }); describe('#meta', () => { it('should support fhir syntax for meta coded properties', () => { minYAML.meta = { security: [{ system: 'http://foo.org', code: 'bar', display: 'FooBar' }], tag: [{ system: 'http://foo.org', code: 'baz', display: 'FooBaz' }] }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.meta).toEqual({ security: [{ system: 'http://foo.org', code: 'bar', display: 'FooBar' }], tag: [{ system: 'http://foo.org', code: 'baz', display: 'FooBaz' }] }); }); it('should support FSH syntax for meta coded properties', () => { minYAML.meta = { security: ['http://foo.org#bar "FooBar"'], tag: ['http://foo.org#baz "FooBaz"'] }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.meta).toEqual({ security: [{ system: 'http://foo.org', code: 'bar', display: 'FooBar' }], tag: [{ system: 'http://foo.org', code: 'baz', display: 'FooBaz' }] }); }); it('should report invalid FSH syntax for meta coded properties', () => { minYAML.meta = { security: ['foobar'], tag: ['foobaz'] }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getMessageAtIndex(-2, 'error')).toMatch( /Invalid code format for meta\.security: foobar\s*File: test-config\.yaml/ ); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid code format for meta\.tag: foobaz\s*File: test-config\.yaml/ ); expect(config.meta).toEqual({}); }); }); describe('#implicitRules', () => { it('should import implicitRules as-is', () => { minYAML.implicitRules = 'http://foo.org/bar'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.implicitRules).toBe('http://foo.org/bar'); }); }); describe('#language', () => { it('should support string for language', () => { minYAML.language = 'en'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.language).toBe('en'); }); it('should support code syntax for language', () => { minYAML.language = '#en'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.language).toBe('en'); }); }); describe('#text', () => { it('should support fhir syntax for text.status', () => { minYAML.text = { status: 'empty', div: '<div></div>' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.text).toEqual({ status: 'empty', div: '<div></div>' }); }); it('should support FSH syntax for text.status', () => { minYAML.text = { status: '#empty', div: '<div></div>' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.text).toEqual({ status: 'empty', div: '<div></div>' }); }); it('should report invalid text.status code', () => { minYAML.text = { // @ts-ignore Type '"whoknows"' is not assignable to type '"empty" | "generated" ...' status: 'whoknows', div: '<div></div>' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid text\.status value: 'whoknows'\. Must be one of: 'generated','extensions','additional','empty'\.\s*File: test-config\.yaml/ ); expect(config.text.status).toBeUndefined(); }); }); describe('#contained', () => { // NOTE: special FSH syntax concepts/quantities aren't available in contained resources it('should import contained as-is', () => { minYAML.contained = [ { resourceType: 'Patient', id: 'bob', active: true } ]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.contained).toEqual([ { resourceType: 'Patient', id: 'bob', active: true } ]); }); }); describe('#extension', () => { it('should import extension as-is', () => { minYAML.extension = [ { url: 'http://extension.org/my-extension', // @ts-ignore Type '{ url: string; valueBoolean: boolean; }' is not assignable ... valueBoolean: true } ]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.extension).toEqual([ { url: 'http://extension.org/my-extension', valueBoolean: true } ]); }); }); describe('#modifierExtension', () => { it('should import modifierExtension as-is', () => { minYAML.modifierExtension = [ { url: 'http://extension.org/my-modifier-extension', // @ts-ignore Type '{ url: string; valueBoolean: boolean; }' is not assignable ... valueBoolean: true } ]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.modifierExtension).toEqual([ { url: 'http://extension.org/my-modifier-extension', valueBoolean: true } ]); }); }); describe('#canonical', () => { it('should import canonical as-is', () => { minYAML.canonical = 'http://foo.org/some-canonical-url'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.canonical).toBe('http://foo.org/some-canonical-url'); }); it('should report an error and throw if canonical is missing and FSHOnly is true', () => { delete minYAML.canonical; minYAML.FSHOnly = true; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to start processing FSH: canonical, fhirVersion\.\s*File: test-config\.yaml/ ); }); it('should report an error and throw if canonical is missing and FSHOnly is false', () => { delete minYAML.canonical; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to generate an IG: canonical, fhirVersion, id, name, status, copyrightYear, releaseLabel\.\s*File: test-config\.yaml/ ); }); }); describe('#url', () => { it('should import url as-is if provided', () => { minYAML.url = 'http://foo.org/some-url/ImplementationGuide/my.guide'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.url).toBe('http://foo.org/some-url/ImplementationGuide/my.guide'); }); it('should default url based on canonical if url is not provided', () => { delete minYAML.url; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.url).toBe(`${config.canonical}/ImplementationGuide/${config.id}`); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); }); }); describe('#version', () => { it('should support a single-component version when YAML parses it as a number', () => { // @ts-ignore Type '1' is not assignable to type 'string' minYAML.version = 1; // YAML parse will interpret 1 as a number, not a string const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.version).toBe('1'); }); it('should support a two-component version when YAML parses it as a number', () => { minYAML.version = 1.2; // YAML parse will interpret 1.2 as a number, not a string const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.version).toBe('1.2'); }); }); describe('#name', () => { it('should import name as-is', () => { minYAML.name = 'MyIG'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.name).toBe('MyIG'); }); it('should report an error and throw if name is missing and FSHOnly is false', () => { delete minYAML.name; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to generate an IG: canonical, fhirVersion, id, name, status, copyrightYear, releaseLabel\.\s*File: test-config\.yaml/ ); }); it('should not report an error and throw if name is missing and FSHOnly is true', () => { delete minYAML.name; minYAML.FSHOnly = true; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.name).toBeUndefined(); }); }); describe('#title', () => { it('should import title as-is', () => { minYAML.title = 'My IG'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.title).toBe('My IG'); }); }); describe('#status', () => { it('should support string for status', () => { minYAML.status = 'draft'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.status).toBe('draft'); }); it('should support code syntax for status', () => { minYAML.status = '#draft'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.status).toBe('draft'); }); it('should report invalid status code', () => { // @ts-ignore Type '"whoknows"' is not assignable to type 'YAMLConfigurationStatus'. minYAML.status = 'married'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid status value: 'married'\. Must be one of: 'draft','active','retired','unknown'\.\s*File: test-config\.yaml/ ); expect(config.status).toBeUndefined(); }); it('should report an error if status is missing and FSHOnly is false', () => { delete minYAML.status; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to generate an IG: canonical, fhirVersion, id, name, status, copyrightYear, releaseLabel\.\s*File: test-config\.yaml/ ); }); it('should not report an error if status is missing and FSHOnly is true', () => { delete minYAML.status; minYAML.FSHOnly = true; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.status).toBeUndefined(); }); }); describe('#experimental', () => { it('should import experimental as-is', () => { minYAML.experimental = true; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.experimental).toBe(true); }); }); describe('#date', () => { it('should support a year-only date when YAML parses it as a number', () => { // @ts-ignore Type '2000' is not assignable to type 'string' minYAML.date = 2000; // YAML parse will interpret 2000 as a number, not a string const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.date).toBe('2000'); }); }); describe('#publisher', () => { it('should convert single publisher with name only to publisher only', () => { minYAML.publisher = { name: 'Bob' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.publisher).toBe('Bob'); expect(config.contact).toBeUndefined(); }); it('should convert single publisher with name and contact info to publisher and contact', () => { minYAML.publisher = { name: 'Bob', email: 'bob@example.org', url: 'http://bob.example.org' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.publisher).toBe('Bob'); expect(config.contact).toEqual([ { name: 'Bob', telecom: [ { system: 'url', value: 'http://bob.example.org' }, { system: 'email', value: 'bob@example.org' } ] } ]); }); it('should convert multiple publishers to publisher and contacts', () => { minYAML.publisher = [ { name: 'Bob', email: 'bob@example.org', url: 'http://bob.example.org' }, { name: 'Sue', email: 'sue@example.org', url: 'http://sue.example.org' } ]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.publisher).toBe('Bob'); expect(config.contact).toEqual([ { name: 'Bob', telecom: [ { system: 'url', value: 'http://bob.example.org' }, { system: 'email', value: 'bob@example.org' } ] }, { name: 'Sue', telecom: [ { system: 'url', value: 'http://sue.example.org' }, { system: 'email', value: 'sue@example.org' } ] } ]); }); }); describe('#contact', () => { it('should convert single-item contact to an array', () => { minYAML.contact = { name: 'Bob', telecom: [{ system: 'email', value: 'bob@example.com' }] }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.contact).toEqual([ { name: 'Bob', telecom: [{ system: 'email', value: 'bob@example.com' }] } ]); }); it('should support contact as an array', () => { minYAML.contact = [{ name: 'Bob', telecom: [{ system: 'email', value: 'bob@example.com' }] }]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.contact).toEqual([ { name: 'Bob', telecom: [{ system: 'email', value: 'bob@example.com' }] } ]); }); it('should translate codes for contact.telecom.use/system', () => { minYAML.contact = { name: 'Bob', telecom: [{ system: '#email', value: 'bob@example.com', use: '#work' }] }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.contact).toEqual([ { name: 'Bob', telecom: [{ system: 'email', value: 'bob@example.com', use: 'work' }] } ]); }); it('should report invalid telecom codes', () => { minYAML.contact = { name: 'Bob', // @ts-ignore Type ... is not assignable to type ... telecom: [{ system: '#carrier-pidgeon', value: 'bob@example.com', use: '#whateva' }] }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getMessageAtIndex(-2, 'error')).toMatch( /Invalid contact\.telecom\.system value: 'carrier-pidgeon'\. Must be one of: 'phone','fax','email','pager','url','sms','other'\.\s*File: test-config\.yaml/ ); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid contact\.telecom\.use value: 'whateva'\. Must be one of: 'home','work','temp','old','mobile'\.\s*File: test-config\.yaml/ ); expect(config.contact[0].telecom[0].system).toBeUndefined(); expect(config.contact[0].telecom[0].use).toBeUndefined(); }); it('should put contacts after publisher contact details', () => { minYAML.publisher = { name: 'Bob', email: 'bob@example.org', url: 'http://bob.example.org' }; minYAML.contact = { name: 'Frank', telecom: [{ system: 'email', value: 'frank@example.com' }] }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.publisher).toBe('Bob'); expect(config.contact).toEqual([ { name: 'Bob', telecom: [ { system: 'url', value: 'http://bob.example.org' }, { system: 'email', value: 'bob@example.org' } ] }, { name: 'Frank', telecom: [{ system: 'email', value: 'frank@example.com' }] } ]); }); }); describe('#description', () => { it('should copy description as-is', () => { minYAML.description = 'This is a great IG. Really great. The best.'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.description).toBe('This is a great IG. Really great. The best.'); }); }); describe('#useContext', () => { it('should convert single-item useContext to an array', () => { minYAML.useContext = { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'gender', display: 'Gender' }, valueCodeableConcept: { coding: [ { system: 'http://hl7.org/fhir/administrative-gender', code: 'female', display: 'Female' } ] } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'gender', display: 'Gender' }, valueCodeableConcept: { coding: [ { system: 'http://hl7.org/fhir/administrative-gender', code: 'female', display: 'Female' } ] } } ]); }); it('should support useContext as an array', () => { minYAML.useContext = [ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'gender', display: 'Gender' }, valueCodeableConcept: { coding: [ { system: 'http://hl7.org/fhir/administrative-gender', code: 'female', display: 'Female' } ] } } ]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'gender', display: 'Gender' }, valueCodeableConcept: { coding: [ { system: 'http://hl7.org/fhir/administrative-gender', code: 'female', display: 'Female' } ] } } ]); }); it('should translate codes for code and valueCodeableConcept', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#gender "Gender"', valueCodeableConcept: 'http://hl7.org/fhir/administrative-gender#female "Female"' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'gender', display: 'Gender' }, valueCodeableConcept: { coding: [ { system: 'http://hl7.org/fhir/administrative-gender', code: 'female', display: 'Female' } ] } } ]); }); it('should report invalid FSH syntax for code and valueCodeableConcept', () => { minYAML.useContext = { code: 'gender', valueCodeableConcept: 'female' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getMessageAtIndex(-2, 'error')).toMatch( /Invalid code format for useContext\.code: gender\s*File: test-config\.yaml/ ); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid code format for useContext\.valueCodeableConcept: female\s*File: test-config\.yaml/ ); expect(config.useContext).toEqual([{}]); }); it('should translate codes for valueQuantity', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#age "Age Range"', // technically "age" uses valueRange, but no other contexts used valueQuantity either, so... valueQuantity: { code: '#a', system: 'http://unitsofmeasure.org', value: 50, comparator: '#>=' } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'age', display: 'Age Range' }, valueQuantity: { code: 'a', system: 'http://unitsofmeasure.org', value: 50, comparator: '>=' } } ]); }); // useContext should support FSH quantity syntax for quantity properties it('should translate quantity for valueQuantity', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#age "Age Range"', // technically "age" uses valueRange, but no other contexts used valueQuantity either, so... valueQuantity: "50 'a'" }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'age', display: 'Age Range' }, valueQuantity: { code: 'a', system: 'http://unitsofmeasure.org', value: 50 } } ]); }); it('should report invalid FSH syntax for quantity', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#age "Age Range"', // technically "age" uses valueRange, but no other contexts used valueQuantity either, so... valueQuantity: '50 a' // NOTE: missing '' around unit }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid useContext\.valueQuantity value: 50 a\s*File: test-config\.yaml/ ); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'age', display: 'Age Range' } } ]); }); it('should report invalid quantity.comparator code', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#age "Age Range"', // technically "age" uses valueRange, but no other contexts used valueQuantity either, so... valueQuantity: { code: '#a', system: 'http://unitsofmeasure.org', value: 50, // @ts-ignore Type '"!="' is not assignable to type '"<" | "<=" | ">=" | ">" | "#<" | ...'. comparator: '!=' } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid useContext\.valueQuantity\.comparator value: '!='\. Must be one of: '<','<=','>=','>'\.\s*File: test-config\.yaml/ ); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'age', display: 'Age Range' }, valueQuantity: { code: 'a', system: 'http://unitsofmeasure.org', value: 50 } } ]); }); it('should translate codes for valueRange', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#age "Age Range"', valueRange: { low: { code: '#a', system: 'http://unitsofmeasure.org', value: 50 }, high: { code: '#a', system: 'http://unitsofmeasure.org', value: 65 } } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'age', display: 'Age Range' }, valueRange: { low: { code: 'a', system: 'http://unitsofmeasure.org', value: 50 }, high: { code: 'a', system: 'http://unitsofmeasure.org', value: 65 } } } ]); }); it('should translate quantity for valueQuantity', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#age "Age Range"', valueRange: { low: "50 'a'", high: "65 'a'" } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'age', display: 'Age Range' }, valueRange: { low: { code: 'a', system: 'http://unitsofmeasure.org', value: 50 }, high: { code: 'a', system: 'http://unitsofmeasure.org', value: 65 } } } ]); }); it('should report invalid FSH syntax for range low / high quantity', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#age "Age Range"', valueRange: { low: '50 a', high: '65 a' } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getMessageAtIndex(-2, 'error')).toMatch( /Invalid useContext\.valueRange\.low value: 50 a\s*File: test-config\.yaml/ ); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid useContext\.valueRange\.high value: 65 a\s*File: test-config\.yaml/ ); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'age', display: 'Age Range' }, valueRange: {} } ]); }); it('should translate codes for valueReference', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#venue "Clinical Venue"', valueReference: { identifier: { use: '#official', type: 'http://terminology.hl7.org/CodeSystem/v2-0203#PRN "Provider number"', value: '123', assigner: { identifier: { use: '#temp', type: 'http://terminology.hl7.org/CodeSystem/v2-0203#TAX "Tax ID number"', value: 'abc' } } } } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'venue', display: 'Clinical Venue' }, valueReference: { identifier: { use: 'official', type: { coding: [ { system: 'http://terminology.hl7.org/CodeSystem/v2-0203', code: 'PRN', display: 'Provider number' } ] }, value: '123', assigner: { identifier: { use: 'temp', type: { coding: [ { system: 'http://terminology.hl7.org/CodeSystem/v2-0203', code: 'TAX', display: 'Tax ID number' } ] }, value: 'abc' } } } } } ]); }); it('should report invalid FSH syntax for identifier.type', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#venue "Clinical Venue"', valueReference: { identifier: { use: '#official', type: 'PRN', value: '123', assigner: { identifier: { use: '#temp', type: 'TAX', value: 'abc' } } } } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getMessageAtIndex(-2, 'error')).toMatch( /Invalid code format for useContext\.valueReference\.identifier\.type: PRN\s*File: test-config\.yaml/ ); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid code format for useContext\.valueReference\.identifier\.assigner\.identifier\.type: TAX\s*File: test-config\.yaml/ ); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'venue', display: 'Clinical Venue' }, valueReference: { identifier: { use: 'official', value: '123', assigner: { identifier: { use: 'temp', value: 'abc' } } } } } ]); }); it('should report invalid FSH identifier.use codes', () => { minYAML.useContext = { code: 'http://terminology.hl7.org/CodeSystem/usage-context-type#venue "Clinical Venue"', valueReference: { identifier: { // @ts-ignore Type '"#myob"' is not assignable to type '"temp" | "old" | "#temp" | ...'. use: '#myob', value: '123', assigner: { identifier: { // @ts-ignore Type '"#the-usual"' is not assignable to type '"temp" | "old" | ...'. use: '#the-usual', value: 'abc' } } } } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getMessageAtIndex(-2, 'error')).toMatch( /Invalid useContext\.valueReference\.identifier\.use value: 'myob'\. Must be one of: 'usual','official','temp','secondary','old'\.\s*File: test-config\.yaml/ ); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid useContext\.valueReference\.identifier\.assigner\.identifier\.use value: 'the-usual'\. Must be one of: 'usual','official','temp','secondary','old'\.\s*File: test-config\.yaml/ ); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'venue', display: 'Clinical Venue' }, valueReference: { identifier: { value: '123', assigner: { identifier: { value: 'abc' } } } } } ]); }); it('should report an error if useContext.code is missing', () => { // @ts-ignore Type '...' is not assignable to type ... minYAML.useContext = { valueCodeableConcept: { coding: [ { system: 'http://hl7.org/fhir/administrative-gender', code: 'female', display: 'Female' } ] } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: useContext\.code\s*File: test-config\.yaml/ ); expect(config.useContext).toEqual([ { valueCodeableConcept: { coding: [ { system: 'http://hl7.org/fhir/administrative-gender', code: 'female', display: 'Female' } ] } } ]); }); it('should report an error if useContext.value[x] is missing', () => { // @ts-ignore Type '...' is not assignable to type ... minYAML.useContext = { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'gender', display: 'Gender' } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: useContext\.value\[x\]\s*File: test-config\.yaml/ ); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'gender', display: 'Gender' } } ]); }); it('should report an error if there is more than one useContext.value[x]', () => { // @ts-ignore Type '...' is not assignable to type ... minYAML.useContext = { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'gender', display: 'Gender' }, valueCodeableConcept: 'http://hl7.org/fhir/administrative-gender#female "Female"', valueQuantity: "50 'a'" }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Only one useContext.value\[x\] is allowed but found multiple: valueCodeableConcept, valueQuantity\s*File: test-config\.yaml/ ); expect(config.useContext).toEqual([ { code: { system: 'http://terminology.hl7.org/CodeSystem/usage-context-type', code: 'gender', display: 'Gender' }, valueCodeableConcept: { coding: [ { system: 'http://hl7.org/fhir/administrative-gender', code: 'female', display: 'Female' } ] }, valueQuantity: { code: 'a', system: 'http://unitsofmeasure.org', value: 50 } } ]); }); }); describe('#jurisdiction', () => { it('should convert single-item jurisdiction to an array', () => { minYAML.jurisdiction = { coding: [ { code: 'US', system: 'urn:iso:std:iso:3166', display: 'United States of America' } ] }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.jurisdiction).toEqual([ { coding: [ { code: 'US', system: 'urn:iso:std:iso:3166', display: 'United States of America' } ] } ]); }); it('should support jurisdiction as an array', () => { minYAML.jurisdiction = [ { coding: [ { code: 'US', system: 'urn:iso:std:iso:3166', display: 'United States of America' } ] } ]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.jurisdiction).toEqual([ { coding: [ { code: 'US', system: 'urn:iso:std:iso:3166', display: 'United States of America' } ] } ]); }); it('should translate jurisdiction codes', () => { minYAML.jurisdiction = ['urn:iso:std:iso:3166#US "United States of America"']; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.jurisdiction).toEqual([ { coding: [ { code: 'US', system: 'urn:iso:std:iso:3166', display: 'United States of America' } ] } ]); }); it('should report invalid FSH syntax for jurisdiction', () => { minYAML.jurisdiction = ['merica']; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid code format for jurisdiction: merica\s*File: test-config\.yaml/ ); expect(config.jurisdiction).toBeUndefined(); }); }); describe('#copyright', () => { it('should copy copyright as-is', () => { minYAML.copyright = 'Copyright Scaly Productions 2020'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.copyright).toBe('Copyright Scaly Productions 2020'); }); }); describe('#packageId', () => { it('should use the id as packageId when packageId is not provided', () => { const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.packageId).toBe('fhir.us.minimal'); }); it('should use the packageId when it is provided', () => { minYAML.packageId = 'diff.package.id'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.id).toBe('fhir.us.minimal'); expect(config.packageId).toBe('diff.package.id'); }); }); describe('#license', () => { // license supports string or code syntax it('should support string for license', () => { minYAML.license = 'CC0-1.0'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.license).toBe('CC0-1.0'); }); it('should support code syntax for license', () => { minYAML.license = '#CC0-1.0'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.license).toBe('CC0-1.0'); }); }); describe('#fhirVersion', () => { it('should support fhirVersion as an array', () => { minYAML.fhirVersion = ['4.0.1', '3.0.2']; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.fhirVersion).toEqual(['4.0.1', '3.0.2']); }); it('should convert single-item fhirVersion to an array', () => { minYAML.fhirVersion = '4.0.1'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.fhirVersion).toEqual(['4.0.1']); }); it('should support FSH syntax for fhirVersion', () => { // because... fhirVersion is actually a code! minYAML.fhirVersion = ['#4.0.1']; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.fhirVersion).toEqual(['4.0.1']); }); it('should report an error and throw if fhirVersion is missing and FSHOnly is true', () => { delete minYAML.fhirVersion; minYAML.FSHOnly = true; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to start processing FSH: canonical, fhirVersion\.\s*File: test-config\.yaml/ ); }); it('should report an error and throw if fhirVersion is an empty array and FSHOnly is true', () => { minYAML.fhirVersion = []; minYAML.FSHOnly = true; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to start processing FSH: canonical, fhirVersion\.\s*File: test-config\.yaml/ ); }); it('should report an error and throw if fhirVersion is missing and FSHOnly is false', () => { delete minYAML.fhirVersion; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to generate an IG: canonical, fhirVersion, id, name, status, copyrightYear, releaseLabel\.\s*File: test-config\.yaml/ ); }); it('should report an error and throw if fhirVersion is an empty array and FSHOnly is false', () => { minYAML.fhirVersion = []; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to generate an IG: canonical, fhirVersion, id, name, status, copyrightYear, releaseLabel\.\s*File: test-config\.yaml/ ); }); }); describe('#dependencies', () => { it('should convert the dependencies map to a list', () => { minYAML.dependencies = { foo: '1.2.3', bar: '4.5.6' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.dependencies).toEqual([ { packageId: 'foo', version: '1.2.3' }, { packageId: 'bar', version: '4.5.6' } ]); }); it('should convert the dependencies map to a list when YAML imports version as a number', () => { minYAML.dependencies = { // @ts-ignore Type '1' is not assignable to type 'string' foo: 1, // YAML parse will interpret 1 as a number, not a string // @ts-ignore Type '2.3' is not assignable to type 'string' bar: 2.3 // YAML parse will interpret 2.3 as a number, not a string }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.dependencies).toEqual([ { packageId: 'foo', version: '1' }, { packageId: 'bar', version: '2.3' } ]); }); it('should convert uppercase package Ids to lowercase', () => { minYAML.dependencies = { 'hl7.ex.PAcKage.iD1': '1.2.3', 'hl7.ex.package.id2': '4.5.6' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.dependencies).toEqual([ { packageId: 'hl7.ex.package.id1', version: '1.2.3' }, { packageId: 'hl7.ex.package.id2', version: '4.5.6' } ]); expect( loggerSpy .getAllMessages('warn') .some(message => message.match( /hl7.ex.PAcKage.iD1 contains uppercase characters, which is discouraged. SUSHI will use hl7.ex.package.id1 as the package name./ ) ) ).toBeTruthy(); }); }); describe('#global', () => { it('should convert the global map to a list', () => { minYAML.global = { Patient: 'http://example.org/fhir/StructureDefinition/my-patient-profile', Encounter: 'http://example.org/fhir/StructureDefinition/my-encounter-profile' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.global).toEqual([ { type: 'Patient', profile: 'http://example.org/fhir/StructureDefinition/my-patient-profile' }, { type: 'Encounter', profile: 'http://example.org/fhir/StructureDefinition/my-encounter-profile' } ]); }); it('should convert the global array values to a list items', () => { minYAML.global = { Patient: [ 'http://example.org/fhir/StructureDefinition/my-patient-profile', 'http://example.org/fhir/StructureDefinition/my-other-patient-profile' ], Encounter: [ 'http://example.org/fhir/StructureDefinition/my-encounter-profile', 'http://example.org/fhir/StructureDefinition/my-other-encounter-profile' ] }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.global).toEqual([ { type: 'Patient', profile: 'http://example.org/fhir/StructureDefinition/my-patient-profile' }, { type: 'Patient', profile: 'http://example.org/fhir/StructureDefinition/my-other-patient-profile' }, { type: 'Encounter', profile: 'http://example.org/fhir/StructureDefinition/my-encounter-profile' }, { type: 'Encounter', profile: 'http://example.org/fhir/StructureDefinition/my-other-encounter-profile' } ]); }); }); describe('#groups', () => { it('should convert the groups map to a list', () => { minYAML.groups = { GroupA: { name: 'Group A', description: 'The Alpha Group', resources: ['StructureDefinition/animal-patient', 'StructureDefinition/arm-procedure'] }, GroupB: { description: 'The Beta Group', resources: ['StructureDefinition/bark-control', 'StructureDefinition/bee-sting'] } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.groups).toEqual([ { id: 'GroupA', name: 'Group A', description: 'The Alpha Group', resources: ['StructureDefinition/animal-patient', 'StructureDefinition/arm-procedure'] }, { id: 'GroupB', name: 'GroupB', description: 'The Beta Group', resources: ['StructureDefinition/bark-control', 'StructureDefinition/bee-sting'] } ]); }); }); describe('#resources', () => { it('should convert the resources map to a list', () => { minYAML.resources = { 'Patient/my-example-patient': { name: 'My Example Patient', description: 'An example Patient', exampleBoolean: true }, 'Patient/my-other-example-patient': { name: 'My Other Example Patient', description: 'Another example Patient', exampleBoolean: true } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.resources).toEqual([ { reference: { reference: 'Patient/my-example-patient' }, name: 'My Example Patient', description: 'An example Patient', exampleBoolean: true }, { reference: { reference: 'Patient/my-other-example-patient' }, name: 'My Other Example Patient', description: 'Another example Patient', exampleBoolean: true } ]); }); it('should support resources.[name].fhirVersion as an array', () => { minYAML.resources = { 'Patient/my-example-patient': { fhirVersion: ['4.0.1'] } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.resources).toEqual([ { reference: { reference: 'Patient/my-example-patient' }, fhirVersion: ['4.0.1'] } ]); }); it('should convert single-item resources.[name].fhirVersion to an array', () => { minYAML.resources = { 'Patient/my-example-patient': { fhirVersion: '4.0.1' } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.resources).toEqual([ { reference: { reference: 'Patient/my-example-patient' }, fhirVersion: ['4.0.1'] } ]); }); it('should support FSH syntax for resource.fhirVersions', () => { minYAML.resources = { 'Patient/my-example-patient': { fhirVersion: ['#4.0.1'] } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.resources).toEqual([ { reference: { reference: 'Patient/my-example-patient' }, fhirVersion: ['4.0.1'] } ]); }); it('should convert omitted resources correctly', () => { minYAML.resources = { 'Patient/my-bad-example-patient': 'omit', 'Patient/my-other-bad-example-patient': '#omit' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.resources).toEqual([ { reference: { reference: 'Patient/my-bad-example-patient' }, omit: true }, { reference: { reference: 'Patient/my-other-bad-example-patient' }, omit: true } ]); }); }); describe('#pages', () => { it('should convert the pages map to a list', () => { minYAML.pages = { 'index.md': { title: 'Example Home' }, 'implementation.xml': null, 'examples.xml': { title: 'Examples Overview', 'simpleExamples.xml': null, 'complexExamples.xml': null } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.pages).toEqual([ { nameUrl: 'index.md', title: 'Example Home' }, { nameUrl: 'implementation.xml' }, { nameUrl: 'examples.xml', title: 'Examples Overview', page: [{ nameUrl: 'simpleExamples.xml' }, { nameUrl: 'complexExamples.xml' }] } ]); }); it('should support FSH syntax for pages.[name].generation', () => { minYAML.pages = { 'index.md': { title: 'Example Home' }, 'examples.xml': { title: 'Examples', generation: '#html' } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.pages).toEqual([ { nameUrl: 'index.md', title: 'Example Home' }, { nameUrl: 'examples.xml', title: 'Examples', generation: 'html' } ]); }); it('should report invalid generation codes', () => { minYAML.pages = { 'index.md': { title: 'Example Home', // @ts-ignore Type '"electric"' is not assignable to type '"generated" | "#generated" ...'. generation: 'electric' }, 'examples.xml': { title: 'Examples Overview', 'simpleExamples.xml': { // @ts-ignore Type '"gas"' is not assignable to type '"generated" | "#generated" ...'. generation: 'gas' } } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getMessageAtIndex(-2, 'error')).toMatch( /Invalid pages\[index\.md\]\.generation value: 'electric'\. Must be one of: 'html','markdown','xml','generated'\.\s*File: test-config\.yaml/ ); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid pages\[examples\.xml\]\[simpleExamples\.xml\]\.generation value: 'gas'\. Must be one of: 'html','markdown','xml','generated'\.\s*File: test-config\.yaml/ ); expect(config.pages).toEqual([ { nameUrl: 'index.md', title: 'Example Home' }, { nameUrl: 'examples.xml', title: 'Examples Overview', page: [{ nameUrl: 'simpleExamples.xml' }] } ]); }); }); describe('#parameters', () => { it('should convert the parameters map to a list', () => { minYAML.parameters = { // @ts-ignore Type 'true' is not assignable to type 'string | string[]'. excludettl: true, validation: 'allow-any-extensions' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.parameters).toEqual([ { code: 'copyrightyear', value: '2020+' }, { code: 'releaselabel', value: 'Build CI' }, { code: 'excludettl', value: 'true' }, { code: 'validation', value: 'allow-any-extensions' } ]); }); it('should convert parameter array values to list items', () => { minYAML.parameters = { validation: ['allow-any-extensions', 'no-broken-links'] }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.parameters).toEqual([ { code: 'copyrightyear', value: '2020+' }, { code: 'releaselabel', value: 'Build CI' }, { code: 'validation', value: 'allow-any-extensions' }, { code: 'validation', value: 'no-broken-links' } ]); }); }); describe('#templates', () => { it('should support template as an array', () => { // NOTE: I don't know what values would actually be used; I made these up. minYAML.templates = [ { code: 'page', source: 'page.xml', scope: 'global' } ]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.templates).toEqual([ { code: 'page', source: 'page.xml', scope: 'global' } ]); }); it('should convert single-item templates to an array', () => { // NOTE: I don't know what values would actually be used; I made these up. minYAML.templates = { code: 'page', source: 'page.xml', scope: 'global' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.templates).toEqual([ { code: 'page', source: 'page.xml', scope: 'global' } ]); }); it('should translate template.code if applicable', () => { // NOTE: I don't know what values would actually be used; I made these up. minYAML.templates = [ { code: '#page', source: 'page.xml', scope: 'global' } ]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.templates).toEqual([ { code: 'page', source: 'page.xml', scope: 'global' } ]); }); it('should report an error if templates.code is missing', () => { minYAML.templates = [ // @ts-ignore Property 'code' is missing in type... { source: 'page.xml', scope: 'global' } ]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: templates\.code\s*File: test-config\.yaml/ ); expect(config.templates).toEqual([ { source: 'page.xml', scope: 'global' } ]); }); it('should report an error if templates.source is missing', () => { minYAML.templates = [ // @ts-ignore Property 'source' is missing in type... { code: 'page', scope: 'global' } ]; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: templates\.source\s*File: test-config\.yaml/ ); expect(config.templates).toEqual([ { code: 'page', scope: 'global' } ]); }); }); describe('#template', () => { it('should copy template as-is', () => { minYAML.template = 'hl7.fhir.template#0.0.5'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.template).toBe('hl7.fhir.template#0.0.5'); }); }); describe('#copyrightYear', () => { // some of these are a little redundant due to minimal-config, but that's OK it('should convert copyrightYear to a parameter', () => { minYAML.copyrightYear = '2019+'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.parameters[0]).toEqual({ code: 'copyrightyear', value: '2019+' }); }); it('should convert copyrightyear to a parameter', () => { delete minYAML.copyrightYear; minYAML.copyrightyear = '2020+'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.parameters[0]).toEqual({ code: 'copyrightyear', value: '2020+' }); }); it('should support copyrightYear when YAML imports it as a number', () => { // @ts-ignore Type '2020' is not assignable to type 'string' minYAML.copyrightYear = 2020; // YAML parse will interpret 2020 as a number, not a string let config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.parameters[0]).toEqual({ code: 'copyrightyear', value: '2020' }); // @ts-ignore Type '2020' is not assignable to type 'string' delete minYAML.copyrightYear; minYAML.copyrightyear = 2020; // YAML parse will interpret 2020 as a number, not a string config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.parameters[0]).toEqual({ code: 'copyrightyear', value: '2020' }); }); it('should report an error and throw if copyrightYear/copyrightyear is missing and FSHOnly is false', () => { delete minYAML.copyrightYear; minYAML.FSHOnly = false; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to generate an IG: canonical, fhirVersion, id, name, status, copyrightYear, releaseLabel\.\s*File: test-config\.yaml/ ); }); it('should not report an error if copyrightYear/copyrightyear is missing and FSHOnly is true', () => { delete minYAML.copyrightYear; minYAML.FSHOnly = true; importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); }); }); describe('#releaseLabel', () => { // some of these are a little redundant due to minimal-config, but that's OK it('should convert releaseLabel to a parameter', () => { minYAML.releaseLabel = 'STU1'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.parameters[1]).toEqual({ code: 'releaselabel', value: 'STU1' }); }); it('should convert releaselabel to a parameter', () => { delete minYAML.releaseLabel; minYAML.releaselabel = 'STU2'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.parameters[1]).toEqual({ code: 'releaselabel', value: 'STU2' }); }); it('should report an error and throw if releaseLabel/releaselabel is missing and FSHOnly is false', () => { delete minYAML.releaseLabel; minYAML.FSHOnly = false; expect(() => importConfiguration(minYAML, 'test-config.yaml')).toThrow( 'Minimal config not met' ); expect(loggerSpy.getLastMessage('error')).toMatch( /SUSHI minimally requires the following configuration properties to generate an IG: canonical, fhirVersion, id, name, status, copyrightYear, releaseLabel\.\s*File: test-config\.yaml/ ); }); it('should not report an error if releaseLabel/releaselabel is missing and and FSHOnly is true', () => { delete minYAML.releaseLabel; minYAML.FSHOnly = true; importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); }); }); describe('#menu', () => { it('should convert the menu map to a list', () => { minYAML.menu = { Home: 'index.html', Artifacts: { Profiles: 'artifacts.html#2', Extensions: 'artifacts.html#3', 'Value Sets': 'artifacts.html#4' }, Downloads: 'downloads.html', History: 'http://hl7.org/fhir/us/example/history.html', 'FHIR Spec': 'new-tab external http://hl7.org/fhir/R4/index.html' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.menu).toEqual([ { name: 'Home', url: 'index.html' }, { name: 'Artifacts', subMenu: [ { name: 'Profiles', url: 'artifacts.html#2' }, { name: 'Extensions', url: 'artifacts.html#3' }, { name: 'Value Sets', url: 'artifacts.html#4' } ] }, { name: 'Downloads', url: 'downloads.html' }, { name: 'History', url: 'http://hl7.org/fhir/us/example/history.html' }, { name: 'FHIR Spec', url: 'http://hl7.org/fhir/R4/index.html', openInNewTab: true } ]); expect(loggerSpy.getAllMessages('warn')).toHaveLength(1); expect(loggerSpy.getLastMessage('warn')).toMatch( /The "external" keyword in menu configuration has been deprecated/ ); }); }); describe('#history', () => { it('should use default values for history where applicable', () => { minYAML.title = 'HL7 FHIR Implementation Guide: Minimal IG Release 1 - US Realm | STU1'; minYAML.description = 'Minimal IG exercises only required fields in a SUSHI configuration.'; minYAML.history = { current: 'https://build.fhir.org/ig/HL7/minimal-ig/' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.history).toEqual({ 'package-id': 'fhir.us.minimal', canonical: 'http://hl7.org/fhir/us/minimal', title: 'HL7 FHIR Implementation Guide: Minimal IG Release 1 - US Realm | STU1', introduction: 'Minimal IG exercises only required fields in a SUSHI configuration.', list: [ { version: 'current', desc: 'Continuous Integration Build (latest in version control)', path: 'https://build.fhir.org/ig/HL7/minimal-ig/', status: 'ci-build', current: true } ] }); }); it('should allow mix of default and provided values for history.current', () => { minYAML.title = 'HL7 FHIR Implementation Guide: Minimal IG Release 1 - US Realm | STU1'; minYAML.description = 'Minimal IG exercises only required fields in a SUSHI configuration.'; minYAML.history = { current: { fhirversion: '4.0.1', date: '2020-04-01', path: 'https://build.fhir.org/ig/HL7/example-ig/', sequence: 'STU 2' } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.history).toEqual({ 'package-id': 'fhir.us.minimal', canonical: 'http://hl7.org/fhir/us/minimal', title: 'HL7 FHIR Implementation Guide: Minimal IG Release 1 - US Realm | STU1', introduction: 'Minimal IG exercises only required fields in a SUSHI configuration.', list: [ { version: 'current', fhirversion: '4.0.1', date: '2020-04-01', desc: 'Continuous Integration Build (latest in version control)', path: 'https://build.fhir.org/ig/HL7/example-ig/', status: 'ci-build', sequence: 'STU 2', current: true } ] }); }); it('should use provided values for history where applicable', () => { minYAML.title = 'HL7 FHIR Implementation Guide: Minimal IG Release 1 - US Realm | STU1'; minYAML.description = 'Minimal IG exercises only required fields in a SUSHI configuration.'; minYAML.history = { 'package-id': 'fhir.us.other', canonical: 'http://hl7.org/fhir/us/other', title: 'HL7 FHIR Implementation Guide: Other IG Release 1 - US Realm | STU1', introduction: 'Other IG is other than the other IG.', current: { fhirversion: '4.0.1', date: '2020-04-01', desc: 'CI Build Release', path: 'https://build.fhir.org/ig/HL7/example-ig/', status: 'ci-build', sequence: 'STU 2', current: true }, '1.0.0': { fhirversion: '4.0.1', date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', sequence: 'STU 1', current: true }, '0.9.1': { fhirversion: '4.0.0', date: '2019-06-10', desc: 'Initial STU ballot (Sep 2019 Ballot)', path: 'https://hl7.org/fhir/us/example/2019Sep/', status: 'ballot', sequence: 'STU 1' } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.history).toEqual({ 'package-id': 'fhir.us.other', canonical: 'http://hl7.org/fhir/us/other', title: 'HL7 FHIR Implementation Guide: Other IG Release 1 - US Realm | STU1', introduction: 'Other IG is other than the other IG.', list: [ { version: 'current', fhirversion: '4.0.1', date: '2020-04-01', desc: 'CI Build Release', path: 'https://build.fhir.org/ig/HL7/example-ig/', status: 'ci-build', sequence: 'STU 2', current: true }, { version: '1.0.0', fhirversion: '4.0.1', date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', sequence: 'STU 1', current: true }, { version: '0.9.1', fhirversion: '4.0.0', date: '2019-06-10', desc: 'Initial STU ballot (Sep 2019 Ballot)', path: 'https://hl7.org/fhir/us/example/2019Sep/', status: 'ballot', sequence: 'STU 1' } ] }); }); it('should report invalid history.current.status code', () => { minYAML.history = { current: { path: 'http://build.fhir.org/ig/HL7/example-ig/', // @ts-ignore Type '"OK"' is not assignable to type '"ci-build" | "preview" | ... '. status: 'OK' } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid history\[current\]\.status value: 'OK'\. Must be one of: 'ci-build','preview','ballot','trial-use','update','normative','trial-use\+normative'\.\s*File: test-config\.yaml/ ); expect(config.history.list[0]).toEqual({ version: 'current', desc: 'Continuous Integration Build (latest in version control)', path: 'http://build.fhir.org/ig/HL7/example-ig/', current: true }); }); it('should report an error if history.current is an object and path is missing', () => { minYAML.history = { // @ts-ignore Type '...' is not assignable to type 'YAMLConfigurationHistoryItem'. current: { fhirversion: '4.0.1' } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: history\[current]\.path\s*File: test-config\.yaml/ ); expect(config.history.list[0]).toEqual({ version: 'current', desc: 'Continuous Integration Build (latest in version control)', status: 'ci-build', fhirversion: '4.0.1', current: true }); }); it('should report invalid history.[version].status code', () => { minYAML.history = { current: 'https://build.fhir.org/ig/HL7/minimal-ig/', '1.0.0': { fhirversion: '4.0.1', date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', // @ts-ignore Type '"ready"' is not assignable to type '"ci-build" | "preview" | ... '. status: 'ready', sequence: 'STU 1', current: true } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid history\[1\.0\.0\]\.status value: 'ready'\. Must be one of: 'ci-build','preview','ballot','trial-use','update','normative','trial-use\+normative'\.\s*File: test-config\.yaml/ ); expect(config.history.list[1]).toEqual({ version: '1.0.0', date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', sequence: 'STU 1', fhirversion: '4.0.1', current: true }); }); it('should report an error if history.[version].date is missing', () => { minYAML.history = { current: 'https://build.fhir.org/ig/HL7/minimal-ig/', '1.0.0': { fhirversion: '4.0.1', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', sequence: 'STU 1', current: true } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: history\[1\.0\.0\]\.date\s*File: test-config\.yaml/ ); expect(config.history.list[1]).toEqual({ version: '1.0.0', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', sequence: 'STU 1', fhirversion: '4.0.1', current: true }); }); it('should report an error if history.[version].desc is missing', () => { minYAML.history = { current: 'https://build.fhir.org/ig/HL7/minimal-ig/', '1.0.0': { fhirversion: '4.0.1', date: '2020-03-06', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', sequence: 'STU 1', current: true } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: history\[1\.0\.0\]\.desc\s*File: test-config\.yaml/ ); expect(config.history.list[1]).toEqual({ version: '1.0.0', date: '2020-03-06', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', sequence: 'STU 1', fhirversion: '4.0.1', current: true }); }); it('should report an error if history.[version].path is missing', () => { minYAML.history = { current: 'https://build.fhir.org/ig/HL7/minimal-ig/', // @ts-ignore Type '...' is not assignable to type ... '1.0.0': { fhirversion: '4.0.1', date: '2020-03-06', desc: 'STU 1 Release', status: 'trial-use', sequence: 'STU 1', current: true } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: history\[1\.0\.0\]\.path\s*File: test-config\.yaml/ ); expect(config.history.list[1]).toEqual({ version: '1.0.0', date: '2020-03-06', desc: 'STU 1 Release', status: 'trial-use', sequence: 'STU 1', fhirversion: '4.0.1', current: true }); }); it('should report an error if history.[version].status is missing', () => { minYAML.history = { current: 'https://build.fhir.org/ig/HL7/minimal-ig/', '1.0.0': { fhirversion: '4.0.1', date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', sequence: 'STU 1', current: true } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: history\[1\.0\.0\]\.status\s*File: test-config\.yaml/ ); expect(config.history.list[1]).toEqual({ version: '1.0.0', date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', sequence: 'STU 1', fhirversion: '4.0.1', current: true }); }); it('should report an error if history.[version].sequence is missing', () => { minYAML.history = { current: 'https://build.fhir.org/ig/HL7/minimal-ig/', '1.0.0': { fhirversion: '4.0.1', date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', current: true } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: history\[1\.0\.0\]\.sequence\s*File: test-config\.yaml/ ); expect(config.history.list[1]).toEqual({ version: '1.0.0', date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', fhirversion: '4.0.1', current: true }); }); it('should report an error if history.[version].fhirVersion is missing', () => { minYAML.history = { current: 'https://build.fhir.org/ig/HL7/minimal-ig/', '1.0.0': { date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', sequence: 'STU 1', current: true } }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('error')).toMatch( /Configuration missing required property: history\[1\.0\.0\]\.fhirVersion\s*File: test-config\.yaml/ ); expect(config.history.list[1]).toEqual({ version: '1.0.0', date: '2020-03-06', desc: 'STU 1 Release', path: 'https://hl7.org/fhir/us/example/STU1/', status: 'trial-use', sequence: 'STU 1', current: true }); }); }); describe('#indexPageContent', () => { it('should copy indexPageContent as-is', () => { minYAML.indexPageContent = 'This is a great index. Really great. The best.'; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.indexPageContent).toBe('This is a great index. Really great. The best.'); }); }); describe('#FSHOnly', () => { it('should copy FSHOnly as-is', () => { minYAML.FSHOnly = true; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.FSHOnly).toBe(true); }); it('should default FSHOnly to false when not specified', () => { const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.FSHOnly).toBe(false); }); it('should report a warning if FSHOnly is true and unused properties are given', () => { minYAML.menu = { Home: 'index.html' }; minYAML.contained = [{ resourceType: 'Patient' }]; minYAML.FSHOnly = true; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(loggerSpy.getLastMessage('warn')).toMatch( /The following properties are unused and only relevant for IG creation: copyrightYear, releaseLabel, template, menu, contained.*File: test-config.yaml/s ); expect(config.FSHOnly).toBe(true); }); }); describe('#instanceOptions', () => { it('should use default values for instanceOptions where applicable', () => { minYAML.instanceOptions = undefined; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.instanceOptions).toEqual({ setMetaProfile: 'always', setId: 'always' }); }); it('should use provided values for instanceOptions where applicable', () => { minYAML.instanceOptions = { setMetaProfile: 'never', setId: 'standalone-only' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.instanceOptions).toEqual({ setMetaProfile: 'never', setId: 'standalone-only' }); }); it('should report invalid instanceOptions.setMetaProfile code', () => { // @ts-ignore minYAML.instanceOptions = { setMetaProfile: 'foo', setId: 'standalone-only' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.instanceOptions).toEqual({ setMetaProfile: 'always', setId: 'standalone-only' }); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid instanceOptions\.setMetaProfile value: 'foo'\. Must be one of: 'always','never','inline-only','standalone-only'\.\s*File: test-config\.yaml/ ); }); it('should report invalid instanceOptions.setId code', () => { // @ts-ignore minYAML.instanceOptions = { setMetaProfile: 'never', setId: 'foo' }; const config = importConfiguration(minYAML, 'test-config.yaml'); expect(config.instanceOptions).toEqual({ setMetaProfile: 'never', setId: 'always' }); expect(loggerSpy.getLastMessage('error')).toMatch( /Invalid instanceOptions\.setId value: 'foo'\. Must be one of: 'always','standalone-only'\.\s*File: test-config\.yaml/ ); }); }); });
the_stack
export type StrWriter = (s: string) => void // export function SplitFileExt(path :string) :[string, string] { // let p = path.lastIndexOf('/') // p = path.lastIndexOf('.', p == -1 ? 0 : p) // return p == -1 ? [path, ''] : [path.substr(0, p), path.substr(p)] // } // export function SplitPath(path :string) :[string, string] { // const p = path.lastIndexOf('/') // return p == -1 ? ['.', path] : [path.substr(0, p), path.substr(p+1)] // } export function search(n :number, f :(n:number)=>bool) :int { // Define f(-1) == false and f(n) == true. // Invariant: f(i-1) == false, f(j) == true. let i = 0, j = n while (i < j) { const mid = i + (((j-i)/2) >> 0) // avoid overflow and truncate to int // i ≤ h < j if (!f(mid)) { i = mid + 1 // preserves f(i-1) == false } else { j = mid // preserves f(j) == true } } // i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i. return i } // serialize works on a collection of promieses. // It's similar to Promise.all but instead of being concurrent, this function // executes each promise serially; in order. // // Example: // let foo = (msg :string, delay :number) => // new Promise<string>(res => setTimeout(() => { log(msg); res(msg) }, delay)) // let inputs :[string,number][] = [ // ["hello", 10],["world",50],["good night",0]] // serialize(inputs.map(a=>()=>foo(a[0],a[1]))).then(results => log({results})) // // Console: hello\nworld\ngood night\n // Promise.all(inputs.map(a=>foo(a[0],a[1]))).then(results => log({results})) // // Console: good night\nhello\nworld\n // export function serialize<T>(v :(()=>Promise<T>)[]) :Promise<T[]> { let results :T[] = [] let p = v[0]() for (let i = 1; i < v.length; i++) { let f = v[i] p = p.then(r => (results.push(r), f())) } return p.then(r => (results.push(r), results)) } // bufcopy creates a new buffer containing bytes with some additional space. // export function bufcopy(bytes :ArrayLike<byte>, addlSize :int) { const size = bytes.length + addlSize const b2 = new Uint8Array(size) b2.set(bytes, 0) // const b = Buffer.allocUnsafe(size) // this.buffer.copy(b) return b2 } // asciibuf creates a byte array from a string of ASCII characters. // The string must only contain character values in the range [0-127]. // export function asciibuf(s :string) :Uint8Array { return Uint8Array.from( s as any as ArrayLike<number>, (_: number, k: number) => s.charCodeAt(k) ) } // asciistr creates a string from bytes representing ASCII characters. // The byte array must only contain values in the range [0-127]. // export function asciistr(b :ArrayLike<byte>) :string { return String.fromCharCode.apply(null, b) } // asciistrn is just like asciistr but implements efficient parsing of // subarrays and only works with Uint8Array // export var asciistrn :(b :Uint8Array, start :int, end :int)=>string = ( typeof Buffer == 'function' ? function asciistrn(b :Uint8Array, start :int, end :int) :string { // make use of faster nodejs Buffer implementation return Buffer.from( b.buffer, b.byteOffset + start, end - start, ).toString('ascii') } : function asciistrn(b :Uint8Array, start :int, end :int) :string { // fallback implementation b = start > 0 && end < b.length ? b.subarray(start, end) : b return String.fromCharCode.apply(null, b) } ) // bufcmp compares two arrays of bytes // export function bufcmp( a :ArrayLike<byte>, b :ArrayLike<byte>, aStart :int = 0, aEnd :int = a.length, bStart :int = 0, bEnd :int = b.length, ) :int { if (a === b) { return 0 } var ai = aStart, bi = bStart for (; ai != aEnd && bi != bEnd; ++ai, ++bi) { if (a[ai] < b[bi]) { return -1 } if (b[bi] < a[ai]) { return 1 } } var aL = aEnd - aStart, bL = bEnd - bStart return ( aL < bL ? -1 : bL < aL ? 1 : 0 ) } // asbuf returns a byte buffer for a // export let asbuf :(a :ArrayLike<byte>) => Uint8Array if (typeof Buffer != 'undefined') { asbuf = (a :ArrayLike<byte>) => { if (a instanceof Buffer || a instanceof Uint8Array) { return a as Uint8Array } if ( (a as any).buffer && (a as any).byteOffset !== undefined && (a as any).byteLength !== undefined ) { return Buffer.from( (a as any).buffer as ArrayBuffer, (a as any).byteOffset as int, (a as any).byteLength as int ) as Uint8Array } const buf = Buffer.allocUnsafe(a.length) for (let i = 0; i < a.length; ++i) { buf[i] = a[i] } return buf as Uint8Array } // function asnodebuf(a :ArrayLike<byte>) :Buffer { // return (a instanceof Buffer) ? a : new Buffer(asbuf(a)) // } // bufcmp1 = (a, b, aStart, aEnd, bStart, bEnd) => { // if (a === b) { // return 0 // } // // Note: although TS type decarations may say that Buffer.compare // // only accepts a Buffer, in fact it also accepts a Uint8Array. // if (a instanceof Buffer && // (b instanceof Buffer || b instanceof Uint8Array)) // { // return a.compare(b as Buffer, bStart, bEnd, aStart, aEnd) // } // if (b instanceof Buffer && // (a instanceof Buffer || a instanceof Uint8Array)) // { // return b.compare(a as Buffer, aStart, aEnd, bStart, bEnd) // } // const abuf = asnodebuf(a) // const bbuf = asbuf(b) as Buffer // return abuf.compare(bbuf, bStart, bEnd, aStart, aEnd) // } } export interface ByteWriter { writeByte(b :int) :void writeNbytes(b :int, n :int) :void write(src :Uint8Array, srcStart? :int, srcEnd? :int) :int } export class AppendBuffer implements ByteWriter { buffer :Uint8Array length :int // current offset constructor(size :int) { this.length = 0 this.buffer = new Uint8Array(size) } reset() { this.length = 0 } // Make sure there's space for at least `size` additional bytes reserve(addlSize :int) { if (this.length + addlSize >= this.buffer.length) { this._grow(addlSize) } } // bytes returns a Uint8Array of the written bytes which references the underlying storage. // Further modifications are observable both by the receiver and the returned array. // Use // bytes() :Uint8Array { return this.buffer.subarray(0, this.length) } // bytesCopy returns a Uint8Array of the written bytes as a copy. // bytesCopy() :Uint8Array { return this.buffer.slice(0, this.length) } // slice(start :int = 0, end? :int) :Uint8Array { // const _end = end === undefined ? this.length : Math.min(this.length, end) // if (this.buffer.length - (_end - start) < 128) { // // trade memory usage for speed by avoiding allocation & copy // return this.buffer.subarray(start, _end) // } // return this.buffer.slice(start, _end) // } writeByte(b :int) :void { if (this.length >= this.buffer.length) { this._grow(8) } this.buffer[this.length++] = b } // write b n times writeNbytes(b :int, n :int) :void { if (this.length + n >= this.buffer.length) { this._grow(n) } let end = this.length + n this.buffer.fill(b, this.length, end) this.length = end } write(src :Uint8Array, srcStart? :int, srcEnd? :int) :int { if (srcStart === undefined) { srcStart = 0 } const end = (srcEnd === undefined) ? src.length : srcEnd const size = end - srcStart if (this.length + size >= this.buffer.length) { this._grow(size) } this.buffer.set(src.subarray(srcStart, srcEnd), this.length) this.length += size return size } private _grow(minAddlSize :int) { this.buffer = bufcopy( this.buffer, Math.max(minAddlSize, this.buffer.length) ) } } const stackFrameRe = /\s*at\s+(?:[^\s]+\.|)([^\s\.]+)\s+(?:\[as ([^\]]+)\]\s+|)\((?:.+[\/ ]src\/([^\:]+)|([^\:]*))(?:\:(\d+)\:(\d+)|.*)\)/ // 1: name // 2: as-name | undefined // 3: src-filename // 4: filename // 5: line // 6: column // debug function export const debuglog = DEBUG ? _debuglog : function(..._ :any[]){} function _debuglog(...v :any[]) { let stackFrame = "" if (Error.captureStackTrace) { const e = {stack:''} Error.captureStackTrace(e, _debuglog) stackFrame = e.stack.split(/\n/, 2)[1] } else { let e = new Error() if (e.stack) { stackFrame = e.stack.split(/\n/, 3)[2] } } let prefix = "DEBUG>" let suffix = "" if (stackFrame) { let m = stackFrameRe.exec(stackFrame) // example: "at Foo.bar [as lol] (/<co> src/parser.ts:1839:5)" // m = { 1:"bar", 2:"lol", 3:"parser.ts", 5:"1839", 6:"5" } // // example: "at Foo.bar (/<co> src/parser.ts:1839:5)" // m = { 1:"bar", 3:"parser.ts", 5:"1839", 6:"5" } // // example: "at Foo.bar [as lol] (/abc/def:123:45)" // m = { 1:"bar", 2:"lol", 4:"/abc/def", 5:"123", 6:"45" } // // example: "at Foo.bar [as lol] (blabla)" // m = { 1:"foo", 4:"blabla" } // if (m) { const fun = m[2] || m[1] const origin = m[3] || m[4] prefix = fun + '>' if (origin) { const trmsg = String(v[0]) if (trmsg.indexOf('TODO:') == 0 || trmsg.indexOf('TODO ') == 0) { // message start with "TODO" prefix = 'TODO src/' + origin + ' ' + fun + '>' v[0] = trmsg.substr(5).replace(/^\s*/, '') } suffix = `at src/${origin}:${m[5]}:${m[6]}` } } } v.splice(0, 0, prefix) if (suffix) { v.push(suffix) } console.log.apply(console, v) } // is2pow returns true if n is a power-of-two number. // n must be a positive non-zero integer. // export function is2pow(n :int) :bool { assert(n > 0) return (n & (n - 1)) == 0 } // mstr takes a multi-line string as input and strips a whitespace prefix from each line // when the last line is purely whitespace. // export function mstr(s :string) :string { let p = s.lastIndexOf("\n") if (p == -1) { return s } let ind = s.substr(p + 1) for (let i = 0; i < ind.length; i++) { let c = ind.charCodeAt(i) if (c != 0x20 && c != 0x09) { // SP TAB // last line is not just whitespace -- treat as vanilla string return s } } s = s.substr(s.charCodeAt(0) == 0x0A ? 1 : 0, p) // strip first LF + last line let lines :string[] = [] for (let line of s.split("\n")) { if (line.length == 0) { lines.push(line) } else if (!line.startsWith(ind)) { // some line does not begin with ind -- treat as vanilla string return s } else { lines.push(line.substr(ind.length)) } } return lines.join("\n") }
the_stack
'use strict'; import { createScanner } from './scanner.ts'; import { JSONPath, JSONVisitor, Location, Node, NodeType, ParseError, ParseErrorCode, ParseOptions, ScanError, Segment, SyntaxKind } from './jsonc.ts';; namespace ParseOptions { export const DEFAULT = { allowTrailingComma: false }; } interface NodeImpl extends Node { type: NodeType; value?: any; offset: number; length: number; colonOffset?: number; parent?: NodeImpl; children?: NodeImpl[]; } /** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */ export function getLocation(text: string, position: number): Location { const segments: Segment[] = []; // strings or numbers const earlyReturnException = new Object(); let previousNode: NodeImpl | undefined = undefined; const previousNodeInst: NodeImpl = { value: {}, offset: 0, length: 0, type: 'object', parent: undefined }; let isAtPropertyKey = false; function setPreviousNode(value: string, offset: number, length: number, type: NodeType) { previousNodeInst.value = value; previousNodeInst.offset = offset; previousNodeInst.length = length; previousNodeInst.type = type; previousNodeInst.colonOffset = undefined; previousNode = previousNodeInst; } try { visit(text, { onObjectBegin: (offset: number, length: number) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; isAtPropertyKey = position > offset; segments.push(''); // push a placeholder (will be replaced) }, onObjectProperty: (name: string, offset: number, length: number) => { if (position < offset) { throw earlyReturnException; } setPreviousNode(name, offset, length, 'property'); segments[segments.length - 1] = name; if (position <= offset + length) { throw earlyReturnException; } }, onObjectEnd: (offset: number, length: number) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.pop(); }, onArrayBegin: (offset: number, length: number) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.push(0); }, onArrayEnd: (offset: number, length: number) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.pop(); }, onLiteralValue: (value: any, offset: number, length: number) => { if (position < offset) { throw earlyReturnException; } setPreviousNode(value, offset, length, getNodeType(value)); if (position <= offset + length) { throw earlyReturnException; } }, onSeparator: (sep: string, offset: number, length: number) => { if (position <= offset) { throw earlyReturnException; } if (sep === ':' && previousNode && previousNode.type === 'property') { previousNode.colonOffset = offset; isAtPropertyKey = false; previousNode = undefined; } else if (sep === ',') { const last = segments[segments.length - 1]; if (typeof last === 'number') { segments[segments.length - 1] = last + 1; } else { isAtPropertyKey = true; segments[segments.length - 1] = ''; } previousNode = undefined; } } }); } catch (e) { if (e !== earlyReturnException) { throw e; } } return { path: segments, previousNode, isAtPropertyKey, matches: (pattern: Segment[]) => { let k = 0; for (let i = 0; k < pattern.length && i < segments.length; i++) { if (pattern[k] === segments[i] || pattern[k] === '*') { k++; } else if (pattern[k] !== '**') { return false; } } return k === pattern.length; } }; } /** * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * Therefore always check the errors list to find out if the input was valid. */ export function parse(text: string, errors: ParseError[] = [], options: ParseOptions = ParseOptions.DEFAULT): any { let currentProperty: string | null = null; let currentParent: any = []; const previousParents: any[] = []; function onValue(value: any) { if (Array.isArray(currentParent)) { (<any[]>currentParent).push(value); } else if (currentProperty !== null) { currentParent[currentProperty] = value; } } const visitor: JSONVisitor = { onObjectBegin: () => { const object = {}; onValue(object); previousParents.push(currentParent); currentParent = object; currentProperty = null; }, onObjectProperty: (name: string) => { currentProperty = name; }, onObjectEnd: () => { currentParent = previousParents.pop(); }, onArrayBegin: () => { const array: any[] = []; onValue(array); previousParents.push(currentParent); currentParent = array; currentProperty = null; }, onArrayEnd: () => { currentParent = previousParents.pop(); }, onLiteralValue: onValue, onError: (error: ParseErrorCode, offset: number, length: number) => { errors.push({ error, offset, length }); } }; visit(text, visitor, options); return currentParent[0]; } /** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */ export function parseTree(text: string, errors: ParseError[] = [], options: ParseOptions = ParseOptions.DEFAULT): Node { let currentParent: NodeImpl = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root function ensurePropertyComplete(endOffset: number) { if (currentParent.type === 'property') { currentParent.length = endOffset - currentParent.offset; currentParent = currentParent.parent!; } } function onValue(valueNode: Node): Node { currentParent.children!.push(valueNode); return valueNode; } const visitor: JSONVisitor = { onObjectBegin: (offset: number) => { currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] }); }, onObjectProperty: (name: string, offset: number, length: number) => { currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] }); currentParent.children!.push({ type: 'string', value: name, offset, length, parent: currentParent }); }, onObjectEnd: (offset: number, length: number) => { ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete currentParent.length = offset + length - currentParent.offset; currentParent = currentParent.parent!; ensurePropertyComplete(offset + length); }, onArrayBegin: (offset: number, length: number) => { currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] }); }, onArrayEnd: (offset: number, length: number) => { currentParent.length = offset + length - currentParent.offset; currentParent = currentParent.parent!; ensurePropertyComplete(offset + length); }, onLiteralValue: (value: any, offset: number, length: number) => { onValue({ type: getNodeType(value), offset, length, parent: currentParent, value }); ensurePropertyComplete(offset + length); }, onSeparator: (sep: string, offset: number, length: number) => { if (currentParent.type === 'property') { if (sep === ':') { currentParent.colonOffset = offset; } else if (sep === ',') { ensurePropertyComplete(offset); } } }, onError: (error: ParseErrorCode, offset: number, length: number) => { errors.push({ error, offset, length }); } }; visit(text, visitor, options); const result = currentParent.children![0]; if (result) { delete result.parent; } return result; } /** * Finds the node at the given path in a JSON DOM. */ export function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined { if (!root) { return undefined; } let node = root; for (let segment of path) { if (typeof segment === 'string') { if (node.type !== 'object' || !Array.isArray(node.children)) { return undefined; } let found = false; for (const propertyNode of node.children) { if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment) { node = propertyNode.children[1]; found = true; break; } } if (!found) { return undefined; } } else { const index = <number>segment; if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) { return undefined; } node = node.children[index]; } } return node; } /** * Gets the JSON path of the given JSON DOM node */ export function getNodePath(node: Node): JSONPath { if (!node.parent || !node.parent.children) { return []; } const path = getNodePath(node.parent); if (node.parent.type === 'property') { const key = node.parent.children[0].value; path.push(key); } else if (node.parent.type === 'array') { const index = node.parent.children.indexOf(node); if (index !== -1) { path.push(index); } } return path; } /** * Evaluates the JavaScript object of the given JSON DOM node */ export function getNodeValue(node: Node): any { switch (node.type) { case 'array': return node.children!.map(getNodeValue); case 'object': const obj = Object.create(null); for (let prop of node.children!) { const valueNode = prop.children![1]; if (valueNode) { obj[prop.children![0].value] = getNodeValue(valueNode); } } return obj; case 'null': case 'string': case 'number': case 'boolean': return node.value; default: return undefined; } } export function contains(node: Node, offset: number, includeRightBound = false): boolean { return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length)); } /** * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. */ export function findNodeAtOffset(node: Node, offset: number, includeRightBound = false): Node | undefined { if (contains(node, offset, includeRightBound)) { const children = node.children; if (Array.isArray(children)) { for (let i = 0; i < children.length && children[i].offset <= offset; i++) { const item = findNodeAtOffset(children[i], offset, includeRightBound); if (item) { return item; } } } return node; } return undefined; } /** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */ export function visit(text: string, visitor: JSONVisitor, options: ParseOptions = ParseOptions.DEFAULT): any { const _scanner = createScanner(text, false); function toNoArgVisit(visitFunction?: (offset: number, length: number, startLine: number, startCharacter: number) => void): () => void { return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; } function toOneArgVisit<T>(visitFunction?: (arg: T, offset: number, length: number, startLine: number, startCharacter: number) => void): (arg: T) => void { return visitFunction ? (arg: T) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; } const onObjectBegin = toNoArgVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisit(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisit(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisit(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); const disallowComments = options && options.disallowComments; const allowTrailingComma = options && options.allowTrailingComma; function scanNext(): number { while (true) { const token = _scanner.scan(); switch (_scanner.getTokenError()) { case ScanError.InvalidUnicode: handleError(ParseErrorCode.InvalidUnicode); break; case ScanError.InvalidEscapeCharacter: handleError(ParseErrorCode.InvalidEscapeCharacter); break; case ScanError.UnexpectedEndOfNumber: handleError(ParseErrorCode.UnexpectedEndOfNumber); break; case ScanError.UnexpectedEndOfComment: if (!disallowComments) { handleError(ParseErrorCode.UnexpectedEndOfComment); } break; case ScanError.UnexpectedEndOfString: handleError(ParseErrorCode.UnexpectedEndOfString); break; case ScanError.InvalidCharacter: handleError(ParseErrorCode.InvalidCharacter); break; } switch (token) { case SyntaxKind.LineCommentTrivia: case SyntaxKind.BlockCommentTrivia: if (disallowComments) { handleError(ParseErrorCode.InvalidCommentToken); } else { onComment(); } break; case SyntaxKind.Unknown: handleError(ParseErrorCode.InvalidSymbol); break; case SyntaxKind.Trivia: case SyntaxKind.LineBreakTrivia: break; default: return token; } } } function handleError(error: ParseErrorCode, skipUntilAfter: number[] = [], skipUntil: number[] = []): void { onError(error); if (skipUntilAfter.length + skipUntil.length > 0) { let token = _scanner.getToken(); while (token !== SyntaxKind.EOF) { if (skipUntilAfter.indexOf(token) !== -1) { scanNext(); break; } else if (skipUntil.indexOf(token) !== -1) { break; } token = scanNext(); } } } function parseString(isValue: boolean): boolean { const value = _scanner.getTokenValue(); if (isValue) { onLiteralValue(value); } else { onObjectProperty(value); } scanNext(); return true; } function parseLiteral(): boolean { switch (_scanner.getToken()) { case SyntaxKind.NumericLiteral: let value = 0; try { value = JSON.parse(_scanner.getTokenValue()); if (typeof value !== 'number') { handleError(ParseErrorCode.InvalidNumberFormat); value = 0; } } catch (e) { handleError(ParseErrorCode.InvalidNumberFormat); } onLiteralValue(value); break; case SyntaxKind.NullKeyword: onLiteralValue(null); break; case SyntaxKind.TrueKeyword: onLiteralValue(true); break; case SyntaxKind.FalseKeyword: onLiteralValue(false); break; default: return false; } scanNext(); return true; } function parseProperty(): boolean { if (_scanner.getToken() !== SyntaxKind.StringLiteral) { handleError(ParseErrorCode.PropertyNameExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]); return false; } parseString(false); if (_scanner.getToken() === SyntaxKind.ColonToken) { onSeparator(':'); scanNext(); // consume colon if (!parseValue()) { handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]); } } else { handleError(ParseErrorCode.ColonExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]); } return true; } function parseObject(): boolean { onObjectBegin(); scanNext(); // consume open brace let needsComma = false; while (_scanner.getToken() !== SyntaxKind.CloseBraceToken && _scanner.getToken() !== SyntaxKind.EOF) { if (_scanner.getToken() === SyntaxKind.CommaToken) { if (!needsComma) { handleError(ParseErrorCode.ValueExpected, [], []); } onSeparator(','); scanNext(); // consume comma if (_scanner.getToken() === SyntaxKind.CloseBraceToken && allowTrailingComma) { break; } } else if (needsComma) { handleError(ParseErrorCode.CommaExpected, [], []); } if (!parseProperty()) { handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBraceToken, SyntaxKind.CommaToken]); } needsComma = true; } onObjectEnd(); if (_scanner.getToken() !== SyntaxKind.CloseBraceToken) { handleError(ParseErrorCode.CloseBraceExpected, [SyntaxKind.CloseBraceToken], []); } else { scanNext(); // consume close brace } return true; } function parseArray(): boolean { onArrayBegin(); scanNext(); // consume open bracket let needsComma = false; while (_scanner.getToken() !== SyntaxKind.CloseBracketToken && _scanner.getToken() !== SyntaxKind.EOF) { if (_scanner.getToken() === SyntaxKind.CommaToken) { if (!needsComma) { handleError(ParseErrorCode.ValueExpected, [], []); } onSeparator(','); scanNext(); // consume comma if (_scanner.getToken() === SyntaxKind.CloseBracketToken && allowTrailingComma) { break; } } else if (needsComma) { handleError(ParseErrorCode.CommaExpected, [], []); } if (!parseValue()) { handleError(ParseErrorCode.ValueExpected, [], [SyntaxKind.CloseBracketToken, SyntaxKind.CommaToken]); } needsComma = true; } onArrayEnd(); if (_scanner.getToken() !== SyntaxKind.CloseBracketToken) { handleError(ParseErrorCode.CloseBracketExpected, [SyntaxKind.CloseBracketToken], []); } else { scanNext(); // consume close bracket } return true; } function parseValue(): boolean { switch (_scanner.getToken()) { case SyntaxKind.OpenBracketToken: return parseArray(); case SyntaxKind.OpenBraceToken: return parseObject(); case SyntaxKind.StringLiteral: return parseString(true); default: return parseLiteral(); } } scanNext(); if (_scanner.getToken() === SyntaxKind.EOF) { if (options.allowEmptyContent) { return true; } handleError(ParseErrorCode.ValueExpected, [], []); return false; } if (!parseValue()) { handleError(ParseErrorCode.ValueExpected, [], []); return false; } if (_scanner.getToken() !== SyntaxKind.EOF) { handleError(ParseErrorCode.EndOfFileExpected, [], []); } return true; } /** * Takes JSON with JavaScript-style comments and remove * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */ export function stripComments(text: string, replaceCh?: string): string { let _scanner = createScanner(text), parts: string[] = [], kind: number, offset = 0, pos: number; do { pos = _scanner.getPosition(); kind = _scanner.scan(); switch (kind) { case SyntaxKind.LineCommentTrivia: case SyntaxKind.BlockCommentTrivia: case SyntaxKind.EOF: if (offset !== pos) { parts.push(text.substring(offset, pos)); } if (replaceCh !== undefined) { parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh)); } offset = _scanner.getPosition(); break; } } while (kind !== SyntaxKind.EOF); return parts.join(''); } export function getNodeType(value: any): NodeType { switch (typeof value) { case 'boolean': return 'boolean'; case 'number': return 'number'; case 'string': return 'string'; case 'object': { if (!value) { return 'null'; } else if (Array.isArray(value)) { return 'array'; } return 'object'; } default: return 'null'; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as k8s from "@pulumi/kubernetes"; import * as input from "@pulumi/kubernetes/types/input"; import * as vol from "./volume"; import * as ds from "./docker-secret"; import * as utils from "./utils"; // Pulumi namespace for the new PodBuilder pulumi.ComponentResource const pulumiComponentNamespace: string = "pulumi:kx:PodBuilder"; // PodBuilderArgs implements the spec settings for a Kubernetes Pod. export type PodBuilderArgs = { // The spec of the Pod. podSpec: input.core.v1.PodSpec; }; // JobBuilderArgs implements the spec settings for a Kubernetes Job. export type JobBuilderArgs = { // The number of retries before marking the job as failed. Defaults to 6. backoffLimit?: pulumi.Input<number>; // The max time the CronJob can run before being terminated. Defaults to 10 // minutes. activeDeadlineSeconds?: pulumi.Input<number>; }; // CronJobBuilderArgs implements the spec settings for a Kubernetes CronJob. export type CronJobBuilderArgs = { // The Cron scheduling extended format. k8s uses the standard 5-field format. schedule: string, // The number of successful finished jobs to retain. This is a pointer to // distinguish between explicit zero and not specified. Defaults to 3. successfulJobsHistoryLimit?: pulumi.Input<number>, // The number of failed finished jobs to retain. This is a pointer to // distinguish between explicit zero and not specified. Defaults to 1. failedJobsHistoryLimit?: pulumi.Input<number>, // The JobBuilderArgs for the CronJob. jobBuilderArgs: JobBuilderArgs, }; // DeploymentdBuilderArgs implements the spec settings for a Kubernetes // Deployment. export type DeploymentBuilderArgs = { // The number of desired replicas of the Pods. replicas?: pulumi.Input<number>; }; // ReplicaSetdBuilderArgs implements the spec settings for a Kubernetes // ReplicaSet. export type ReplicaSetBuilderArgs = { // The number of desired replicas of the Pods. replicas?: pulumi.Input<number>; }; // DaemonSetBuilderArgs implements the spec settings for a Kubernetes // DaemonSet. export type DaemonSetBuilderArgs = { // An update strategy to replace existing DaemonSet pods with new pods. // Defaults to "RollingUpdate". updateStrategy?: pulumi.Input<string>; // The minimum number of seconds for which a newly created DaemonSet pod // should be ready without any of its container crashing, for it to be // considered available. Defaults to 0 (pod will be considered available as // soon as it is ready). minReadySeconds?: pulumi.Input<number>; // The number of old history to retain to allow rollback. This is a pointer to // distinguish between explicit zero and not specified. Defaults to 10. revisionHistoryLimit?: pulumi.Input<number>; }; // PodBuilder implements a Kubernetes Pod, with the specified PodBuilderArgs. export class PodBuilder extends pulumi.ComponentResource { public readonly podBuilderName: string; public readonly podBuilderProvider: k8s.Provider; public readonly podBuilder: input.core.v1.Pod; constructor( name: string, provider: k8s.Provider, args: PodBuilderArgs, opts?: pulumi.ComponentResourceOptions, ) { super(pulumiComponentNamespace, name, args, opts); if (args === undefined || provider === undefined) { return {} as PodBuilder; } this.podBuilderName = name; this.podBuilderProvider = provider; // Create the podBuilder base. this.podBuilder = {spec: args.podSpec}; let pb = (<any>this.podBuilder); if (pb.spec.initContainers === undefined) { pb.spec.initContainers = []; } if (pb.spec.volumes === undefined) { pb.spec.volumes = []; } // Add Downward API environment variables to containers. vol.addEnvVars(vol.downwardApiEnvVars, pb.spec.initContainers); vol.addEnvVars(vol.downwardApiEnvVars, pb.spec.containers); // Mount the Downward API volume to the mount path. this.mountVolume( "/etc/podinfo", vol.downwardApiVolume); } // The options for the Pod's manifest metadata public withMetadata( metadata: input.meta.v1.ObjectMeta, ) { let pb = (<any>this.podBuilder); pb.metadata = metadata; return this; }; // Add Docker Registry creds to pull down private container images. public addImagePullSecrets( dockerConfigJson?: string, ) { if (dockerConfigJson === undefined) { return this; } let pb = (<any>this.podBuilder); // Create a new Secret const dockerSecret = new ds.DockerSecretBuilder( this.podBuilderName, this.podBuilderProvider, { labels: pb.metadata.labels, namespace: pb.metadata.namespace, dockerConfigJson: dockerConfigJson, }, ); // Create a new Secret from the DockerSecretBuilder. let secret = dockerSecret.toSecret(); let secretName = secret.metadata.apply(m => m.name); // Add the Secret to the imagePullSecrets. if (pb.spec.imagePullSecrets === undefined ) { pb.spec.imagePullSecrets = []; } pb.spec.imagePullSecrets.push({ name: secretName}); return this; }; // Adds environment variables from a ConfigMap into the initContainers // and containers of the the Pod. public addEnvVarsFromConfigMap ( configMapName: pulumi.Input<string>, ) { let initContainers = (<any>this.podBuilder).spec.initContainers; let containers = (<any>this.podBuilder).spec.containers; if (initContainers !== undefined) { if (initContainers.envFrom === undefined) { initContainers.envFrom = []; } vol.addEnvVarsFromConfigMap(configMapName, initContainers); } if (containers !== undefined) { if (containers.envFrom === undefined) { containers.envFrom = []; } vol.addEnvVarsFromConfigMap(configMapName, containers); } return this; }; // Adds environment variables from a Secret into the initContainers // and containers of the the Pod. public addEnvVarsFromSecret ( secretName: pulumi.Input<string>, ) { let initContainers = (<any>this.podBuilder).spec.initContainers; let containers = (<any>this.podBuilder).spec.containers; if (initContainers !== undefined) { if (initContainers.envFrom === undefined) { initContainers.envFrom = []; } vol.addEnvVarsFromSecret(secretName, initContainers); } if (containers !== undefined) { if (containers.envFrom === undefined) { containers.envFrom = []; } vol.addEnvVarsFromSecret(secretName, containers); } return this; }; // Adds environment variables into the initContainers and containers of // the the Pod. public addEnvVar ( environmentVar: input.core.v1.EnvVar, ) { let initContainers = (<any>this.podBuilder).spec.initContainers; let containers = (<any>this.podBuilder).spec.containers; if (initContainers !== undefined) { if (initContainers.env === undefined) { initContainers.env = []; } vol.addEnvVar(environmentVar, initContainers); } if (containers !== undefined) { if (containers.env === undefined) { containers.env = []; } vol.addEnvVar(environmentVar, containers); } return this; }; // Adds a volume to a mountPath on the containers. public mountVolume ( mountPath: string, volume: input.core.v1.Volume, ) { let initContainers = (<any>this.podBuilder).spec.initContainers; let containers = (<any>this.podBuilder).spec.containers; let volumes = (<any>this.podBuilder).spec.volumes; if (initContainers === undefined || containers === undefined) { return this; } // Mount the volume to the container's mount path. vol.addVolumeMount(volume.name, mountPath, [...initContainers, ...containers]); // Add the volumes to the volumes group of the Pod vol.addVolume(volume, volumes); return this; }; // Adds an initContainer to the Pod. // This is an array of containers that operates as an in-order chain. All // initContainers must successfully exit before the Pods's containers run. public addInitContainer ( initContainer: input.core.v1.Container, ) { let initContainers = (<any>this.podBuilder).spec.initContainers; if (initContainers === undefined) { initContainers = []; } // Add Downward API environment variables to containers. vol.addEnvVars(vol.downwardApiEnvVars, [initContainer]); // Mount the Downward API volume to the mount path. vol.addVolumeMount(vol.downwardApiVolume.name, "/etc/podinfo", [initContainer]); initContainers.push(initContainer); return this; }; // Adds a sidecar to the Pod. public addSidecar ( container: input.core.v1.Container, ) { let containers = (<any>this.podBuilder).spec.containers; if (containers === undefined) { return this; } // Add Downward API environment variables to containers. vol.addEnvVars(vol.downwardApiEnvVars, [container]); // Mount the Downward API volume to the mout path. vol.addVolumeMount(vol.downwardApiVolume.name, "/etc/podinfo", [container]); containers.push(container); return this; }; // Create a new Pod resource (output type) from the PodBuilder in k8s. public createPod(): k8s.core.v1.Pod { return new k8s.core.v1.Pod( this.podBuilderName, this.podBuilder, {provider: this.podBuilderProvider}, ); }; // Create a new Job resource (output type) from the PodBuilder in k8s. public createJob( name: string, jobArgs?: JobBuilderArgs, ): k8s.batch.v1.Job { const jobBuilder = makeJobBuilderBase(this.podBuilder, jobArgs); return new k8s.batch.v1.Job( name, jobBuilder, {provider: this.podBuilderProvider}, ); }; // Create a new CronJob resource (output type) from the PodBuilder in k8s. public createCronJob( name: string, cronJobArgs?: CronJobBuilderArgs, ): k8s.batch.v1beta1.CronJob { const cronJobBuilder = makeCronJobBuilderBase(this.podBuilder, cronJobArgs); return new k8s.batch.v1beta1.CronJob( name, cronJobBuilder, {provider: this.podBuilderProvider}, ); }; // Create a new Deployment from the PodBuilder. public createDeployment( name: string, deploymentArgs?: DeploymentBuilderArgs, ): k8s.apps.v1.Deployment { const deployBuilder = makeDeploymentBuilderBase(this.podBuilder, deploymentArgs); return new k8s.apps.v1.Deployment( name, deployBuilder, {provider: this.podBuilderProvider}, ); }; // Create a new ReplicaSet from the PodBuilder. public createReplicaSet( name: string, replicaSetArgs?: ReplicaSetBuilderArgs, ): k8s.apps.v1.ReplicaSet { const replicaSetBuilder = makeReplicaSetBuilderBase(this.podBuilder, replicaSetArgs); return new k8s.apps.v1.ReplicaSet( name, replicaSetBuilder, {provider: this.podBuilderProvider}, ); }; // Create a new DaemonSet from the PodBuilder. public createDaemonSet( name: string, daemonSetArgs?: DaemonSetBuilderArgs, ): k8s.extensions.v1beta1.DaemonSet { const daemonSetBuilder = makeDaemonSetBuilderBase(this.podBuilder, daemonSetArgs); return new k8s.extensions.v1beta1.DaemonSet( name, daemonSetBuilder, {provider: this.podBuilderProvider}, ); }; } // Create a base manifest for a Kubernetes Job. export function makeJobBuilderBase( podBuilder: input.core.v1.Pod, jobBuilderArgs?: JobBuilderArgs, ): input.batch.v1.Job { if (podBuilder === undefined) { return {} as input.batch.v1.Job; } let pb = (<any>podBuilder); let backoffLimit, activeDeadlineSeconds; if (jobBuilderArgs !== undefined) { backoffLimit = jobBuilderArgs.backoffLimit; activeDeadlineSeconds = jobBuilderArgs.activeDeadlineSeconds; } return { metadata: { labels: pb.metadata.labels, namespace: utils.objOrDefault(pb.metadata.namespace, "default"), }, spec: { backoffLimit: utils.objOrDefault(backoffLimit, 6), // # of retries before the Job fails. activeDeadlineSeconds: utils.objOrDefault(activeDeadlineSeconds, 600), // max time before termination. template: { metadata: pulumi.output(pb.metadata), spec: pulumi.output(pb.spec), }, }, }; } // Create a base manifest for a Kubernetes CronJob. export function makeCronJobBuilderBase( podBuilder: input.core.v1.Pod, cronJobArgs?: CronJobBuilderArgs, ): input.batch.v1beta1.CronJob { if (podBuilder === undefined) { return {} as input.batch.v1beta1.CronJob; } let pb = (<any>podBuilder); let backoffLimit, schedule, successfulJobsHistoryLimit; let failedJobsHistoryLimit, activeDeadlineSeconds; if (cronJobArgs !== undefined) { schedule = cronJobArgs.schedule; backoffLimit = cronJobArgs.jobBuilderArgs.backoffLimit; successfulJobsHistoryLimit = cronJobArgs.successfulJobsHistoryLimit; failedJobsHistoryLimit = cronJobArgs.failedJobsHistoryLimit; activeDeadlineSeconds = cronJobArgs.jobBuilderArgs.activeDeadlineSeconds; } return { metadata: { labels: pb.metadata.labels, namespace: utils.objOrDefault(pb.metadata.namespace, "default"), }, spec: { schedule: utils.objOrDefault(schedule, ""), successfulJobsHistoryLimit: utils.objOrDefault(successfulJobsHistoryLimit, 3), failedJobsHistoryLimit: utils.objOrDefault(failedJobsHistoryLimit, 1), jobTemplate: { spec: { backoffLimit: utils.objOrDefault( backoffLimit, 6), // # of retries before the Job fails. activeDeadlineSeconds: utils.objOrDefault( activeDeadlineSeconds, 600), // max time before termination. template: { metadata: pulumi.output(pb.metadata), spec: pulumi.output(pb.spec), }, }, }, }, }; } // Create a base manifest for a Kubernetes Deployment. export function makeDeploymentBuilderBase( podBuilder: input.core.v1.Pod, deploymentArgs?: DeploymentBuilderArgs, ): input.apps.v1.Deployment { if (podBuilder === undefined) { return {} as input.apps.v1.Deployment; } let pb = (<any>podBuilder); let replicas; if (deploymentArgs !== undefined) { replicas = deploymentArgs.replicas; } return { metadata: { labels: pb.metadata.labels, namespace: utils.objOrDefault(pb.metadata.namespace, "default"), }, spec: { replicas: utils.objOrDefault(replicas, 1), selector: { matchLabels: pb.metadata.labels }, template: { metadata: pulumi.output(pb.metadata), spec: pulumi.output(pb.spec), }, }, }; } // Create a base manifest for a Kubernetes ReplicaSet. export function makeReplicaSetBuilderBase( podBuilder: input.core.v1.Pod, replicaSetArgs?: ReplicaSetBuilderArgs, ): input.apps.v1.ReplicaSet { if (podBuilder === undefined) { return {} as input.apps.v1.ReplicaSet; } let pb = (<any>podBuilder); let replicas; if (replicaSetArgs !== undefined) { replicas = replicaSetArgs.replicas; } return { metadata: { labels: pb.metadata.labels, namespace: utils.objOrDefault(pb.metadata.namespace, "default"), }, spec: { replicas: utils.objOrDefault(replicas, 1), selector: { matchLabels: pb.metadata.labels }, template: { metadata: pulumi.output(pb.metadata), spec: pulumi.output(pb.spec), }, }, }; } // Create a base manifest for a Kubernetes DaemonSet. export function makeDaemonSetBuilderBase( podBuilder: input.core.v1.Pod, daemonSetArgs?: DaemonSetBuilderArgs, ): input.extensions.v1beta1.DaemonSet { if (podBuilder === undefined) { return {} as input.extensions.v1beta1.DaemonSet; } let pb = (<any>podBuilder); let minReadySeconds; let revisionHistoryLimit; let updateStrategy; if (daemonSetArgs !== undefined) { minReadySeconds = daemonSetArgs.minReadySeconds; revisionHistoryLimit = daemonSetArgs.revisionHistoryLimit; updateStrategy = daemonSetArgs.updateStrategy; } return { metadata: { labels: pb.metadata.labels, namespace: utils.objOrDefault(pb.metadata.namespace, "default"), }, spec: { minReadySeconds: utils.objOrDefault(minReadySeconds, 0), revisionHistoryLimit: utils.objOrDefault(revisionHistoryLimit, 10), updateStrategy: {type: utils.objOrDefault(updateStrategy, "RollingUpdate")}, selector: { matchLabels: pb.metadata.labels }, template: { metadata: pulumi.output(pb.metadata), spec: pulumi.output(pb.spec), }, }, }; }
the_stack
import * as loginPage from '../../Base/pages/Login.po'; import { LoginPageData } from '../../Base/pagedata/LoginPageData'; import * as addTaskPage from '../../Base/pages/AddTasks.po'; import { AddTasksPageData } from '../../Base/pagedata/AddTasksPageData'; import * as dashboardPage from '../../Base/pages/Dashboard.po'; import * as organizationProjectsPage from '../../Base/pages/OrganizationProjects.po'; import * as logoutPage from '../../Base/pages/Logout.po'; import { OrganizationProjectsPageData } from '../../Base/pagedata/OrganizationProjectsPageData'; import { CustomCommands } from '../../commands'; import * as organizationTagsUserPage from '../../Base/pages/OrganizationTags.po'; import { OrganizationTagsPageData } from '../../Base/pagedata/OrganizationTagsPageData'; import * as faker from 'faker'; import * as manageEmployeesPage from '../../Base/pages/ManageEmployees.po'; import { Given, Then, When, And } from 'cypress-cucumber-preprocessor/steps'; const pageLoadTimeout = Cypress.config('pageLoadTimeout'); let firstName = faker.name.firstName(); let lastName = faker.name.lastName(); let username = faker.internet.userName(); let password = faker.internet.password(); let employeeEmail = faker.internet.email(); let imgUrl = faker.image.avatar(); // Login with email Given('Login with default credentials', () => { CustomCommands.login(loginPage, LoginPageData, dashboardPage); }); // Add new tag Then('User can add new tag', () => { dashboardPage.verifyAccountingDashboardIfVisible(); CustomCommands.addTag(organizationTagsUserPage, OrganizationTagsPageData); }); // Add new employee And('User can add new employee', () => { CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); CustomCommands.addEmployee( manageEmployeesPage, firstName, lastName, username, employeeEmail, password, imgUrl ); }); // Add new project And('User can add new project', () => { CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); CustomCommands.addProject( organizationProjectsPage, OrganizationProjectsPageData ); }); // Add new task When('User go to Tasks dashboard page', () => { cy.on('uncaught:exception', (err, runnable) => { return false; }); CustomCommands.logout(dashboardPage, logoutPage, loginPage); CustomCommands.clearCookies(); CustomCommands.login(loginPage, LoginPageData, dashboardPage); cy.visit('/#/pages/tasks/dashboard', { timeout: pageLoadTimeout }); }); Then('User can see gird button', () => { addTaskPage.gridBtnExists(); }); And('User can click on second grid button to change view', () => { addTaskPage.gridBtnClick(1); }); And('User can see Add task button', () => { addTaskPage.addTaskButtonVisible(); }); When('User click on Add task button', () => { addTaskPage.clickAddTaskButton(); }); Then('User will see project dropdown', () => { addTaskPage.selectProjectDropdownVisible(); }); When('User click on project dropdown', () => { addTaskPage.clickSelectProjectDropdown(); }); Then('User can select project from dropdown options', () => { addTaskPage.selectProjectOptionDropdown( AddTasksPageData.defaultTaskProject ); }); And('User can see employee dropdown', () => { addTaskPage.selectEmployeeDropdownVisible(); }); When('User click on employee dropdown', () => { addTaskPage.clickSelectEmployeeDropdown(); }); Then('User can select employee from dropdown options', () => { addTaskPage.selectEmployeeDropdownOption(0); addTaskPage.clickKeyboardButtonByKeyCode(9); }); And('User can see title input field', () => { addTaskPage.addTitleInputVisible(); }); And('User can add value for title', () => { addTaskPage.enterTitleInputData(AddTasksPageData.defaultTaskTitle); }); And('User can see due date input field', () => { addTaskPage.dueDateInputVisible(); }); And('User can enter value for due date', () => { addTaskPage.enterDueDateData(); addTaskPage.clickKeyboardButtonByKeyCode(9); }); And('User can see estimate days input field', () => { addTaskPage.estimateDaysInputVisible(); }); And('User can enter value for estimate days', () => { addTaskPage.enterEstiamteDaysInputData( AddTasksPageData.defaultTaskEstimateDays ); }); And('User can see estimate hours input field', () => { addTaskPage.estimateHoursInputVisible(); }); And('User can add value for estimate hours', () => { addTaskPage.enterEstiamteHoursInputData( AddTasksPageData.defaultTaskEstimateHours ); }); And('User can see estimate minutes input field', () => { addTaskPage.estimateMinutesInputVisible(); }); And('User can enter value for estimate minutes', () => { addTaskPage.enterEstimateMinutesInputData( AddTasksPageData.defaultTaskEstimateMinutes ); }); And('User can task description input field', () => { addTaskPage.taskDecriptionTextareaVisible(); }); And('User can enter value for description', () => { addTaskPage.enterTaskDescriptionTextareaData( AddTasksPageData.defaultTaskDescription ); }); And('User can see save task button', () => { addTaskPage.saveTaskButtonVisible(); }); When('User click on save task button', () => { addTaskPage.clickSaveTaskButton(); }); Then('Notification message will appear', () => { addTaskPage.waitMessageToHide(); }); And('User can verify task was created', () => { addTaskPage.verifyTaskExists(AddTasksPageData.defaultTaskTitle); }); // Duplicate task Then('User can see table populated with tasks', () => { addTaskPage.tasksTableVisible(); }); When('User click on table first row', () => { addTaskPage.selectTasksTableRow(0); }); Then('Duplicate task button will become active', () => { addTaskPage.duplicateOrEditTaskButtonVisible(); }); When('User click on duplicate task button', () => { addTaskPage.clickDuplicateOrEditTaskButton(0); }); Then('User will see confirm action button', () => { addTaskPage.confirmDuplicateOrEditTaskButtonVisible(); }); When('User click on confirm action button', () => { addTaskPage.clickConfirmDuplicateOrEditTaskButton(); }); Then('Notification message will appear', () => { addTaskPage.waitMessageToHide(); }); // Edit task And('User can see tasks table again', () => { addTaskPage.tasksTableVisible(); }); When('User select table first row', () => { addTaskPage.selectTasksTableRow(0); }); Then('Edit task button will become active', () => { addTaskPage.duplicateOrEditTaskButtonVisible(); }); When('User click on edit task button', () => { addTaskPage.clickDuplicateOrEditTaskButton(1); }); Then('User will see edit project dropdown', () => { addTaskPage.selectProjectDropdownVisible(); }); When('User click on edit project dropdown', () => { addTaskPage.clickSelectProjectDropdown(); }); Then('User can select new project from dropdown options', () => { addTaskPage.selectProjectOptionDropdown( AddTasksPageData.defaultTaskProject ); }); And('User can see edit title input field', () => { addTaskPage.addTitleInputVisible(); }); And('User can add value for edit title', () => { addTaskPage.enterTitleInputData(AddTasksPageData.editTaskTitle); }); And('User can see edit due date input field', () => { addTaskPage.dueDateInputVisible(); }); And('User can enter value for edit due date', () => { addTaskPage.enterDueDateData(); addTaskPage.clickKeyboardButtonByKeyCode(9); }); And('User can see edit estimate days input field', () => { addTaskPage.estimateDaysInputVisible(); }); And('User can enter value for estimate days edit', () => { addTaskPage.enterEstiamteDaysInputData( AddTasksPageData.defaultTaskEstimateDays ); }); And('User can see edit estimate hours input field', () => { addTaskPage.estimateHoursInputVisible(); }); And('User can add value for estimate hours edit', () => { addTaskPage.enterEstiamteHoursInputData( AddTasksPageData.defaultTaskEstimateHours ); }); And('User can see edit estimate minutes input field', () => { addTaskPage.estimateMinutesInputVisible(); }); And('User can enter value for estimate minutes edit', () => { addTaskPage.enterEstimateMinutesInputData( AddTasksPageData.defaultTaskEstimateMinutes ); }); And('User can task edit description input field', () => { addTaskPage.taskDecriptionTextareaVisible(); }); And('User can enter value for description edit', () => { addTaskPage.enterTaskDescriptionTextareaData( AddTasksPageData.defaultTaskDescription ); }); And('User can see save edited task button', () => { addTaskPage.saveTaskButtonVisible(); }); When('User click on save edited task button', () => { addTaskPage.clickSaveTaskButton(); }); Then('Notification message will appear', () => { addTaskPage.waitMessageToHide(); }); And('User can verify task was edited', () => { addTaskPage.verifyTaskExists(AddTasksPageData.editTaskTitle); }); // Delete task And('User can see table for tasks', () => { addTaskPage.tasksTableVisible(); }); When('User click on first table row', () => { addTaskPage.selectTasksTableRow(0); }); Then('User can see duplicate or edit task button', () => { addTaskPage.duplicateOrEditTaskButtonVisible(); }); When('User click on duplicate or edit task button', () => { addTaskPage.clickDuplicateOrEditTaskButton(1); }); Then('User can see confirm button', () => { addTaskPage.confirmDuplicateOrEditTaskButtonVisible(); }); When('User click on confirm button', () => { addTaskPage.clickConfirmDuplicateOrEditTaskButton(); }); Then('Notification message will appear', () => { addTaskPage.waitMessageToHide(); }); And('User can see tasks table again', () => { addTaskPage.tasksTableVisible(); }); When('User click on table first row', () => { addTaskPage.selectTasksTableRow(0); }); Then('Delete task button will become active', () => { addTaskPage.deleteTaskButtonVisible(); }); When('User click on delete task button', () => { addTaskPage.clickDeleteTaskButton(); }); Then('User can see confirm delete button', () => { addTaskPage.confirmDeleteTaskButtonVisible(); }); When('User click on confirm delete button', () => { addTaskPage.clickConfirmDeleteTaskButton(); }); Then('Notification message will appear', () => { addTaskPage.waitMessageToHide(); }); And('User can verify task was deleted', () => { addTaskPage.verifyElementIsDeleted(AddTasksPageData.editTaskTitle); }); When('User click on table first row', () => { addTaskPage.selectTasksTableRow(0); }); Then('Delete button will become active again', () => { addTaskPage.deleteTaskButtonVisible(); }); When('User click on delete task button', () => { addTaskPage.clickDeleteTaskButton(); }); Then('User will see confirm delete button again', () => { addTaskPage.confirmDeleteTaskButtonVisible(); }); And('User can click again on confirm delete task button', () => { addTaskPage.clickConfirmDeleteTaskButton(); });
the_stack
import { SerializableLiteral } from "./serializable-literal"; import blake from "blakejs"; import * as bls from "noble-bls12-381"; import secp256K1 from "secp256k1"; import base32 from "base32-encoding"; import { StartDealParams } from "./start-deal-params"; import cbor from "borc"; import { RandomNumberGenerator } from "@ganache/utils"; import { Message } from "./message"; import { Signature } from "./signature"; // https://spec.filecoin.io/appendix/address/ interface AddressConfig { type: string; } enum AddressProtocol { ID, SECP256K1, // Represents the address SECP256K1 protocol Actor, // Represents the address Actor protocol BLS, // Represents the address BLS protocol Unknown = 255 } enum AddressNetwork { Testnet = "t", Mainnet = "f", Unknown = "UNKNOWN" } function switchEndianness(hexString: string) { const regex = hexString.match(/.{2}/g); if (!regex) { throw new Error(`Could not switch endianness of hex string: ${hexString}`); } return regex.reverse().join(""); } class Address extends SerializableLiteral<AddressConfig> { get config() { return {}; } static readonly FirstNonSingletonActorId = 100; // Ref impl: https://git.io/JtgqT static readonly FirstMinerId = 1000; // Ref impl: https://git.io/Jt2WE static readonly CHECKSUM_BYTES = 4; static readonly CustomBase32Alphabet = "abcdefghijklmnopqrstuvwxyz234567"; #privateKey?: string; get privateKey(): string | undefined { return this.#privateKey; } get network(): AddressNetwork { return Address.parseNetwork(this.value); } get protocol(): AddressProtocol { return Address.parseProtocol(this.value); } constructor(publicAddress: string, privateKey?: string) { super(publicAddress); this.#privateKey = privateKey; } setPrivateKey(privateKey: string) { this.#privateKey = privateKey; } async signProposal(proposal: StartDealParams): Promise<Buffer> { if (this.#privateKey) { const serialized = proposal.serialize(); const encoded = cbor.encode(serialized); const signature = await bls.sign(encoded, this.#privateKey); return Buffer.from(signature); } else { throw new Error( `Could not sign proposal with address ${this.value} due to not having the associated private key.` ); } } async signMessage(message: Message): Promise<Buffer> { if (this.#privateKey) { // TODO (Issue ganache#867): From the code at https://git.io/Jtud2, // it appears that messages are signed using the CID. However there are // two issues here that I spent too much time trying to figure out: // 1. We don't generate an identical CID // 2. Even if we did, this signature doesn't match what lotus provides // But here's the catch, I know for certain `signBuffer` mimics lotus's // Filecoin.WalletSign method. In other words, if I take the CID that lotus gives me // and put it back into Filecoin.WalletSign, it matches the below output // (given that message.cid.value was replaced by the CID string provided // by lotus for the same message). I'm not sure what's wrong here without // debugging lotus itself and watching the values change, but since we're // not guaranteeing cryptographic integrity, I'm letting this one slide for now. return await this.signBuffer(Buffer.from(message.cid.value)); } else { throw new Error( `Could not sign message with address ${this.value} due to not having the associated private key.` ); } } async signBuffer(buffer: Buffer): Promise<Buffer> { if (this.#privateKey) { switch (this.protocol) { case AddressProtocol.BLS: { const signature = await bls.sign( buffer, switchEndianness(this.#privateKey) ); return Buffer.from(signature); } case AddressProtocol.SECP256K1: { const hash = blake.blake2b(buffer, null, 32); const result = secp256K1.ecdsaSign( hash, Buffer.from(this.#privateKey, "hex") ); return Buffer.concat([result.signature, Buffer.from([result.recid])]); } default: { throw new Error( `Cannot sign with this protocol ${this.protocol}. Supported protocols: BLS and SECP256K1` ); } } } else { throw new Error( `Could not sign message with address ${this.value} due to not having the associated private key.` ); } } async verifySignature( buffer: Buffer, signature: Signature ): Promise<boolean> { switch (this.protocol) { case AddressProtocol.BLS: { return await bls.verify( signature.data, buffer, Address.recoverBLSPublicKey(this.value) ); } case AddressProtocol.SECP256K1: { const hash = blake.blake2b(buffer, null, 32); return secp256K1.ecdsaVerify( signature.data.slice(0, 64), // remove the recid suffix (should be the last/65th byte) hash, Address.recoverSECP256K1PublicKey(signature, hash) ); } default: { return false; } } } static recoverBLSPublicKey(address: string): Buffer { const protocol = Address.parseProtocol(address); const decoded = base32.parse( address.slice(2), Address.CustomBase32Alphabet ); const payload = decoded.slice(0, decoded.length - 4); if (protocol === AddressProtocol.BLS) { return payload; } else { throw new Error( "Address is not a BLS protocol; cannot recover the public key." ); } } static recoverSECP256K1PublicKey( signature: Signature, message: Uint8Array ): Buffer { return Buffer.from( secp256K1.ecdsaRecover( signature.data.slice(0, 64), signature.data[64], message ).buffer ); } static fromPrivateKey( privateKey: string, protocol: AddressProtocol = AddressProtocol.BLS, network: AddressNetwork = AddressNetwork.Testnet ): Address { let publicKey: Buffer; let payload: Buffer; if (protocol === AddressProtocol.BLS) { // Get the public key // BLS uses big endian, but we use little endian publicKey = Buffer.from(bls.getPublicKey(switchEndianness(privateKey))); payload = publicKey; } else if (protocol === AddressProtocol.SECP256K1) { publicKey = Buffer.from( secp256K1.publicKeyCreate(Buffer.from(privateKey, "hex"), false) ); // https://bit.ly/3atGMwX says blake2b-160, but calls the checksum // both blake2b-4 and 4 bytes, so there is inconsistency of the // terminology of bytes vs bits, but the implementation at // https://git.io/JtEM6 shows 20 bytes and 4 bytes respectively payload = Buffer.from(blake.blake2b(publicKey, null, 20)); } else { throw new Error( "Protocol type not yet supported. Supported address protocols: BLS, SECP256K1" ); } const checksum = Address.createChecksum(protocol, payload); // Merge the public key and checksum const payloadAndChecksum = Buffer.concat([payload, checksum]); // Use a custom alphabet to base32 encode the checksummed public key, // and prepend the network and protocol identifiers. const address = `${network}${protocol}${base32.stringify( payloadAndChecksum, Address.CustomBase32Alphabet )}`; return new Address(address, privateKey); } static random( rng: RandomNumberGenerator = new RandomNumberGenerator(), protocol: AddressProtocol = AddressProtocol.BLS, network: AddressNetwork = AddressNetwork.Testnet ): Address { // Note that this private key isn't cryptographically secure! // It uses insecure randomization! Don't use it in production! const privateKey = rng.getBuffer(32).toString("hex"); return Address.fromPrivateKey(privateKey, protocol, network); } static parseNetwork(publicAddress: string): AddressNetwork { if (publicAddress.length < 1) { return AddressNetwork.Unknown; } switch (publicAddress.charAt(0)) { case AddressNetwork.Mainnet: { return AddressNetwork.Mainnet; } case AddressNetwork.Testnet: { return AddressNetwork.Testnet; } default: { return AddressNetwork.Unknown; } } } static parseProtocol(publicAddress: string): AddressProtocol { if (publicAddress.length < 2) { return AddressProtocol.Unknown; } switch (parseInt(publicAddress.charAt(1), 10)) { case AddressProtocol.ID: { return AddressProtocol.ID; } case AddressProtocol.BLS: { return AddressProtocol.BLS; } case AddressProtocol.Actor: { return AddressProtocol.Actor; } case AddressProtocol.SECP256K1: { return AddressProtocol.SECP256K1; } default: { return AddressProtocol.Unknown; } } } /** * Creates an AddressProtocol.ID address * @param id - A positive integer for the id. * @param isSingletonSystemActor - If false, it adds Address.FirstNonSingletonActorId to the id. * Almost always `false`. See https://git.io/JtgqL for examples of singleton system actors. * @param network - The AddressNetwork prefix for the address; usually AddressNetwork.Testnet for Ganache. */ static fromId( id: number, isSingletonSystemActor: boolean = false, isMiner: boolean = false, network: AddressNetwork = AddressNetwork.Testnet ): Address { if (Math.round(id) !== id || id < 0) { throw new Error("id must be a positive integer"); } return new Address( `${network}${AddressProtocol.ID}${ isSingletonSystemActor ? id : isMiner ? Address.FirstMinerId + id : Address.FirstNonSingletonActorId + id }` ); } static createChecksum(protocol: AddressProtocol, payload: Buffer): Buffer { // Create a checksum using the blake2b algorithm const checksumBuffer = Buffer.concat([Buffer.from([protocol]), payload]); const checksum = blake.blake2b( checksumBuffer, null, Address.CHECKSUM_BYTES ); return Buffer.from(checksum.buffer); } static validate(inputAddress: string): Address { inputAddress = inputAddress.trim(); if (inputAddress === "" || inputAddress === "<empty>") { throw new Error("invalid address length"); } // MaxAddressStringLength is the max length of an address encoded as a string // it includes the network prefix, protocol, and bls publickey (bls is the longest) const MaxAddressStringLength = 2 + 84; if ( inputAddress.length > MaxAddressStringLength || inputAddress.length < 3 ) { throw new Error("invalid address length"); } const address = new Address(inputAddress); const raw = address.value.slice(2); if (address.network === AddressNetwork.Unknown) { throw new Error("unknown address network"); } if (address.protocol === AddressProtocol.Unknown) { throw new Error("unknown address protocol"); } if (address.protocol === AddressProtocol.ID) { if (raw.length > 20) { throw new Error("invalid address length"); } const id = parseInt(raw, 10); if (isNaN(id) || id.toString(10) !== raw) { throw new Error("invalid address payload"); } return address; } const payloadWithChecksum = base32.parse(raw, Address.CustomBase32Alphabet); if (payloadWithChecksum.length < Address.CHECKSUM_BYTES) { throw new Error("invalid address checksum"); } const payload = payloadWithChecksum.slice( 0, payloadWithChecksum.length - Address.CHECKSUM_BYTES ); const providedChecksum = payloadWithChecksum.slice( payloadWithChecksum.length - Address.CHECKSUM_BYTES ); if ( address.protocol === AddressProtocol.SECP256K1 || address.protocol === AddressProtocol.Actor ) { if (payload.length !== 20) { throw new Error("invalid address payload"); } } const generatedChecksum = Address.createChecksum(address.protocol, payload); if (!generatedChecksum.equals(providedChecksum)) { throw new Error("invalid address checksum"); } return address; } } type SerializedAddress = string; export { Address, SerializedAddress, AddressProtocol, AddressNetwork };
the_stack
import { WebPartContext } from '@microsoft/sp-webpart-base'; import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions } from '@microsoft/sp-http'; // tslint:disable-next-line: no-any const wordjpg: any = require('../assets/wordlist.jpg'); // tslint:disable-next-line: no-any const $: any = require('../assets/jquery.min'); export class Game { public rounds: Round[] = []; } export class Round { public word: string = ''; public answers: string[] = []; public correctAnswer: string = ''; public incorrectAnswers: string[] = []; } export class WordGameListItem { // tslint:disable-next-line: variable-name public Name: string; // tslint:disable-next-line: variable-name public Score: number; // tslint:disable-next-line: variable-name public Seconds: number; // tslint:disable-next-line: variable-name public Details: string; constructor(name: string, score: number, seconds: number, details: string) { this.Name = name; this.Score = score; this.Seconds = seconds; this.Details = details; } } export class WordService { public allwords: string[] = []; public words3: string[] = []; public words4: string[] = []; public words5: string[] = []; public words6: string[] = []; public words7: string[] = []; public words8: string[] = []; public context: WebPartContext; public GenerateGame(): Game { const game: Game = new Game(); const round1: Round = new Round(); round1.word = this.GetRandomScrambledWord(5); round1.answers = this.FindPossibleWords(round1.word); const round2: Round = new Round(); round2.word = this.GetRandomScrambledWord(5); round2.answers = this.FindPossibleWords(round2.word); const round3: Round = new Round(); round3.word = this.GetRandomScrambledWord(5); round3.answers = this.FindPossibleWords(round3.word); const round4: Round = new Round(); round4.word = this.GetRandomScrambledWord(6); round4.answers = this.FindPossibleWords(round4.word); const round5: Round = new Round(); round5.word = this.GetRandomScrambledWord(6); round5.answers = this.FindPossibleWords(round5.word); const round6: Round = new Round(); round6.word = this.GetRandomScrambledWord(6); round6.answers = this.FindPossibleWords(round6.word); game.rounds.push(round1); game.rounds.push(round2); game.rounds.push(round3); game.rounds.push(round4); game.rounds.push(round5); game.rounds.push(round6); return game; } public async loadWords(): Promise<void> { // tslint:disable-next-line: no-string-literal window['wordService'] = this; /* SP Loader Implementation */ // console.log(jquery); // await SPComponentLoader.loadScript('../assets/jquery.min.js', { globalExportsName: "ScriptGlobal" }); // console.log('jquery loaded'); /* JSON File Implementation If you have a custom word list you would like to use add it as a JSON file in assets/wordlist.json and uncomment the const wordlist at the top of this file. Then comment out the Text File implementation below */ // let wordvalues = (Object as any).values(wordlist) as any; // let wordlistlength = wordvalues.length as number; // for(let i=0;i<wordlistlength;i++) // this.allwords.push(wordvalues[i]); /* Text File Implementation Yields the smallest file download size vs JSON (700k vs 1.3mb) The word list is a text file stored as wordlist.jpg and loaded as text/plain using an overrided mime type */ const responseText: string = await $.ajax({ url: wordjpg, beforeSend: (xhr) => { xhr.overrideMimeType('text/plain; charset=x-user-defined'); } }) as string; this.allwords = responseText.split('\r\n'); this.allwords.forEach(word => { if (word.indexOf('-') > -1) { return; } if (word.indexOf('-') > -1) { return; } switch (word.length) { case 3: this.words3.push(word); break; case 4: this.words4.push(word); break; case 5: this.words5.push(word); break; case 6: this.words6.push(word); break; case 7: this.words7.push(word); break; case 8: this.words8.push(word); break; default: break; } }); console.log('words length: ' + this.allwords.length); } public GetWordCount(): number { return this.allwords.length; } public GetRandomScrambledWord(level: number): string { let randomWord: string = ''; let randwordnum: number = 0; switch (level) { case 3: randwordnum = Math.floor(Math.random() * Math.floor(this.words3.length)); randomWord = this.words3[randwordnum]; break; case 4: randwordnum = Math.floor(Math.random() * Math.floor(this.words4.length)); randomWord = this.words4[randwordnum]; break; case 5: randwordnum = Math.floor(Math.random() * Math.floor(this.words5.length)); randomWord = this.words5[randwordnum]; break; case 6: randwordnum = Math.floor(Math.random() * Math.floor(this.words6.length)); randomWord = this.words6[randwordnum]; break; case 7: randwordnum = Math.floor(Math.random() * Math.floor(this.words7.length)); randomWord = this.words7[randwordnum]; break; case 8: randwordnum = Math.floor(Math.random() * Math.floor(this.words8.length)); randomWord = this.words8[randwordnum]; break; default: break; } const scrambledWord: string = this.ScrambleWord(randomWord); return scrambledWord; } public FindPossibleWords(currentWord: string): string[] { // coati // taco // currentWord = "coati"; const possibleWords: string[] = []; this.allwords.forEach(word => { let tempword: string = word; // taco for (let i: number = 0; i < currentWord.length; i++) { const letter: string = currentWord[i]; if (tempword.indexOf(letter) > -1) { tempword = tempword.slice(0, tempword.indexOf(letter)) + tempword.slice(tempword.indexOf(letter) + 1); } else { tempword = 'n'; break; } } if (tempword.length === 0) { possibleWords.push(word); } }); return possibleWords; } public ScrambleWord(word: string): string { let notScrambled: boolean = true; let scrambledWord: string = ''; let count: number = 0; const originalword: string = word; while (notScrambled) { word = originalword; let chars: string = ''; for (let i: number = 0; i < word.length; i++) { chars += ' '; } let index: number = 0; while (word.length > 0) { // Get a random number between 0 and the length of the word. const next: number = Math.floor(Math.random() * Math.floor(word.length)); // Take the character from the random position and add to our char array. chars = this.replaceCharAt(chars, index, word[next]); // Remove the character from the word. word = word.substr(0, next) + word.substr(next + 1); ++index; } scrambledWord = chars.slice(0); count++; if (originalword !== scrambledWord) { notScrambled = false; } // just in case there is a problem if (count === 10) { notScrambled = false; } } return scrambledWord; } // SHAREPOINT APIS public SetContext(context: WebPartContext): void { this.context = context; } public async SubmitScore(score: number, seconds: number, details: string): Promise<void> { try { await this.CreateListIfNotExists(); await this.CreateListItem(score, seconds, details); } catch (error) { // do nothing } } public async GetHighScores(): Promise<WordGameListItem[]> { let scores: WordGameListItem[] = []; try { const result: SPHttpClientResponse = await this.context.spHttpClient.get( this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('WordGameList')/items", SPHttpClient.configurations.v1); // tslint:disable-next-line: no-any const json: any = await result.json(); console.log(json); json.value.forEach(item => { scores.push(new WordGameListItem(item.Title, item.Score, item.Seconds, item.Details)); }); scores.sort((a, b) => { return b.Score - a.Score; }); // top 10 if (scores.length > 10) { scores = scores.slice(0, 10); } console.log('high scores', scores); } catch (error) { console.log('could not find list'); } return scores; } // replace a character in a string private replaceCharAt(orig: string, index: number, replacement: string): string { return orig.substr(0, index) + replacement + orig.substr(index + replacement.length); } private async CreateListIfNotExists(): Promise<void> { const result: SPHttpClientResponse = await this.context.spHttpClient.get( this.context.pageContext.web.absoluteUrl + '/_api/web/lists', SPHttpClient.configurations.v1); // tslint:disable-next-line: no-any const json: any = await result.json(); let exists: boolean = false; json.value.forEach(list => { if (list.Title === 'WordGameList') { console.log('list found'); exists = true; } }); console.log(json); if (exists === false) { console.log('Attempting to create list'); await this.CreateList(); await this.AddListColumnNumber('Score'); await this.AddListColumnNumber('Seconds'); await this.AddListColumnMultiLineText('Details'); } } private async CreateListItem(score: number, seconds: number, details: string): Promise<void> { const listMetadata: {} = { '__metadata': { 'type': 'SP.Data.WordGameListListItem' }, 'Title': this.context.pageContext.user.displayName, 'Score': score, 'Seconds': seconds, 'Details': details }; const options: ISPHttpClientOptions = { headers: { 'Accept': 'application/json;odata=verbose', 'Content-Type': 'application/json;odata=verbose', 'OData-Version': '' // Really important to specify }, body: JSON.stringify(listMetadata) }; const result: SPHttpClientResponse = await this.context.spHttpClient.post( this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('WordGameList')/items", SPHttpClient.configurations.v1, options); // tslint:disable-next-line: no-any const json: any = await result.json(); console.log(json); } private async CreateList(): Promise<void> { const listMetadata: {} = { '__metadata': { 'type': 'SP.List' }, 'AllowContentTypes': true, 'BaseTemplate': 100, 'ContentTypesEnabled': true, 'Description': 'Holds high scores for the word game', 'Title': 'WordGameList' }; const options: ISPHttpClientOptions = { headers: { 'Accept': 'application/json;odata=verbose', 'Content-Type': 'application/json;odata=verbose', 'OData-Version': '' // Really important to specify }, body: JSON.stringify(listMetadata) }; const result: SPHttpClientResponse = await this.context.spHttpClient.post( this.context.pageContext.web.absoluteUrl + '/_api/web/lists', SPHttpClient.configurations.v1, options); // tslint:disable-next-line: no-any const json: any = await result.json(); console.log(json); } private async AddListColumnMultiLineText(name: string): Promise<void> { const listMetadata: {} = { '__metadata': { 'type': 'SP.FieldNumber' }, 'FieldTypeKind': 3, 'Title': name }; const options: ISPHttpClientOptions = { headers: { 'Accept': 'application/json;odata=verbose', 'Content-Type': 'application/json;odata=verbose', 'OData-Version': '' // Really important to specify }, body: JSON.stringify(listMetadata) }; const result: SPHttpClientResponse = await this.context.spHttpClient.post( this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('WordGameList')/fields", SPHttpClient.configurations.v1, options); // tslint:disable-next-line: no-any const json: any = await result.json(); console.log(json); } private async AddListColumnNumber(name: string): Promise<void> { const listMetadata: {} = { '__metadata': { 'type': 'SP.FieldNumber' }, 'FieldTypeKind': 9, 'Title': name, 'MinimumValue': 0, 'MaximumValue': 1000000 }; const options: ISPHttpClientOptions = { headers: { 'Accept': 'application/json;odata=verbose', 'Content-Type': 'application/json;odata=verbose', 'OData-Version': '' // Really important to specify }, body: JSON.stringify(listMetadata) }; const result: SPHttpClientResponse = await this.context.spHttpClient.post( this.context.pageContext.web.absoluteUrl + "/_api/web/lists/getbytitle('WordGameList')/fields", SPHttpClient.configurations.v1, options); // tslint:disable-next-line: no-any const json: any = await result.json(); console.log(json); } }
the_stack
import { CollectionReference } from "@google-cloud/firestore"; import { OneTimeProductPurchase, SubscriptionPurchase, ProductType, Purchase, SubscriptionPurchaseV2 } from "./types/purchases"; import { PurchaseQueryError, PurchaseUpdateError } from "./types/errors"; import { OneTimeProductPurchaseImpl, mergePurchaseWithFirestorePurchaseRecord, SubscriptionPurchaseImpl, SubscriptionPurchaseImplV2 } from "./internal/purchases_impl"; import { DeveloperNotification, NotificationType } from "./types/notifications"; const REPLACED_PURCHASE_USERID_PLACEHOLDER = 'invalid'; /* * A class that provides user-purchase linking features */ export default class PurchaseManager { /* * This class is intended to be initialized by the library. * Library consumer should not initialize this class themselves. */ constructor(private purchasesDbRef: CollectionReference, private playDeveloperApiClient: any) { }; /* * Query a onetime product purchase by its package name, product Id (product) and purchase token. * The method queries Google Play Developer API to get the latest status of the purchase, * then merge it with purchase ownership info stored in the library's managed Firestore database, * then returns the merge information as a OneTimeProductPurchase to its caller. */ async queryOneTimeProductPurchase(packageName: string, product: string, purchaseToken: string): Promise<OneTimeProductPurchase> { // STEP 1. Query Play Developer API to verify the purchase token const apiResponse = await new Promise((resolve, reject) => { this.playDeveloperApiClient.purchases.products.get({ packageName: packageName, productId: product, token: purchaseToken }, (err, result) => { if (err) { reject(this.convertPlayAPIErrorToLibraryError(err)); } else { resolve(result.data); } }) }); // STEP 2. Look up purchase records from Firestore which matches this purchase token try { const purchaseRecordDoc = await this.purchasesDbRef.doc(purchaseToken).get(); // Generate OneTimeProductPurchase object from Firestore response const now = Date.now(); const onetimeProductPurchase = OneTimeProductPurchaseImpl.fromApiResponse(apiResponse, packageName, purchaseToken, product, now); // Attempt to save purchase record cache to Firestore const firestoreObject = onetimeProductPurchase.toFirestoreObject(); if (purchaseRecordDoc.exists) { // STEP 3a. We have this purchase cached in Firstore. Update our cache with the newly received response from Google Play Developer API await purchaseRecordDoc.ref.update(firestoreObject); // STEP 4a. Merge other fields of our purchase record in Firestore (such as userId) with our OneTimeProductPurchase object and return to caller. mergePurchaseWithFirestorePurchaseRecord(onetimeProductPurchase, purchaseRecordDoc.data()); return onetimeProductPurchase; } else { // STEP 3b. This is a brand-new purchase. Save the purchase record to Firestore await purchaseRecordDoc.ref.set(firestoreObject); // STEP 4b. Return the OneTimeProductPurchase object. return onetimeProductPurchase; } } catch (err) { // Some unexpected error has occured while interacting with Firestore. const libraryError = new Error(err.message); libraryError.name = PurchaseQueryError.OTHER_ERROR; throw libraryError; } } /* * Query a subscription purchase by its package name, product Id (product) and purchase token. * The method queries Google Play Developer API to get the latest status of the purchase, * then merge it with purchase ownership info stored in the library's managed Firestore database, * then returns the merge information as a SubscriptionPurchase to its caller. */ querySubscriptionPurchase(packageName: string, product: string, purchaseToken: string): Promise<SubscriptionPurchaseV2> { return this.querySubscriptionPurchaseWithTriggerV2(packageName, product, purchaseToken); } /* * Actual private information of querySubscriptionPurchase(packageName, product, purchaseToken) * It's expanded to support storing extra information only available via Realtime Developer Notification, * such as latest notification type. * - triggerNotificationType is only neccessary if the purchase query action is triggered by a Realtime Developer notification */ private async querySubscriptionPurchaseWithTrigger(packageName: string, product: string, purchaseToken: string, triggerNotificationType?: NotificationType): Promise<SubscriptionPurchase> { // STEP 1. Query Play Developer API to verify the purchase token const apiResponse = await new Promise((resolve, reject) => { this.playDeveloperApiClient.purchases.subscriptions.get({ packageName: packageName, subscriptionId: product, token: purchaseToken }, (err, result) => { if (err) { reject(this.convertPlayAPIErrorToLibraryError(err)); } else { resolve(result.data); } }) }); try { // STEP 2. Look up purchase records from Firestore which matches this purchase token const purchaseRecordDoc = await this.purchasesDbRef.doc(purchaseToken).get(); // Generate SubscriptionPurchase object from Firestore response const now = Date.now(); const subscriptionPurchase = SubscriptionPurchaseImpl.fromApiResponse(apiResponse, packageName, purchaseToken, product, now); // Store notificationType to database if queryPurchase was triggered by a realtime developer notification if (triggerNotificationType !== undefined) { subscriptionPurchase.latestNotificationType = triggerNotificationType; } // Convert subscriptionPurchase object to a format that to be stored in Firestore const firestoreObject = subscriptionPurchase.toFirestoreObject(); if (purchaseRecordDoc.exists) { // STEP 3a. We has this purchase cached in Firstore. Update our cache with the newly received response from Google Play Developer API await purchaseRecordDoc.ref.update(firestoreObject); // STEP 4a. Merge other fields of our purchase record in Firestore (such as userId) with our SubscriptionPurchase object and return to caller. mergePurchaseWithFirestorePurchaseRecord(subscriptionPurchase, purchaseRecordDoc.data()); return subscriptionPurchase; } else { // STEP 3b. This is a brand-new subscription purchase. Just save the purchase record to Firestore await purchaseRecordDoc.ref.set(firestoreObject); if (subscriptionPurchase.linkedPurchaseToken) { // STEP 4b. This is a subscription purchase that replaced other subscriptions in the past. Let's disable the purchases that it has replaced. await this.disableReplacedSubscription(packageName, product, subscriptionPurchase.linkedPurchaseToken); } // STEP 5. This is a brand-new subscription purchase. Just save the purchase record to Firestore and return an SubscriptionPurchase object with userId = null. return subscriptionPurchase; } } catch (err) { // Some unexpected error has occured while interacting with Firestore. const libraryError = new Error(err.message); libraryError.name = PurchaseQueryError.OTHER_ERROR; throw libraryError; } } /* * Actual private information of querySubscriptionPurchase(packageName, product, purchaseToken) * It's expanded to support storing extra information only available via Realtime Developer Notification, * such as latest notification type. * - triggerNotificationType is only neccessary if the purchase query action is triggered by a Realtime Developer notification */ private async querySubscriptionPurchaseWithTriggerV2(packageName: string, product: string, purchaseToken: string, triggerNotificationType?: NotificationType): Promise<SubscriptionPurchaseV2> { // STEP 1. Query Play Developer API to verify the purchase token const apiResponseV2 = await new Promise((resolve, reject) => { this.playDeveloperApiClient.purchases.subscriptionsv2.get({ packageName: packageName, token: purchaseToken }, (err, result) => { if (err) { reject(this.convertPlayAPIErrorToLibraryError(err)); } else { resolve(result.data); } }) }); try { // STEP 2. Look up purchase records from Firestore which matches this purchase token const purchaseRecordDoc = await this.purchasesDbRef.doc(purchaseToken).get(); // Generate SubscriptionPurchase object from Firestore response const now = Date.now(); const subscriptionPurchase = SubscriptionPurchaseImplV2.fromApiResponse(apiResponseV2, packageName, purchaseToken, product, now); // Store notificationType to database if queryPurchase was triggered by a realtime developer notification if (triggerNotificationType !== undefined) { subscriptionPurchase.latestNotificationType = triggerNotificationType; } // Convert subscriptionPurchase object to a format that to be stored in Firestore const firestoreObject = subscriptionPurchase.toFirestoreObject(); if (purchaseRecordDoc.exists) { // STEP 3a. We has this purchase cached in Firstore. Update our cache with the newly received response from Google Play Developer API await purchaseRecordDoc.ref.update(firestoreObject); // STEP 4a. Merge other fields of our purchase record in Firestore (such as userId) with our SubscriptionPurchase object and return to caller. mergePurchaseWithFirestorePurchaseRecord(subscriptionPurchase, purchaseRecordDoc.data()); return subscriptionPurchase; } else { // STEP 3b. This is a brand-new subscription purchase. Just save the purchase record to Firestore await purchaseRecordDoc.ref.set(firestoreObject); if (subscriptionPurchase.linkedPurchaseToken) { // STEP 4b. This is a subscription purchase that replaced other subscriptions in the past. Let's disable the purchases that it has replaced. await this.disableReplacedSubscriptionV2(packageName, product, subscriptionPurchase.linkedPurchaseToken); } // STEP 5. This is a brand-new subscription purchase. Just save the purchase record to Firestore and return an SubscriptionPurchase object with userId = null. return subscriptionPurchase; } } catch (err) { // Some unexpected error has occured while interacting with Firestore. const libraryError = new Error(err.message); libraryError.name = PurchaseQueryError.OTHER_ERROR; throw libraryError; } } /* * There are situations that a subscription is replaced by another subscription. * For example, an user signs up for a subscription (tokenA), cancel its and re-signups (tokenB) * We must disable the subscription linked to tokenA because it has been replaced by tokenB. * If failed to do so, there's chance that a malicious user can have a single purchase registered to multiple user accounts. * * This method is used to disable a replaced subscription. It's not intended to be used from outside of the library. */ private async disableReplacedSubscription(packageName: string, product: string, purchaseToken: string): Promise<void> { console.log('Disabling purchase token = ', purchaseToken); // STEP 1: Lookup the purchase record in Firestore const purchaseRecordDoc = await this.purchasesDbRef.doc(purchaseToken).get(); if (purchaseRecordDoc.exists) { // Purchase record found in Firestore. Check if it has been disabled. if (purchaseRecordDoc.data().replacedByAnotherPurchase) { // The old purchase has been. We don't need to take further action return; } else { // STEP 2a: Old purchase found in cache, so we disable it await purchaseRecordDoc.ref.update({ replacedByAnotherPurchase: true, userId: REPLACED_PURCHASE_USERID_PLACEHOLDER }); return; } } else { // Purchase record not found in Firestore. We'll try to fetch purchase detail from Play Developer API to backfill the missing cache const apiResponse = await new Promise((resolve, reject) => { this.playDeveloperApiClient.purchases.subscriptions.get({ packageName: packageName, subscriptionId: product, token: purchaseToken }, async (err, result) => { if (err) { console.warn('Error fetching purchase data from Play Developer API to backfilled missing purchase record in Firestore. ', err.message); // We only log an warning to console log as there is chance that backfilling is impossible. // For example: after a subscription upgrade, the new token has linkedPurchaseToken to be the token before upgrade. // We can't tell the product of the purchase before upgrade from the old token itself, so we can't query Play Developer API // to backfill our cache. resolve(null); } else { resolve(result.data); } }) }) if (apiResponse) { // STEP 2b. Parse the response from Google Play Developer API and store the purchase detail const now = Date.now(); const subscriptionPurchase = SubscriptionPurchaseImpl.fromApiResponse(apiResponse, packageName, purchaseToken, product, now); subscriptionPurchase.replacedByAnotherPurchase = true; // Mark the purchase as already being replaced by other purchase. subscriptionPurchase.userId = REPLACED_PURCHASE_USERID_PLACEHOLDER; const firestoreObject = subscriptionPurchase.toFirestoreObject(); await purchaseRecordDoc.ref.set(firestoreObject); // STEP 3. If this purchase has also replaced another purchase, repeating from STEP 1 with the older token if (subscriptionPurchase.linkedPurchaseToken) { await this.disableReplacedSubscription(packageName, product, subscriptionPurchase.linkedPurchaseToken); } } } } /* * There are situations that a subscription is replaced by another subscription. * For example, an user signs up for a subscription (tokenA), cancel its and re-signups (tokenB) * We must disable the subscription linked to tokenA because it has been replaced by tokenB. * If failed to do so, there's chance that a malicious user can have a single purchase registered to multiple user accounts. * * This method is used to disable a replaced subscription. It's not intended to be used from outside of the library. */ private async disableReplacedSubscriptionV2(packageName: string, product: string, purchaseToken: string): Promise<void> { console.log('Disabling purchase token = ', purchaseToken); // STEP 1: Lookup the purchase record in Firestore const purchaseRecordDoc = await this.purchasesDbRef.doc(purchaseToken).get(); if (purchaseRecordDoc.exists) { // Purchase record found in Firestore. Check if it has been disabled. if (purchaseRecordDoc.data().replacedByAnotherPurchase) { // The old purchase has been. We don't need to take further action return; } else { // STEP 2a: Old purchase found in cache, so we disable it await purchaseRecordDoc.ref.update({ replacedByAnotherPurchase: true, userId: REPLACED_PURCHASE_USERID_PLACEHOLDER }); return; } } else { // Purchase record not found in Firestore. We'll try to fetch purchase detail from Play Developer API to backfill the missing cache const apiResponseV2 = await new Promise((resolve, reject) => { this.playDeveloperApiClient.purchases.subscriptionsV2.get({ packageName: packageName, subscriptionId: product, token: purchaseToken }, async (err, result) => { if (err) { console.warn('Error fetching purchase data from Play Developer API to backfilled missing purchase record in Firestore. ', err.message); // We only log an warning to console log as there is chance that backfilling is impossible. // For example: after a subscription upgrade, the new token has linkedPurchaseToken to be the token before upgrade. // We can't tell the product of the purchase before upgrade from the old token itself, so we can't query Play Developer API // to backfill our cache. resolve(null); } else { resolve(result.data); } }) }) if (apiResponseV2) { // STEP 2b. Parse the response from Google Play Developer API and store the purchase detail const now = Date.now(); const subscriptionPurchase = SubscriptionPurchaseImplV2.fromApiResponse(apiResponseV2, packageName, purchaseToken, product, now); subscriptionPurchase.replacedByAnotherPurchase = true; // Mark the purchase as already being replaced by other purchase. subscriptionPurchase.userId = REPLACED_PURCHASE_USERID_PLACEHOLDER; const firestoreObject = subscriptionPurchase.toFirestoreObject(); await purchaseRecordDoc.ref.set(firestoreObject); // STEP 3. If this purchase has also replaced another purchase, repeating from STEP 1 with the older token if (subscriptionPurchase.linkedPurchaseToken) { await this.disableReplacedSubscriptionV2(packageName, product, subscriptionPurchase.linkedPurchaseToken); } } } } /* * Another method to query latest status of a Purchase. * Internally it just calls queryOneTimeProductPurchase / querySubscriptionPurchase accordingly */ async queryPurchase(packageName: string, product: string, purchaseToken: string, productType: ProductType): Promise<Purchase> { if (productType === ProductType.ONE_TIME) { return await this.queryOneTimeProductPurchase(packageName, product, purchaseToken); } else if (productType === ProductType.SUBS) { return await this.querySubscriptionPurchase(packageName, product, purchaseToken); } else { throw new Error('Invalid productType.'); } } /* * Force register a purchase to an user. * This method is not intended to be called from outside of the library. */ private async forceRegisterToUserAccount(purchaseToken: string, userId: string): Promise<void> { try { await this.purchasesDbRef.doc(purchaseToken).update({ userId: userId }); } catch (err) { // console.error('Failed to update purchase record in Firestore. \n', err.message); const libraryError = new Error(err.message); libraryError.name = PurchaseUpdateError.OTHER_ERROR; throw libraryError; } } /* * Register a purchase (both one-time product and recurring subscription) to a user. * It's intended to be exposed to Android app to verify purchases made in the app */ async registerToUserAccount(packageName: string, product: string, purchaseToken: string, productType: ProductType, userId: string): Promise<void> { // STEP 1. Fetch the purchase using Play Developer API and purchase records in Firestore. let purchase: Purchase; try { purchase = await this.queryPurchase(packageName, product, purchaseToken, productType); } catch (err) { // console.error('Error querying purchase', err); // Error when attempt to query purchase. Return invalid token to caller. const libraryError = new Error(err.message); libraryError.name = PurchaseUpdateError.INVALID_TOKEN; throw libraryError; } // STEP 2. Check if the purchase is registerable. if (!purchase.isRegisterable()) { const libraryError = new Error('Purchase is not registerable'); libraryError.name = PurchaseUpdateError.INVALID_TOKEN; throw libraryError; } // STEP 3. Check if the purchase has been registered to an user. If it is, then return conflict error to our caller. if (purchase.userId === userId) { // Purchase record already registered to the target user. We'll do nothing. return; } else if (purchase.userId) { console.log('Purchase has been registered to another user'); // Purchase record already registered to different user. Return 'conflict' to caller const libraryError = new Error('Purchase has been registered to another user'); libraryError.name = PurchaseUpdateError.CONFLICT; throw libraryError; } // STEP 3: Register purchase to the user await this.forceRegisterToUserAccount(purchaseToken, userId); } async transferToUserAccount(packageName: string, product: string, purchaseToken: string, productType: ProductType, userId: string): Promise<void> { try { // STEP 1. Fetch the purchase using Play Developer API and purchase records in Firestore. await this.queryPurchase(packageName, product, purchaseToken, productType); // STEP 2: Attempt to transfer a purchase to the user await this.forceRegisterToUserAccount(purchaseToken, userId); } catch (err) { // Error when attempt to query purchase. Return invalid token to caller. const libraryError = new Error(err.message); libraryError.name = PurchaseUpdateError.INVALID_TOKEN; throw libraryError; } } async processDeveloperNotification(packageName: string, notification: DeveloperNotification): Promise<SubscriptionPurchaseV2 | null> { if (notification.testNotification) { console.log('Received a test Realtime Developer Notification. ', notification.testNotification); return null; } // Received a real-time developer notification. const subscriptionNotification = notification.subscriptionNotification; if (subscriptionNotification.notificationType !== NotificationType.SUBSCRIPTION_PURCHASED) { // We can safely ignoreSUBSCRIPTION_PURCHASED because with new subscription, our Android app will send the same token to server for verification // For other type of notification, we query Play Developer API to update our purchase record cache in Firestore return await this.querySubscriptionPurchaseWithTriggerV2(packageName, subscriptionNotification.subscriptionId, subscriptionNotification.purchaseToken, subscriptionNotification.notificationType ); } return null; } private convertPlayAPIErrorToLibraryError(playError: any): Error { const libraryError = new Error(playError.message); if (playError.code === 404) { libraryError.name = PurchaseQueryError.INVALID_TOKEN; } else { // Unexpected error occurred. It's likely an issue with Service Account libraryError.name = PurchaseQueryError.OTHER_ERROR; console.error('Unexpected error when querying Google Play Developer API. Please check if you use a correct service account'); } return libraryError; } /** * Uses [subscriptions.acknowledge]{@link https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.subscriptions/acknowledge} * to acknowledge new subcription purchases. * * @param packageName * @param product * @param purchaseToken */ async acknowledgePurchase(packageName: string, product: string, purchaseToken:string){ try { await this.playDeveloperApiClient.purchases.subscriptions.acknowledge({ packageName: packageName, subscriptionId: product, token: purchaseToken}, async (err, result) => { if (err) { this.convertPlayAPIErrorToLibraryError(err); } else { result.data; }}) } catch (err) { const libraryError = new Error(err.message); throw libraryError; } } }
the_stack
import { IPointData, Matrix, Point } from '@pixi/math'; import { Matrix2d } from '../proj2d'; import { Point3d } from './Point3d'; import { AFFINE } from '../base'; const mat4id = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]; export class Matrix3d { /** * A default (identity) matrix * * @static * @const */ static readonly IDENTITY = new Matrix3d(); /** * A temp matrix * * @static * @const */ static readonly TEMP_MATRIX = new Matrix3d(); /** * mat4 implementation through array of 16 elements */ mat4: Float64Array; floatArray: Float32Array = null; _dirtyId = 0; _updateId = -1; _mat4inv: Float64Array = null; cacheInverse = false; constructor(backingArray?: ArrayLike<number>) { this.mat4 = new Float64Array(backingArray || mat4id); } get a(): number { return this.mat4[0] / this.mat4[15]; } set a(value: number) { this.mat4[0] = value * this.mat4[15]; } get b(): number { return this.mat4[1] / this.mat4[15]; } set b(value: number) { this.mat4[1] = value * this.mat4[15]; } get c(): number { return this.mat4[4] / this.mat4[15]; } set c(value: number) { this.mat4[4] = value * this.mat4[15]; } get d(): number { return this.mat4[5] / this.mat4[15]; } set d(value: number) { this.mat4[5] = value * this.mat4[15]; } get tx(): number { return this.mat4[12] / this.mat4[15]; } set tx(value: number) { this.mat4[12] = value * this.mat4[15]; } get ty(): number { return this.mat4[13] / this.mat4[15]; } set ty(value: number) { this.mat4[13] = value * this.mat4[15]; } set(a: number, b: number, c: number, d: number, tx: number, ty: number): this { const mat4 = this.mat4; mat4[0] = a; mat4[1] = b; mat4[2] = 0; mat4[3] = 0; mat4[4] = c; mat4[5] = d; mat4[6] = 0; mat4[7] = 0; mat4[8] = 0; mat4[9] = 0; mat4[10] = 1; mat4[11] = 0; mat4[12] = tx; mat4[13] = ty; mat4[14] = 0; mat4[15] = 1; return this; } toArray(transpose?: boolean, out?: Float32Array): Float32Array { if (!this.floatArray) { this.floatArray = new Float32Array(9); } const array = out || this.floatArray; const mat3 = this.mat4; if (transpose) { array[0] = mat3[0]; array[1] = mat3[1]; array[2] = mat3[3]; array[3] = mat3[4]; array[4] = mat3[5]; array[5] = mat3[7]; array[6] = mat3[12]; array[7] = mat3[13]; array[8] = mat3[15]; } else { // this branch is NEVER USED in pixi array[0] = mat3[0]; array[1] = mat3[4]; array[2] = mat3[12]; array[3] = mat3[2]; array[4] = mat3[6]; array[5] = mat3[13]; array[6] = mat3[3]; array[7] = mat3[7]; array[8] = mat3[15]; } return array; } setToTranslation(tx: number, ty: number, tz: number): void { const mat4 = this.mat4; mat4[0] = 1; mat4[1] = 0; mat4[2] = 0; mat4[3] = 0; mat4[4] = 0; mat4[5] = 1; mat4[6] = 0; mat4[7] = 0; mat4[8] = 0; mat4[9] = 0; mat4[10] = 1; mat4[11] = 0; mat4[12] = tx; mat4[13] = ty; mat4[14] = tz; mat4[15] = 1; } // eslint-disable-next-line max-len setToRotationTranslationScale(quat: Float64Array, tx: number, ty: number, tz: number, sx: number, sy: number, sz: number): Float64Array { const out = this.mat4; const x = quat[0]; const y = quat[1]; const z = quat[2]; const w = quat[3]; const x2 = x + x; const y2 = y + y; const z2 = z + z; const xx = x * x2; const xy = x * y2; const xz = x * z2; const yy = y * y2; const yz = y * z2; const zz = z * z2; const wx = w * x2; const wy = w * y2; const wz = w * z2; out[0] = (1 - (yy + zz)) * sx; out[1] = (xy + wz) * sx; out[2] = (xz - wy) * sx; out[3] = 0; out[4] = (xy - wz) * sy; out[5] = (1 - (xx + zz)) * sy; out[6] = (yz + wx) * sy; out[7] = 0; out[8] = (xz + wy) * sz; out[9] = (yz - wx) * sz; out[10] = (1 - (xx + yy)) * sz; out[11] = 0; out[12] = tx; out[13] = ty; out[14] = tz; out[15] = 1; return out; } apply(pos: IPointData, newPos: IPointData): IPointData { newPos = newPos || new Point3d(); const mat4 = this.mat4; const x = pos.x; const y = pos.y; // TODO: pixi 6.1.0 global mixin const z = (pos as any).z || 0; // TODO: apply for 2d point const w = 1.0 / (mat4[3] * x + mat4[7] * y + mat4[11] * z + mat4[15]); newPos.x = w * (mat4[0] * x + mat4[4] * y + mat4[8] * z + mat4[12]); newPos.y = w * (mat4[1] * x + mat4[5] * y + mat4[9] * z + mat4[13]); // TODO: pixi 6.1.0 global mixin (newPos as any).z = w * (mat4[2] * x + mat4[6] * y + mat4[10] * z + mat4[14]); return newPos; } translate(tx: number, ty: number, tz: number): this { const a = this.mat4; a[12] = a[0] * tx + a[4] * ty + a[8] * tz + a[12]; a[13] = a[1] * tx + a[5] * ty + a[9] * tz + a[13]; a[14] = a[2] * tx + a[6] * ty + a[10] * tz + a[14]; a[15] = a[3] * tx + a[7] * ty + a[11] * tz + a[15]; return this; } scale(x: number, y: number, z?: number): this { const mat4 = this.mat4; mat4[0] *= x; mat4[1] *= x; mat4[2] *= x; mat4[3] *= x; mat4[4] *= y; mat4[5] *= y; mat4[6] *= y; mat4[7] *= y; if (z !== undefined) { mat4[8] *= z; mat4[9] *= z; mat4[10] *= z; mat4[11] *= z; } return this; } scaleAndTranslate(scaleX: number, scaleY: number, scaleZ: number, tx: number, ty: number, tz: number): void { const mat4 = this.mat4; mat4[0] = scaleX * mat4[0] + tx * mat4[3]; mat4[1] = scaleY * mat4[1] + ty * mat4[3]; mat4[2] = scaleZ * mat4[2] + tz * mat4[3]; mat4[4] = scaleX * mat4[4] + tx * mat4[7]; mat4[5] = scaleY * mat4[5] + ty * mat4[7]; mat4[6] = scaleZ * mat4[6] + tz * mat4[7]; mat4[8] = scaleX * mat4[8] + tx * mat4[11]; mat4[9] = scaleY * mat4[9] + ty * mat4[11]; mat4[10] = scaleZ * mat4[10] + tz * mat4[11]; mat4[12] = scaleX * mat4[12] + tx * mat4[15]; mat4[13] = scaleY * mat4[13] + ty * mat4[15]; mat4[14] = scaleZ * mat4[14] + tz * mat4[15]; } // TODO: remove props applyInverse<P extends IPointData = Point>(pos: IPointData, newPos?: P): P { newPos = (newPos || new Point3d()) as any; if (!this._mat4inv) { this._mat4inv = new Float64Array(16); } const mat4 = this._mat4inv; const a = this.mat4; const x = pos.x; const y = pos.y; // TODO: pixi 6.1.0 global mixin let z = (pos as any).z || 0; if (!this.cacheInverse || this._updateId !== this._dirtyId) { this._updateId = this._dirtyId; Matrix3d.glMatrixMat4Invert(mat4, a); } const w1 = 1.0 / (mat4[3] * x + mat4[7] * y + mat4[11] * z + mat4[15]); const x1 = w1 * (mat4[0] * x + mat4[4] * y + mat4[8] * z + mat4[12]); const y1 = w1 * (mat4[1] * x + mat4[5] * y + mat4[9] * z + mat4[13]); const z1 = w1 * (mat4[2] * x + mat4[6] * y + mat4[10] * z + mat4[14]); z += 1.0; const w2 = 1.0 / (mat4[3] * x + mat4[7] * y + mat4[11] * z + mat4[15]); const x2 = w2 * (mat4[0] * x + mat4[4] * y + mat4[8] * z + mat4[12]); const y2 = w2 * (mat4[1] * x + mat4[5] * y + mat4[9] * z + mat4[13]); const z2 = w2 * (mat4[2] * x + mat4[6] * y + mat4[10] * z + mat4[14]); if (Math.abs(z1 - z2) < 1e-10) { (newPos as any).set(NaN, NaN, 0); } const alpha = (0 - z1) / (z2 - z1); (newPos as any).set((x2 - x1) * alpha + x1, (y2 - y1) * alpha + y1, 0.0); return newPos; } invert(): Matrix3d { Matrix3d.glMatrixMat4Invert(this.mat4, this.mat4); return this; } invertCopyTo(matrix: Matrix3d): void { if (!this._mat4inv) { this._mat4inv = new Float64Array(16); } const mat4 = this._mat4inv; const a = this.mat4; if (!this.cacheInverse || this._updateId !== this._dirtyId) { this._updateId = this._dirtyId; Matrix3d.glMatrixMat4Invert(mat4, a); } matrix.mat4.set(mat4); } identity(): Matrix3d { const mat3 = this.mat4; mat3[0] = 1; mat3[1] = 0; mat3[2] = 0; mat3[3] = 0; mat3[4] = 0; mat3[5] = 1; mat3[6] = 0; mat3[7] = 0; mat3[8] = 0; mat3[9] = 0; mat3[10] = 1; mat3[11] = 0; mat3[12] = 0; mat3[13] = 0; mat3[14] = 0; mat3[15] = 1; return this; } clone(): Matrix3d { return new Matrix3d(this.mat4); } copyTo3d(matrix: Matrix3d): Matrix3d { const mat3 = this.mat4; const ar2 = matrix.mat4; ar2[0] = mat3[0]; ar2[1] = mat3[1]; ar2[2] = mat3[2]; ar2[3] = mat3[3]; ar2[4] = mat3[4]; ar2[5] = mat3[5]; ar2[6] = mat3[6]; ar2[7] = mat3[7]; ar2[8] = mat3[8]; return matrix; } copyTo2d(matrix: Matrix2d): Matrix2d { const mat3 = this.mat4; const ar2 = matrix.mat3; ar2[0] = mat3[0]; ar2[1] = mat3[1]; ar2[2] = mat3[3]; ar2[3] = mat3[4]; ar2[4] = mat3[5]; ar2[5] = mat3[7]; ar2[6] = mat3[12]; ar2[7] = mat3[13]; ar2[8] = mat3[15]; return matrix; } copyTo2dOr3d<P extends Matrix2d | Matrix3d>(matrix: P): P { if (matrix instanceof Matrix2d) { return this.copyTo2d(matrix) as any; } return this.copyTo3d(matrix as any) as any; } /** * legacy method, change the values of given pixi matrix * @param matrix * @param affine * @param preserveOrientation * @return matrix */ copyTo(matrix: Matrix, affine?: AFFINE, preserveOrientation?: boolean): Matrix { const mat3 = this.mat4; const d = 1.0 / mat3[15]; const tx = mat3[12] * d; const ty = mat3[13] * d; matrix.a = (mat3[0] - mat3[3] * tx) * d; matrix.b = (mat3[1] - mat3[3] * ty) * d; matrix.c = (mat3[4] - mat3[7] * tx) * d; matrix.d = (mat3[5] - mat3[7] * ty) * d; matrix.tx = tx; matrix.ty = ty; if (affine >= 2) { let D = matrix.a * matrix.d - matrix.b * matrix.c; if (!preserveOrientation) { D = Math.abs(D); } if (affine === AFFINE.POINT) { if (D > 0) { D = 1; } else D = -1; matrix.a = D; matrix.b = 0; matrix.c = 0; matrix.d = D; } else if (affine === AFFINE.AXIS_X) { D /= Math.sqrt(matrix.b * matrix.b + matrix.d * matrix.d); matrix.c = 0; matrix.d = D; } else if (affine === AFFINE.AXIS_Y) { D /= Math.sqrt(matrix.a * matrix.a + matrix.c * matrix.c); matrix.a = D; matrix.c = 0; } } return matrix; } /** * legacy method, change the values of given pixi matrix * @param matrix * @return */ copyFrom(matrix: Matrix): this { const mat3 = this.mat4; mat3[0] = matrix.a; mat3[1] = matrix.b; mat3[2] = 0; mat3[3] = 0; mat3[4] = matrix.c; mat3[5] = matrix.d; mat3[6] = 0; mat3[7] = 0; mat3[8] = 0; mat3[9] = 0; mat3[10] = 1; mat3[11] = 0; mat3[12] = matrix.tx; mat3[13] = matrix.ty; mat3[14] = 0; mat3[15] = 1; this._dirtyId++; return this; } setToMultLegacy(pt: Matrix, lt: Matrix3d): this { const out = this.mat4; const b = lt.mat4; const a00 = pt.a; const a01 = pt.b; const a10 = pt.c; const a11 = pt.d; const a30 = pt.tx; const a31 = pt.ty; let b0 = b[0]; let b1 = b[1]; let b2 = b[2]; let b3 = b[3]; out[0] = b0 * a00 + b1 * a10 + b3 * a30; out[1] = b0 * a01 + b1 * a11 + b3 * a31; out[2] = b2; out[3] = b3; b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; out[4] = b0 * a00 + b1 * a10 + b3 * a30; out[5] = b0 * a01 + b1 * a11 + b3 * a31; out[6] = b2; out[7] = b3; b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; out[8] = b0 * a00 + b1 * a10 + b3 * a30; out[9] = b0 * a01 + b1 * a11 + b3 * a31; out[10] = b2; out[11] = b3; b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; out[12] = b0 * a00 + b1 * a10 + b3 * a30; out[13] = b0 * a01 + b1 * a11 + b3 * a31; out[14] = b2; out[15] = b3; this._dirtyId++; return this; } setToMultLegacy2(pt: Matrix3d, lt: Matrix): this { const out = this.mat4; const a = pt.mat4; const a00 = a[0]; const a01 = a[1]; const a02 = a[2]; const a03 = a[3]; const a10 = a[4]; const a11 = a[5]; const a12 = a[6]; const a13 = a[7]; const b00 = lt.a; const b01 = lt.b; const b10 = lt.c; const b11 = lt.d; const b30 = lt.tx; const b31 = lt.ty; out[0] = b00 * a00 + b01 * a10; out[1] = b00 * a01 + b01 * a11; out[2] = b00 * a02 + b01 * a12; out[3] = b00 * a03 + b01 * a13; out[4] = b10 * a00 + b11 * a10; out[5] = b10 * a01 + b11 * a11; out[6] = b10 * a02 + b11 * a12; out[7] = b10 * a03 + b11 * a13; out[8] = a[8]; out[9] = a[9]; out[10] = a[10]; out[11] = a[11]; out[12] = b30 * a00 + b31 * a10 + a[12]; out[13] = b30 * a01 + b31 * a11 + a[13]; out[14] = b30 * a02 + b31 * a12 + a[14]; out[15] = b30 * a03 + b31 * a13 + a[15]; this._dirtyId++; return this; } // that's transform multiplication we use setToMult(pt: Matrix3d, lt: Matrix3d): this { Matrix3d.glMatrixMat4Multiply(this.mat4, pt.mat4, lt.mat4); this._dirtyId++; return this; } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types prepend(lt: any): void { if (lt.mat4) { this.setToMult(lt, this); } else { this.setToMultLegacy(lt, this); } } static glMatrixMat4Invert(out: Float64Array, a: Float64Array): Float64Array { const a00 = a[0]; const a01 = a[1]; const a02 = a[2]; const a03 = a[3]; const a10 = a[4]; const a11 = a[5]; const a12 = a[6]; const a13 = a[7]; const a20 = a[8]; const a21 = a[9]; const a22 = a[10]; const a23 = a[11]; const a30 = a[12]; const a31 = a[13]; const a32 = a[14]; const a33 = a[15]; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; const b02 = a00 * a13 - a03 * a10; const b03 = a01 * a12 - a02 * a11; const b04 = a01 * a13 - a03 * a11; const b05 = a02 * a13 - a03 * a12; const b06 = a20 * a31 - a21 * a30; const b07 = a20 * a32 - a22 * a30; const b08 = a20 * a33 - a23 * a30; const b09 = a21 * a32 - a22 * a31; const b10 = a21 * a33 - a23 * a31; const b11 = a22 * a33 - a23 * a32; // Calculate the determinant let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { return null; } det = 1.0 / det; out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; return out; } static glMatrixMat4Multiply(out: Float64Array, a: Float64Array, b: Float64Array): Float64Array { const a00 = a[0]; const a01 = a[1]; const a02 = a[2]; const a03 = a[3]; const a10 = a[4]; const a11 = a[5]; const a12 = a[6]; const a13 = a[7]; const a20 = a[8]; const a21 = a[9]; const a22 = a[10]; const a23 = a[11]; const a30 = a[12]; const a31 = a[13]; const a32 = a[14]; const a33 = a[15]; // Cache only the current line of the second matrix let b0 = b[0]; let b1 = b[1]; let b2 = b[2]; let b3 = b[3]; out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; return out; } }
the_stack
import { hexToBin } from '../format/hex'; import { validateSecp256k1PrivateKey } from '../key/key-utils'; import { CompilerDefaults } from './compiler-defaults'; import { BuiltInVariables } from './language/resolve'; import { AuthenticationTemplate, AuthenticationTemplateAddressData, AuthenticationTemplateEntity, AuthenticationTemplateHdKey, AuthenticationTemplateKey, AuthenticationTemplateScenario, AuthenticationTemplateScenarioData, AuthenticationTemplateScenarioInput, AuthenticationTemplateScenarioOutput, AuthenticationTemplateScript, AuthenticationTemplateScriptLocking, AuthenticationTemplateScriptTest, AuthenticationTemplateScriptTested, AuthenticationTemplateScriptUnlocking, AuthenticationTemplateVariable, AuthenticationTemplateWalletData, AuthenticationVirtualMachineIdentifier, } from './template-types'; const listIds = (ids: string[]) => ids .map((id) => `"${id}"`) .sort((a, b) => a.localeCompare(b)) .join(', '); /** * Verify that the provided value is an array which is not sparse. */ const isDenseArray = (maybeArray: unknown): maybeArray is unknown[] => Array.isArray(maybeArray) && !maybeArray.includes(undefined); /** * Check that a value is an array which contains only strings and has no empty * items (is not a sparse array, e.g. `[1, , 3]`). */ const isStringArray = (maybeArray: unknown): maybeArray is string[] => isDenseArray(maybeArray) && !maybeArray.some((item) => typeof item !== 'string'); const isObject = (maybeObject: unknown): maybeObject is object => typeof maybeObject === 'object' && maybeObject !== null; const isStringObject = ( maybeStringObject: object ): maybeStringObject is { [key: string]: string } => !Object.values(maybeStringObject).some((value) => typeof value !== 'string'); const hasNonHexCharacter = /[^a-fA-F0-9]/u; const isHexString = (maybeHexString: unknown): maybeHexString is string => typeof maybeHexString === 'string' && !hasNonHexCharacter.test(maybeHexString); const characterLength32BytePrivateKey = 64; const isObjectOfValidPrivateKeys = ( maybePrivateKeysObject: object ): maybePrivateKeysObject is { [key: string]: string } => !Object.values(maybePrivateKeysObject).some( (value) => !isHexString(value) || value.length !== characterLength32BytePrivateKey || !validateSecp256k1PrivateKey(hexToBin(value)) ); const isInteger = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value); const isPositiveInteger = (value: unknown): value is number => isInteger(value) && value >= 0; const isRangedInteger = ( value: unknown, minimum: number, maximum: number ): value is number => isInteger(value) && value >= minimum && value <= maximum; /** * Verify that a value is a valid `satoshi` value: either a number between `0` * and `Number.MAX_SAFE_INTEGER` or a 16-character, hexadecimal-encoded string. * * @param maybeSatoshis - the value to verify */ const isValidSatoshisValue = ( maybeSatoshis: unknown ): maybeSatoshis is number | string | undefined => { const uint64HexLength = 16; if ( maybeSatoshis === undefined || isRangedInteger(maybeSatoshis, 0, Number.MAX_SAFE_INTEGER) || (isHexString(maybeSatoshis) && maybeSatoshis.length === uint64HexLength) ) { return true; } return false; }; /** * Parse an authentication template `scripts` object into its component scripts, * validating the shape of each script object. Returns either an error message * as a string or an object of cloned and sorted scripts. * * @param scripts - the `scripts` property of an `AuthenticationTemplate` */ // eslint-disable-next-line complexity export const parseAuthenticationTemplateScripts = (scripts: object) => { const unknownScripts = Object.entries(scripts).map<{ id: string; script: unknown; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment }>(([id, script]) => ({ id, script })); const nonObjectScripts = unknownScripts .filter(({ script }) => typeof script !== 'object' || script === null) .map(({ id }) => id); if (nonObjectScripts.length > 0) { return `All authentication template scripts must be objects, but the following scripts are not objects: ${listIds( nonObjectScripts )}.`; } const allScripts = unknownScripts as { id: string; script: object }[]; const unlockingResults: ( | { id: string; script: AuthenticationTemplateScriptUnlocking } | string )[] = allScripts .filter(({ script }) => 'unlocks' in script) // eslint-disable-next-line complexity .map(({ id, script }) => { const { ageLock, estimate, fails, invalid, name, passes, script: scriptContents, timeLockType, unlocks, } = script as { ageLock: unknown; estimate: unknown; fails: unknown; invalid: unknown; name: unknown; passes: unknown; script: unknown; timeLockType: unknown; unlocks: unknown; }; if (typeof unlocks !== 'string') { return `The "unlocks" property of unlocking script "${id}" must be a string.`; } if (typeof scriptContents !== 'string') { return `The "script" property of unlocking script "${id}" must be a string.`; } if (ageLock !== undefined && typeof ageLock !== 'string') { return `If defined, the "ageLock" property of unlocking script "${id}" must be a string.`; } if (estimate !== undefined && typeof estimate !== 'string') { return `If defined, the "estimate" property of unlocking script "${id}" must be a string.`; } if (name !== undefined && typeof name !== 'string') { return `If defined, the "name" property of unlocking script "${id}" must be a string.`; } if (fails !== undefined && !isStringArray(fails)) { return `If defined, the "fails" property of unlocking script "${id}" must be an array containing only scenario identifiers (strings).`; } if (invalid !== undefined && !isStringArray(invalid)) { return `If defined, the "invalid" property of unlocking script "${id}" must be an array containing only scenario identifiers (strings).`; } if (passes !== undefined && !isStringArray(passes)) { return `If defined, the "passes" property of unlocking script "${id}" must be an array containing only scenario identifiers (strings).`; } if ( timeLockType !== undefined && timeLockType !== ('timestamp' as const) && timeLockType !== ('height' as const) ) { return `If defined, the "timeLockType" property of unlocking script "${id}" must be either "timestamp" or "height".`; } return { id, script: { ...(ageLock === undefined ? {} : { ageLock }), ...(estimate === undefined ? {} : { estimate }), ...(fails === undefined ? {} : { fails }), ...(invalid === undefined ? {} : { invalid }), ...(passes === undefined ? {} : { passes }), ...(name === undefined ? {} : { name }), script: scriptContents, ...(timeLockType === undefined ? {} : { timeLockType }), unlocks, }, }; }); const invalidUnlockingResults = unlockingResults.filter( (result): result is string => typeof result === 'string' ); if (invalidUnlockingResults.length > 0) { return invalidUnlockingResults.join(' '); } const validUnlockingResults = unlockingResults as { id: string; script: AuthenticationTemplateScriptUnlocking; }[]; const unlocking = validUnlockingResults.reduce<{ [id: string]: AuthenticationTemplateScriptUnlocking; }>((all, result) => ({ ...all, [result.id]: result.script }), {}); const unlockingIds = validUnlockingResults.map(({ id }) => id); const impliedLockingIds = validUnlockingResults.map( ({ script }) => script.unlocks ); const lockingResults: ( | { id: string; script: AuthenticationTemplateScriptLocking } | string )[] = allScripts .filter( ({ id, script }) => 'lockingType' in script || impliedLockingIds.includes(id) ) // eslint-disable-next-line complexity .map(({ id, script }) => { const { lockingType, script: scriptContents, name } = script as { name: unknown; script: unknown; lockingType: unknown; }; if (lockingType !== 'standard' && lockingType !== 'p2sh') { return `The "lockingType" property of locking script "${id}" must be either "standard" or "p2sh".`; } if (typeof scriptContents !== 'string') { return `The "script" property of locking script "${id}" must be a string.`; } if (name !== undefined && typeof name !== 'string') { return `If defined, the "name" property of locking script "${id}" must be a string.`; } return { id, script: { lockingType, ...(name === undefined ? {} : { name }), script: scriptContents, }, }; }); const invalidLockingResults = lockingResults.filter( (result): result is string => typeof result === 'string' ); if (invalidLockingResults.length > 0) { return invalidLockingResults.join(' '); } const validLockingResults = lockingResults as { id: string; script: AuthenticationTemplateScriptLocking; }[]; const locking = validLockingResults.reduce<{ [id: string]: AuthenticationTemplateScriptLocking; }>((all, result) => ({ ...all, [result.id]: result.script }), {}); const lockingIds = validLockingResults.map(({ id }) => id); const unknownLockingIds = Object.values(unlocking) .map((script) => script.unlocks) .filter((unlocks) => !lockingIds.includes(unlocks)); if (unknownLockingIds.length > 0) { return `The following locking scripts (referenced in "unlocks" properties) were not provided: ${listIds( unknownLockingIds )}.`; } const testedResults: ( | { id: string; script: AuthenticationTemplateScriptTested } | string )[] = allScripts .filter(({ script }) => 'tests' in script) // eslint-disable-next-line complexity .map(({ id, script }) => { const { tests, script: scriptContents, name, pushed } = script as { name: unknown; script: unknown; tests: unknown; pushed: unknown; }; if (typeof scriptContents !== 'string') { return `The "script" property of tested script "${id}" must be a string.`; } if (name !== undefined && typeof name !== 'string') { return `If defined, the "name" property of tested script "${id}" must be a string.`; } if (pushed !== undefined && pushed !== true && pushed !== false) { return `If defined, the "pushed" property of tested script "${id}" must be a boolean value.`; } if (!Array.isArray(tests)) { return `If defined, the "tests" property of tested script "${id}" must be an array.`; } const extractedTests = // eslint-disable-next-line complexity tests.map<string | AuthenticationTemplateScriptTest>((test) => { const { check, fails, invalid, name: testName, passes, setup, } = test as { check: unknown; fails: unknown; invalid: unknown; name: unknown; passes: unknown; setup: unknown; }; if (typeof check !== 'string') { return `The "check" properties of all tests in tested script "${id}" must be a strings.`; } if (testName !== undefined && typeof testName !== 'string') { return `If defined, the "name" properties of all tests in tested script "${id}" must be strings.`; } if (setup !== undefined && typeof setup !== 'string') { return `If defined, the "setup" properties of all tests in tested script "${id}" must be strings.`; } if (fails !== undefined && !isStringArray(fails)) { return `If defined, the "fails" property of each test in tested script "${id}" must be an array containing only scenario identifiers (strings).`; } if (invalid !== undefined && !isStringArray(invalid)) { return `If defined, the "invalid" property of each test in tested script "${id}" must be an array containing only scenario identifiers (strings).`; } if (passes !== undefined && !isStringArray(passes)) { return `If defined, the "passes" property of each test in tested script "${id}" must be an array containing only scenario identifiers (strings).`; } return { check, ...(fails === undefined ? {} : { fails }), ...(invalid === undefined ? {} : { invalid }), ...(passes === undefined ? {} : { passes }), ...(testName === undefined ? {} : { name: testName }), ...(setup === undefined ? {} : { setup }), }; }); const invalidTests = extractedTests.filter( (result): result is string => typeof result === 'string' ); if (invalidTests.length > 0) { return invalidTests.join(' '); } const validTests = extractedTests as AuthenticationTemplateScriptTest[]; return { id, script: { ...(name === undefined ? {} : { name }), ...(pushed === undefined ? {} : { pushed }), script: scriptContents, tests: validTests, }, }; }); const invalidTestedResults = testedResults.filter( (result): result is string => typeof result === 'string' ); if (invalidTestedResults.length > 0) { return invalidTestedResults.join(' '); } const validTestedResults = testedResults as { id: string; script: AuthenticationTemplateScriptTested; }[]; const tested = validTestedResults.reduce<{ [id: string]: AuthenticationTemplateScriptTested; }>((all, result) => ({ ...all, [result.id]: result.script }), {}); const testedIds = validTestedResults.map(({ id }) => id); const lockingAndUnlockingIds = [...lockingIds, ...unlockingIds]; const lockingAndUnlockingIdsWithTests = lockingAndUnlockingIds.filter((id) => testedIds.includes(id) ); if (lockingAndUnlockingIdsWithTests.length > 0) { return `Locking and unlocking scripts may not have tests, but the following scripts include a "tests" property: ${listIds( lockingAndUnlockingIdsWithTests )}`; } const alreadySortedIds = [...lockingAndUnlockingIds, testedIds]; const otherResults: ( | { id: string; script: AuthenticationTemplateScript } | string )[] = allScripts .filter(({ id }) => !alreadySortedIds.includes(id)) .map(({ id, script }) => { const { script: scriptContents, name } = script as { name: unknown; script: unknown; timeLockType: unknown; unlocks: unknown; }; if (typeof scriptContents !== 'string') { return `The "script" property of script "${id}" must be a string.`; } if (name !== undefined && typeof name !== 'string') { return `If defined, the "name" property of script "${id}" must be a string.`; } return { id, script: { ...(name === undefined ? {} : { name }), script: scriptContents, }, }; }); const invalidOtherResults = otherResults.filter( (result): result is string => typeof result === 'string' ); if (invalidOtherResults.length > 0) { return invalidOtherResults.join(' '); } const validOtherResults = otherResults as { id: string; script: AuthenticationTemplateScript; }[]; const other = validOtherResults.reduce<{ [id: string]: AuthenticationTemplateScript; }>((all, result) => ({ ...all, [result.id]: result.script }), {}); return { locking, other, tested, unlocking, }; }; const authenticationTemplateVariableTypes = [ 'AddressData', 'HdKey', 'Key', 'WalletData', ] as AuthenticationTemplateVariable['type'][]; const isAuthenticationTemplateVariableType = ( type: unknown ): type is AuthenticationTemplateVariable['type'] => authenticationTemplateVariableTypes.includes( type as AuthenticationTemplateVariable['type'] ); /** * Parse an authentication template entity `variables` object into its component * variables, validating the shape of each variable object. Returns either an * error message as a string or the cloned variables object. * * @param scripts - the `scripts` property of an `AuthenticationTemplate` */ export const parseAuthenticationTemplateVariable = ( variables: object, entityId: string ) => { const unknownVariables = Object.entries(variables).map<{ id: string; variable: unknown; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment }>(([id, variable]) => ({ id, variable })); const nonObjectVariables = unknownVariables .filter(({ variable }) => typeof variable !== 'object' || variable === null) .map(({ id }) => id); if (nonObjectVariables.length > 0) { return `All authentication template variables must be objects, but the following variables owned by entity "${entityId}" are not objects: ${listIds( nonObjectVariables )}.`; } const allEntities = unknownVariables as { id: string; variable: object }[]; const variableResults: ( | { id: string; variable: AuthenticationTemplateVariable } | string )[] = allEntities // eslint-disable-next-line complexity .map(({ id, variable }) => { const { description, name, type } = variable as { description: unknown; name: unknown; type: unknown; }; if (!isAuthenticationTemplateVariableType(type)) { return `The "type" property of variable "${id}" must be a valid authentication template variable type. Available types are: ${listIds( authenticationTemplateVariableTypes )}.`; } if (description !== undefined && typeof description !== 'string') { return `If defined, the "description" property of variable "${id}" must be a string.`; } if (name !== undefined && typeof name !== 'string') { return `If defined, the "name" property of variable "${id}" must be a string.`; } if (type === 'HdKey') { const { addressOffset, hdPublicKeyDerivationPath, privateDerivationPath, publicDerivationPath, } = variable as { addressOffset: unknown; hdPublicKeyDerivationPath: unknown; privateDerivationPath: unknown; publicDerivationPath: unknown; }; if (addressOffset !== undefined && typeof addressOffset !== 'number') { return `If defined, the "addressOffset" property of HdKey "${id}" must be a number.`; } if ( hdPublicKeyDerivationPath !== undefined && typeof hdPublicKeyDerivationPath !== 'string' ) { return `If defined, the "hdPublicKeyDerivationPath" property of HdKey "${id}" must be a string.`; } if ( privateDerivationPath !== undefined && typeof privateDerivationPath !== 'string' ) { return `If defined, the "privateDerivationPath" property of HdKey "${id}" must be a string.`; } if ( publicDerivationPath !== undefined && typeof publicDerivationPath !== 'string' ) { return `If defined, the "publicDerivationPath" property of HdKey "${id}" must be a string.`; } const hdPublicKeyPath = hdPublicKeyDerivationPath ?? CompilerDefaults.hdKeyHdPublicKeyDerivationPath; const privatePath = privateDerivationPath ?? CompilerDefaults.hdKeyPrivateDerivationPath; const publicPath = publicDerivationPath ?? privatePath.replace('m', 'M'); const validPrivatePathWithIndex = /^m(?:\/(?:[0-9]+|i)'?)*$/u; const validPrivatePath = /^m(?:\/[0-9]+'?)*$/u; const replacedPrivatePath = privatePath.replace('i', '0'); if ( !validPrivatePathWithIndex.test(privatePath) && !validPrivatePath.test(replacedPrivatePath) ) { return `If defined, the "privateDerivationPath" property of HdKey "${id}" must be a valid private derivation path, but the provided value is "${hdPublicKeyPath}". A valid path must begin with "m" and include only "/", "'", a single "i" address index character, and numbers.`; } if (!validPrivatePath.test(hdPublicKeyPath)) { return `If defined, the "hdPublicKeyDerivationPath" property of an HdKey must be a valid private derivation path for the HdKey's HD public node, but the provided value for HdKey "${id}" is "${hdPublicKeyPath}". A valid path must begin with "m" and include only "/", "'", and numbers (the "i" character cannot be used in "hdPublicKeyDerivationPath").`; } const validPublicPathWithIndex = /^M(?:\/(?:[0-9]+|i))*$/u; const validPublicPath = /^M(?:\/[0-9]+)*$/u; const replacedPublicPath = publicPath.replace('i', '0'); if ( !validPublicPathWithIndex.test(publicPath) && !validPublicPath.test(replacedPublicPath) ) { return `The "publicDerivationPath" property of HdKey "${id}" must be a valid public derivation path, but the current value is "${publicPath}". Public derivation paths must begin with "M" and include only "/", a single "i" address index character, and numbers. If the "privateDerivationPath" uses hardened derivation, the "publicDerivationPath" should be set to enable public derivation from the "hdPublicKeyDerivationPath".`; } const publicPathSuffix = publicPath.replace('M/', ''); const impliedPrivatePath = `${hdPublicKeyPath}/${publicPathSuffix}`; if (impliedPrivatePath !== privatePath) { return `The "privateDerivationPath" property of HdKey "${id}" is "${privatePath}", but the implied private derivation path of "hdPublicKeyDerivationPath" and "publicDerivationPath" is "${impliedPrivatePath}". The "publicDerivationPath" property must be set to allow for public derivation of the same HD node derived by "privateDerivationPath" beginning from the HD public key derived at "hdPublicKeyDerivationPath".`; } return { id, variable: { ...(addressOffset === undefined ? {} : { addressOffset }), ...(description === undefined ? {} : { description }), ...(hdPublicKeyDerivationPath === undefined ? {} : { hdPublicKeyDerivationPath }), ...(name === undefined ? {} : { name }), ...(privateDerivationPath === undefined ? {} : { privateDerivationPath }), ...(publicDerivationPath === undefined ? {} : { publicDerivationPath }), type, } as AuthenticationTemplateHdKey, }; } return { id, variable: { ...(description === undefined ? {} : { description }), ...(name === undefined ? {} : { name }), type, } as | AuthenticationTemplateWalletData | AuthenticationTemplateAddressData | AuthenticationTemplateKey, }; }); const invalidVariableResults = variableResults.filter( (result): result is string => typeof result === 'string' ); if (invalidVariableResults.length > 0) { return invalidVariableResults.join(' '); } const validVariableResults = (variableResults as unknown) as { id: string; variable: AuthenticationTemplateVariable; }[]; const clonedVariables = validVariableResults.reduce<{ [id: string]: AuthenticationTemplateVariable; }>((all, result) => ({ ...all, [result.id]: result.variable }), {}); return clonedVariables; }; /** * Parse an authentication template `entities` object into its component * entities, validating the shape of each entity object. Returns either an error * message as a string or the cloned entities object. * * @param scripts - the `scripts` property of an `AuthenticationTemplate` */ export const parseAuthenticationTemplateEntities = (entities: object) => { const unknownEntities = Object.entries(entities).map<{ id: string; entity: unknown; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment }>(([id, entity]) => ({ entity, id })); const nonObjectEntities = unknownEntities .filter(({ entity }) => typeof entity !== 'object' || entity === null) .map(({ id }) => id); if (nonObjectEntities.length > 0) { return `All authentication template entities must be objects, but the following entities are not objects: ${listIds( nonObjectEntities )}.`; } const allEntities = unknownEntities as { id: string; entity: object }[]; const entityResults: ( | { id: string; entity: AuthenticationTemplateEntity } | string )[] = allEntities // eslint-disable-next-line complexity .map(({ id, entity }) => { const { description, name, scripts, variables } = entity as { description: unknown; name: unknown; scripts: unknown; variables: unknown; }; if (description !== undefined && typeof description !== 'string') { return `If defined, the "description" property of entity "${id}" must be a string.`; } if (name !== undefined && typeof name !== 'string') { return `If defined, the "name" property of entity "${id}" must be a string.`; } if (scripts !== undefined && !isStringArray(scripts)) { return `If defined, the "scripts" property of entity "${id}" must be an array containing only script identifiers (strings).`; } if (variables !== undefined && !isObject(variables)) { return `If defined, the "variables" property of entity "${id}" must be an object.`; } const variableResult = variables === undefined ? undefined : parseAuthenticationTemplateVariable(variables, id); if (typeof variableResult === 'string') { return variableResult; } return { entity: { ...(description === undefined ? {} : { description }), ...(name === undefined ? {} : { name }), ...(scripts === undefined ? {} : { scripts }), ...(variableResult === undefined ? {} : { variables: variableResult }), }, id, }; }); const invalidEntityResults = entityResults.filter( (result): result is string => typeof result === 'string' ); if (invalidEntityResults.length > 0) { return invalidEntityResults.join(' '); } const validEntityResults = entityResults as { id: string; entity: AuthenticationTemplateEntity; }[]; const clonedEntities = validEntityResults.reduce<{ [id: string]: AuthenticationTemplateEntity; }>((all, result) => ({ ...all, [result.id]: result.entity }), {}); return clonedEntities; }; /** * Validate and clone an Authentication Template Scenario `data.hdKeys` object. * * @param hdKeys - the `data.hdKeys` object to validate and clone * @param location - the location of the error to specify in error messages, * e.g. `scenario "test"` or * `'lockingBytecode.override' in output 2 of scenario "test"` */ // eslint-disable-next-line complexity export const parseAuthenticationTemplateScenarioDataHdKeys = ( hdKeys: object, location: string ): string | AuthenticationTemplateScenarioData['hdKeys'] => { const { addressIndex, hdPublicKeys, hdPrivateKeys } = hdKeys as { addressIndex: unknown; hdPublicKeys: unknown; hdPrivateKeys: unknown; }; const maximumAddressIndex = 2147483648; if ( addressIndex !== undefined && !isRangedInteger(addressIndex, 0, maximumAddressIndex) ) { return `If defined, the "data.hdKeys.addressIndex" property of ${location} must be a positive integer between 0 and 2,147,483,648 (inclusive).`; } if ( hdPublicKeys !== undefined && !(isObject(hdPublicKeys) && isStringObject(hdPublicKeys)) ) { return `If defined, the "data.hdKeys.hdPublicKeys" property of ${location} must be an object, and each value must be a string.`; } if ( hdPrivateKeys !== undefined && !(isObject(hdPrivateKeys) && isStringObject(hdPrivateKeys)) ) { return `If defined, the "data.hdKeys.hdPrivateKeys" property of ${location} must be an object, and each value must be a string.`; } return { ...(addressIndex === undefined ? {} : { addressIndex }), ...(hdPublicKeys === undefined ? {} : { hdPublicKeys: { ...hdPublicKeys } }), ...(hdPrivateKeys === undefined ? {} : { hdPrivateKeys: { ...hdPrivateKeys } }), }; }; /** * Validate and clone an Authentication Template Scenario `data.keys` object. * * @param keys - the `data.keys` object to validate and clone * @param location - the location of the error to specify in error messages, * e.g. `scenario "test"` or * `'lockingBytecode.override' in output 2 of scenario "test"` */ export const parseAuthenticationTemplateScenarioDataKeys = ( keys: object, location: string ): string | AuthenticationTemplateScenarioData['keys'] => { const { privateKeys } = keys as { privateKeys: unknown }; if ( privateKeys !== undefined && !(isObject(privateKeys) && isObjectOfValidPrivateKeys(privateKeys)) ) { return `If defined, the "data.keys.privateKeys" property of ${location} must be an object, and each value must be a 32-byte, hexadecimal-encoded private key.`; } return { ...(privateKeys === undefined ? {} : { privateKeys }) }; }; /** * Validate and clone an Authentication Template Scenario `data` object. * * @param data - the `data` object to validate and clone * @param location - the location of the error to specify in error messages, * e.g. `scenario "test"` or * `'lockingBytecode.override' in output 2 of scenario "test"` */ // eslint-disable-next-line complexity export const parseAuthenticationTemplateScenarioData = ( data: object, location: string ): string | AuthenticationTemplateScenarioData => { const { bytecode, currentBlockHeight, currentBlockTime, hdKeys, keys, } = data as { bytecode: unknown; currentBlockHeight: unknown; currentBlockTime: unknown; hdKeys: unknown; keys: unknown; }; if ( bytecode !== undefined && (!isObject(bytecode) || !isStringObject(bytecode)) ) { return `If defined, the "data.bytecode" property of ${location} must be an object, and each value must be a string.`; } const minimumBlockTime = 500000000; const maximumBlockTime = 4294967295; if ( currentBlockHeight !== undefined && !isRangedInteger(currentBlockHeight, 0, minimumBlockTime - 1) ) { return `If defined, the "currentBlockHeight" property of ${location} must be a positive integer from 0 to 499,999,999 (inclusive).`; } if ( currentBlockTime !== undefined && !isRangedInteger(currentBlockTime, minimumBlockTime, maximumBlockTime) ) { return `If defined, the "currentBlockTime" property of ${location} must be a positive integer from 500,000,000 to 4,294,967,295 (inclusive).`; } const hdKeysResult = hdKeys === undefined ? undefined : isObject(hdKeys) ? parseAuthenticationTemplateScenarioDataHdKeys(hdKeys, location) : `If defined, the "data.hdKeys" property of ${location} must be an object.`; if (typeof hdKeysResult === 'string') { return hdKeysResult; } const keysResult = keys === undefined ? undefined : isObject(keys) ? parseAuthenticationTemplateScenarioDataKeys(keys, location) : `If defined, the "data.keys" property of ${location} must be an object.`; if (typeof keysResult === 'string') { return keysResult; } return { ...(bytecode === undefined ? {} : { bytecode: { ...bytecode } }), ...(currentBlockHeight === undefined ? {} : { currentBlockHeight }), ...(currentBlockTime === undefined ? {} : { currentBlockTime }), ...(hdKeysResult === undefined ? {} : { hdKeys: hdKeysResult }), ...(keysResult === undefined ? {} : { keys: keysResult }), }; }; /** * Validate and clone an Authentication Template Scenario `transaction.inputs` * array. * * @param inputs - the `transaction.inputs` array to validate and clone * @param location - the location of the error to specify in error messages, * e.g. `scenario "test"` */ export const parseAuthenticationTemplateScenarioTransactionInputs = ( inputs: unknown, location: string ): undefined | string | AuthenticationTemplateScenarioInput[] => { if (inputs === undefined) { return undefined; } if (!isDenseArray(inputs)) { return `If defined, the "transaction.inputs" property of ${location} must be an array of scenario input objects.`; } const inputResults: (AuthenticationTemplateScenarioInput | string)[] = inputs // eslint-disable-next-line complexity .map((maybeInput, inputIndex) => { const { outpointIndex, outpointTransactionHash, sequenceNumber, unlockingBytecode, } = maybeInput as { outpointIndex: unknown; outpointTransactionHash: unknown; sequenceNumber: unknown; unlockingBytecode: unknown; }; const newLocation = `input ${inputIndex} in ${location}`; if (outpointIndex !== undefined && !isPositiveInteger(outpointIndex)) { return `If defined, the "outpointIndex" property of ${newLocation} must be a positive integer.`; } const characterLength32ByteHash = 64; if ( outpointTransactionHash !== undefined && !( isHexString(outpointTransactionHash) && outpointTransactionHash.length === characterLength32ByteHash ) ) { return `If defined, the "outpointTransactionHash" property of ${newLocation} must be a 32-byte, hexadecimal-encoded hash (string).`; } const maxSequenceNumber = 0xffffffff; if ( sequenceNumber !== undefined && !isRangedInteger(sequenceNumber, 0, maxSequenceNumber) ) { return `If defined, the "sequenceNumber" property of ${newLocation} must be a number between 0 and 4294967295 (inclusive).`; } if ( unlockingBytecode !== undefined && unlockingBytecode !== null && !isHexString(unlockingBytecode) ) { return `If defined, the "unlockingBytecode" property of ${newLocation} must be either a null value or a hexadecimal-encoded string.`; } return { ...(outpointIndex === undefined ? {} : { outpointIndex }), ...(outpointTransactionHash === undefined ? {} : { outpointTransactionHash }), ...(sequenceNumber === undefined ? {} : { sequenceNumber }), ...(unlockingBytecode === undefined ? {} : { unlockingBytecode }), }; }); const invalidInputResults = inputResults.filter( (result): result is string => typeof result === 'string' ); if (invalidInputResults.length > 0) { return invalidInputResults.join(' '); } const clonedInputs = inputResults as AuthenticationTemplateScenarioInput[]; return clonedInputs; }; /** * Validate and clone an Authentication Template Scenario transaction output * `lockingBytecode` object. * * @param outputs - the `transaction.outputs[outputIndex].lockingBytecode` * object to validate and clone * @param location - the location of the error to specify in error messages, * e.g. `output 2 in scenario "test"` */ // eslint-disable-next-line complexity export const parseAuthenticationTemplateScenarioTransactionOutputLockingBytecode = ( lockingBytecode: object, location: string ): string | AuthenticationTemplateScenarioOutput['lockingBytecode'] => { const { overrides, script } = lockingBytecode as { overrides: unknown; script: unknown; }; if (script !== undefined && script !== null && !isHexString(script)) { return `If defined, the "script" property of ${location} must be a hexadecimal-encoded string or "null".`; } const clonedOverrides = overrides === undefined ? undefined : isObject(overrides) ? parseAuthenticationTemplateScenarioData( overrides, `'lockingBytecode.override' in ${location}` ) : `If defined, the "overrides" property of ${location} must be an object.`; if (typeof clonedOverrides === 'string') { return clonedOverrides; } return { ...(script === undefined ? {} : { script }), ...(clonedOverrides === undefined ? {} : { overrides: clonedOverrides }), }; }; /** * Validate and clone an Authentication Template Scenario `transaction.outputs` * array. * * @param outputs - the `transaction.outputs` array to validate and clone * @param location - the location of the error to specify in error messages, * e.g. `of output 2 in scenario "test"` */ export const parseAuthenticationTemplateScenarioTransactionOutputs = ( outputs: unknown, location: string ): undefined | string | AuthenticationTemplateScenarioOutput[] => { if (outputs === undefined) { return undefined; } if (!isDenseArray(outputs)) { return `If defined, the "transaction.outputs" property of ${location} must be an array of scenario output objects.`; } const outputResults: ( | AuthenticationTemplateScenarioOutput | string )[] = outputs // eslint-disable-next-line complexity .map((maybeOutput, outputIndex) => { const { lockingBytecode, satoshis } = maybeOutput as { lockingBytecode: unknown; satoshis: unknown; }; const newLocation = `output ${outputIndex} in ${location}`; if ( lockingBytecode !== undefined && typeof lockingBytecode !== 'string' && !isObject(lockingBytecode) ) { return `If defined, the "lockingBytecode" property of ${newLocation} must be a string or an object.`; } if ( typeof lockingBytecode === 'string' && !isHexString(lockingBytecode) ) { return `If the "lockingBytecode" property of ${newLocation} is a string, it must be a valid, hexadecimal-encoded locking bytecode.`; } const clonedLockingBytecode = lockingBytecode === undefined || typeof lockingBytecode === 'string' ? undefined : parseAuthenticationTemplateScenarioTransactionOutputLockingBytecode( lockingBytecode, newLocation ); if (typeof clonedLockingBytecode === 'string') { return clonedLockingBytecode; } if (!isValidSatoshisValue(satoshis)) { return `If defined, the "satoshis" property of ${newLocation} must be either a number or a little-endian, unsigned 64-bit integer as a hexadecimal-encoded string (16 characters).`; } return { ...(lockingBytecode === undefined ? {} : typeof lockingBytecode === 'string' ? { lockingBytecode } : { lockingBytecode: clonedLockingBytecode }), ...(satoshis === undefined ? {} : { satoshis }), }; }); const invalidOutputResults = outputResults.filter( (result): result is string => typeof result === 'string' ); if (invalidOutputResults.length > 0) { return invalidOutputResults.join(' '); } const clonedOutputs = outputResults as AuthenticationTemplateScenarioOutput[]; if (clonedOutputs.length === 0) { return `If defined, the "transaction.outputs" property of ${location} must be have at least one output.`; } return clonedOutputs; }; /** * Validate and clone an Authentication Template Scenario `transaction` object. * * @param transaction - the `transaction` object to validate and clone * @param location - the location of the error to specify in error messages, * e.g. `of output 2 in scenario "test"` */ // eslint-disable-next-line complexity export const parseAuthenticationTemplateScenarioTransaction = ( transaction: object, location: string ): string | AuthenticationTemplateScenario['transaction'] => { const { inputs, locktime, outputs, version } = transaction as { inputs: unknown; locktime: unknown; outputs: unknown; version: unknown; }; const maximumLocktime = 4294967295; if ( locktime !== undefined && !isRangedInteger(locktime, 0, maximumLocktime) ) { return `If defined, the "locktime" property of ${location} must be an integer between 0 and 4,294,967,295 (inclusive).`; } const maximumVersion = 4294967295; if (version !== undefined && !isRangedInteger(version, 0, maximumVersion)) { return `If defined, the "version" property of ${location} must be an integer between 0 and 4,294,967,295 (inclusive).`; } const clonedInputs = parseAuthenticationTemplateScenarioTransactionInputs( inputs, location ); if (typeof clonedInputs === 'string') { return clonedInputs; } const clonedOutputs = parseAuthenticationTemplateScenarioTransactionOutputs( outputs, location ); if (typeof clonedOutputs === 'string') { return clonedOutputs; } return { ...(locktime === undefined ? {} : { locktime }), ...(clonedInputs === undefined ? {} : { inputs: clonedInputs }), ...(clonedOutputs === undefined ? {} : { outputs: clonedOutputs }), ...(version === undefined ? {} : { version }), }; }; /** * Validate and clone an object of Authentication Template scenarios. * * @param scenarios - the scenarios object to validate and clone */ export const parseAuthenticationTemplateScenarios = (scenarios: object) => { const unknownScenarios = Object.entries(scenarios).map<{ id: string; scenario: unknown; // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment }>(([id, scenario]) => ({ id, scenario })); const nonObjectScenarios = unknownScenarios .filter(({ scenario }) => typeof scenario !== 'object' || scenario === null) .map(({ id }) => id); if (nonObjectScenarios.length > 0) { return `All authentication template scenarios must be objects, but the following scenarios are not objects: ${listIds( nonObjectScenarios )}.`; } const allScenarios = unknownScenarios as { id: string; scenario: object }[]; const scenarioResults: ( | { id: string; scenario: AuthenticationTemplateScenario } | string )[] = allScenarios // eslint-disable-next-line complexity .map(({ id, scenario }) => { const { data, description, extends: extendsProp, name, transaction, value, } = scenario as { data: unknown; description: unknown; extends: unknown; name: unknown; transaction: unknown; value: unknown; }; const location = `scenario "${id}"`; if (description !== undefined && typeof description !== 'string') { return `If defined, the "description" property of ${location} must be a string.`; } if (name !== undefined && typeof name !== 'string') { return `If defined, the "name" property of ${location} must be a string.`; } if (extendsProp !== undefined && typeof extendsProp !== 'string') { return `If defined, the "extends" property of ${location} must be a string.`; } if (!isValidSatoshisValue(value)) { return `If defined, the "value" property of ${location} must be either a number or a little-endian, unsigned 64-bit integer as a hexadecimal-encoded string (16 characters).`; } if (data !== undefined && !isObject(data)) { return `If defined, the "data" property of ${location} must be an object.`; } if (transaction !== undefined && !isObject(transaction)) { return `If defined, the "transaction" property of ${location} must be an object.`; } const dataResult = data === undefined ? undefined : parseAuthenticationTemplateScenarioData(data, location); if (typeof dataResult === 'string') { return dataResult; } const transactionResult = transaction === undefined ? undefined : parseAuthenticationTemplateScenarioTransaction( transaction, location ); if (typeof transactionResult === 'string') { return transactionResult; } const inputsUnderTest = transactionResult?.inputs?.filter( (input) => input.unlockingBytecode === undefined || input.unlockingBytecode === null ); if (inputsUnderTest !== undefined && inputsUnderTest.length !== 1) { return `If defined, the "transaction.inputs" array of ${location} must have exactly one input under test (an "unlockingBytecode" set to "null").`; } return { id, scenario: { ...(dataResult === undefined ? {} : { data: dataResult }), ...(description === undefined ? {} : { description }), ...(extendsProp === undefined ? {} : { extends: extendsProp }), ...(name === undefined ? {} : { name }), ...(transactionResult === undefined ? {} : { transaction: transactionResult }), ...(value === undefined ? {} : { value }), }, }; }); const invalidScenarioResults = scenarioResults.filter( (result): result is string => typeof result === 'string' ); if (invalidScenarioResults.length > 0) { return invalidScenarioResults.join(' '); } const validScenarioResults = scenarioResults as { id: string; scenario: AuthenticationTemplateScenario; }[]; const clonedScenarios = validScenarioResults.reduce<{ [id: string]: AuthenticationTemplateScenario; }>((all, result) => ({ ...all, [result.id]: result.scenario }), {}); const unknownExtends = Object.values(clonedScenarios).reduce<string[]>( (all, scenario) => scenario.extends !== undefined && (clonedScenarios[scenario.extends] as | AuthenticationTemplateScenario | undefined) === undefined ? [...all, scenario.extends] : all, [] ); if (unknownExtends.length > 0) { return `If defined, each scenario ID referenced by another scenario's "extends" property must exist. Unknown scenario IDs: ${listIds( unknownExtends )}.`; } return clonedScenarios; }; const isVersion0 = (maybeTemplate: object): maybeTemplate is { version: 0 } => (maybeTemplate as { version?: unknown }).version === 0; const schemaIsOptionalString = ( maybeTemplate: object ): maybeTemplate is { $schema?: string } => { const property = (maybeTemplate as { $schema?: unknown }).$schema; return property === undefined || typeof property === 'string'; }; const nameIsOptionalString = ( maybeTemplate: object ): maybeTemplate is { name?: string } => { const property = (maybeTemplate as { name?: unknown }).name; return property === undefined || typeof property === 'string'; }; const descriptionIsOptionalString = ( maybeTemplate: object ): maybeTemplate is { description?: string } => { const property = (maybeTemplate as { description?: unknown }).description; return property === undefined || typeof property === 'string'; }; const supportsOnlyValidVmIdentifiers = <Identifiers>( maybeTemplate: object, availableIdentifiers: Identifiers[] ): maybeTemplate is { supported: Identifiers[] } => { const { supported } = maybeTemplate as { supported?: unknown }; return ( Array.isArray(supported) && supported.every((value) => availableIdentifiers.includes(value)) ); }; /** * Parse and validate an authentication template, returning either an error * message as a string or a valid, safely-cloned `AuthenticationTemplate`. * * This method validates both the structure and the contents of a template: * - All properties and sub-properties are verified to be of the expected type. * - The ID of each entity, script, and scenario is confirmed to be unique. * - Script IDs referenced by entities and other scripts (via `unlocks`) are * confirmed to exist. * - The derivation paths of each HdKey are validated against each other. * * This method does not validate the BTL contents of scripts (by attempting * compilation, evaluate `AuthenticationTemplateScriptTest`s, or test scenario * generation. Unknown properties are ignored and excluded from the final * result. * * @param maybeTemplate - object to validate as an authentication template */ // eslint-disable-next-line complexity export const validateAuthenticationTemplate = ( maybeTemplate: unknown ): string | AuthenticationTemplate => { if (typeof maybeTemplate !== 'object' || maybeTemplate === null) { return 'A valid authentication template must be an object.'; } if (!isVersion0(maybeTemplate)) { return 'Only version 0 authentication templates are currently supported.'; } const vmIdentifiers = [ 'BCH_2022_11_SPEC', 'BCH_2022_11', 'BCH_2022_05_SPEC', 'BCH_2022_05', 'BCH_2021_11_SPEC', 'BCH_2021_11', 'BCH_2021_05_SPEC', 'BCH_2021_05', 'BCH_2020_11_SPEC', 'BCH_2020_11', 'BCH_2020_05', 'BCH_2019_11', 'BCH_2019_05', 'BSV_2018_11', 'BTC_2017_08', ] as AuthenticationVirtualMachineIdentifier[]; if ( !supportsOnlyValidVmIdentifiers(maybeTemplate, vmIdentifiers) || // eslint-disable-next-line @typescript-eslint/no-explicit-any maybeTemplate.supported.includes(undefined as any) ) { return `Version 0 authentication templates must include a "supported" list of authentication virtual machine versions. Available identifiers are: ${vmIdentifiers.join( ', ' )}.`; } if (!schemaIsOptionalString(maybeTemplate)) { return 'The "$schema" property of an authentication template must be a string.'; } if (!nameIsOptionalString(maybeTemplate)) { return 'The "name" property of an authentication template must be a string.'; } if (!descriptionIsOptionalString(maybeTemplate)) { return 'The "description" property of an authentication template must be a string.'; } const { entities, scenarios, scripts } = (maybeTemplate as unknown) as { entities: unknown; scenarios: unknown; scripts: unknown; }; if (typeof entities !== 'object' || entities === null) { return `The "entities" property of an authentication template must be an object.`; } if (typeof scripts !== 'object' || scripts === null) { return `The "scripts" property of an authentication template must be an object.`; } if ( scenarios !== undefined && (typeof scenarios !== 'object' || scenarios === null) ) { return `If defined, the "scenarios" property of an authentication template must be an object.`; } const parsedScripts = parseAuthenticationTemplateScripts(scripts); if (typeof parsedScripts === 'string') { return parsedScripts; } const clonedScripts = [ ...Object.entries(parsedScripts.locking), ...Object.entries(parsedScripts.other), ...Object.entries(parsedScripts.tested), ...Object.entries(parsedScripts.unlocking), ].reduce((all, [id, script]) => ({ ...all, [id]: script }), {}); const clonedEntities = parseAuthenticationTemplateEntities(entities); if (typeof clonedEntities === 'string') { return clonedEntities; } const clonedScenarios = scenarios === undefined ? undefined : parseAuthenticationTemplateScenarios(scenarios); if (typeof clonedScenarios === 'string') { return clonedScenarios; } const variableIds = Object.values(clonedEntities).reduce<string[]>( (all, entity) => entity.variables === undefined ? all : [...all, ...Object.keys(entity.variables)], [] ); const entityIds = Object.keys(clonedEntities); const scriptIds = Object.keys(clonedScripts); const scenarioIds = clonedScenarios === undefined ? [] : Object.keys(clonedScenarios); const usedIds = [...variableIds, ...entityIds, ...scriptIds, ...scenarioIds]; const builtInIds = [ BuiltInVariables.currentBlockHeight, BuiltInVariables.currentBlockTime, BuiltInVariables.signingSerialization, ]; const usedBuiltInIds = builtInIds.filter((builtInIdentifier) => usedIds.includes(builtInIdentifier) ); if (usedBuiltInIds.length > 0) { return `Built-in identifiers may not be re-used by any entity, variable, script, or scenario. The following built-in identifiers are re-used: ${listIds( usedBuiltInIds )}.`; } const idUsageCount = usedIds.reduce<{ [id: string]: number }>( (count, id) => ({ ...count, [id]: ((count[id] as number | undefined) ?? 0) + 1, }), {} ); const duplicateIds = Object.entries(idUsageCount) .filter(([, count]) => count > 1) .map(([id]) => id); if (duplicateIds.length > 0) { return `The ID of each entity, variable, script, and scenario in an authentication template must be unique. The following IDs are re-used: ${listIds( duplicateIds )}.`; } const unknownScriptIds = Object.values(clonedEntities) .reduce<string[]>( (all, entity) => entity.scripts === undefined ? all : [...all, ...entity.scripts], [] ) .reduce<string[]>( (unique, id) => scriptIds.includes(id) || unique.includes(id) ? unique : [...unique, id], [] ); if (unknownScriptIds.length > 0) { return `Only known scripts may be assigned to entities. The following script IDs are not provided in this template: ${listIds( unknownScriptIds )}.`; } const unknownScenarioIds = [ ...Object.values(parsedScripts.unlocking).reduce<string[]>( (all, script) => [ ...all, ...(script.estimate === undefined ? [] : [script.estimate]), ...(script.fails === undefined ? [] : script.fails), ...(script.invalid === undefined ? [] : script.invalid), ...(script.passes === undefined ? [] : script.passes), ], [] ), ...Object.values(parsedScripts.tested).reduce<string[]>( (all, script) => [ ...all, ...script.tests.reduce<string[]>( (fromScript, test) => [ ...fromScript, ...(test.fails === undefined ? [] : test.fails), ...(test.invalid === undefined ? [] : test.invalid), ...(test.passes === undefined ? [] : test.passes), ], [] ), ], [] ), ].reduce<string[]>( (unique, id) => scenarioIds.includes(id) || unique.includes(id) ? unique : [...unique, id], [] ); if (unknownScenarioIds.length > 0) { return `Only known scenarios may be referenced by scripts. The following scenario IDs are not provided in this template: ${listIds( unknownScenarioIds )}.`; } const entityIdsReferencedByScenarioData = ( data: AuthenticationTemplateScenarioData | undefined ) => { const hdPublicKeyEntityIds = data?.hdKeys?.hdPublicKeys === undefined ? [] : Object.keys(data.hdKeys.hdPublicKeys); const hdPrivateKeyEntityIds = data?.hdKeys?.hdPrivateKeys === undefined ? [] : Object.keys(data.hdKeys.hdPrivateKeys); return [...hdPublicKeyEntityIds, ...hdPrivateKeyEntityIds]; }; const unknownEntityIds = clonedScenarios === undefined ? [] : Object.values(clonedScenarios) .reduce<string[]>( (all, scenario) => [ ...all, ...entityIdsReferencedByScenarioData(scenario.data), ...(scenario.transaction?.outputs ?? []).reduce<string[]>( (fromOverrides, output) => isObject(output.lockingBytecode) ? [ ...fromOverrides, ...entityIdsReferencedByScenarioData( output.lockingBytecode.overrides ), ] : fromOverrides, [] ), ], [] ) .reduce<string[]>( (unique, id) => entityIds.includes(id) || unique.includes(id) ? unique : [...unique, id], [] ); if (unknownEntityIds.length > 0) { return `Only known entities may be referenced by hdKeys properties within scenarios. The following entity IDs are not provided in this template: ${listIds( unknownEntityIds )}.`; } return { ...(maybeTemplate.$schema === undefined ? {} : { $schema: maybeTemplate.$schema }), ...(maybeTemplate.description === undefined ? {} : { description: maybeTemplate.description }), entities: clonedEntities, ...(maybeTemplate.name === undefined ? {} : { name: maybeTemplate.name }), scenarios: clonedScenarios, scripts: clonedScripts, supported: maybeTemplate.supported, version: maybeTemplate.version, } as AuthenticationTemplate; };
the_stack
import * as React from 'react' import { SafeAreaView, Dimensions, Alert, ActivityIndicator } from 'react-native' import { RTCPeerConnection, RTCIceCandidate, RTCSessionDescription, RTCView, getUserMedia, MediaStreamTrack, SourceInfo, MediaStream, } from 'react-native-webrtc' // import InCallManager from 'react-native-incall-manager'; import * as Apollo from 'react-apollo-hooks' import { graphql, GraphqlQueryControls } from 'react-apollo' import styled from 'styled-components/native' import Theme from '../../config/Theme' import idx from 'idx' import { NavigationInjectedProps } from 'react-navigation' import gql from 'graphql-tag' import { CallScreenQuery_me } from './__generated__/CallScreenQuery' import { CALL_TYPES, gravatarURL } from '../../config/utils' import { SendRTCMessageVariables } from './__generated__/SendRTCMessage' import { StyledComponentClass } from 'styled-components' import { iceServers } from '../../config/config' const { width, height } = Dimensions.get('window') const HEIGHT_SMALL_VIDEO = Math.round(height * 0.2) const WIDTH_SMALL_VIDEO = (HEIGHT_SMALL_VIDEO * 9) / 16 const PeerVideoPlaceHolder = styled.View` position: absolute; background-color: ${({ theme }) => theme.colors.primary}; width: ${width}; height: ${height}; left: 0; right: 0; top: 0; bottom: 0; align-items: center; justify-content: center; ` const LocalVideoPlaceHolder = styled.View` position: absolute; background-color: black; width: ${WIDTH_SMALL_VIDEO}; height: ${HEIGHT_SMALL_VIDEO}; right: 20; top: 50; border-radius: 5; z-index: 1000; ` const PeerVideo = styled(RTCView)` position: absolute; background-color: black; width: ${width}; height: ${height}; left: 0; right: 0; top: 0; bottom: 0; align-items: center; justify-content: center; ` const LocalVideo: StyledComponentClass<any, any> = styled(RTCView).attrs({ mirror: true, })` position: absolute; background-color: black; width: ${WIDTH_SMALL_VIDEO}; height: ${HEIGHT_SMALL_VIDEO}; right: 20; top: 40; border-radius: 5; z-index: 1000; ` const Wrapper = styled(SafeAreaView)` flex: 1; background-color: black; ` const ButtonsContainer = styled.View` position: absolute; left: 30; right: 30; bottom: 30; width: ${width - 60}; flex-direction: row; align-items: center; justify-content: space-between; ` const ActionButtons = styled.TouchableOpacity` width: 60; height: 60; border-radius: ${60 / 2}; background-color: white; align-items: center; justify-content: center; ` const CallIcon = styled.Image.attrs({ source: props => props.theme.images.phone, })` width: 30; height: 11; ` const Icon = styled.Image` width: 24; height: 24; tint-color: black; ` const HangupButton = styled.TouchableOpacity` width: 70; height: 70; border-radius: ${70 / 2}; background-color: red; align-items: center; justify-content: center; ` const ButtonWrapper = styled.TouchableOpacity` padding: 18px 40px; align-items: center; justify-content: center; border-radius: 100px; margin: 10px 20px; background-color: ${({ theme }) => theme.colors.accent}; ` const ButtonText = styled.Text` color: white; font-size: 20px; font-family: 'Rubik'; ` const Logo = styled.Image.attrs({ source: ({ theme }) => theme.images.logo, })` width: 400; height: 180; ` const ChatifyText = styled.Text` font-family: 'Rubik'; color: white; font-size: 20; margin-top: -20; margin-bottom: 20; ` const AlignAtCenter = styled.View` flex: 1; background-color: ${({ theme }) => theme.colors.primary}; align-items: center; justify-content: center; ` const UserProfile = styled.Image` width: 100; height: 100; border-radius: 10; ` const WrapperImageAndName = styled.View` width: ${width - 40}; align-items: center; justify-content: center; ` const ChatifyState = styled.Text` font-family: 'Rubik'; color: white; font-size: 20; text-align: center; margin-top: 20; width: ${width - 80}; ` const ChatifyUser = styled.Text` font-family: 'Rubik'; color: white; font-size: 16; text-align: center; margin-top: 10; width: ${width - 80}; margin-bottom: 20; ` interface Params { calling: boolean sdp: string chatId: string callUser: string callUserEmail: string callID: string } interface Data extends GraphqlQueryControls { me: CallScreenQuery_me } interface Props extends NavigationInjectedProps<Params> { data: Data } const mutationDoc = gql` mutation SendRTCMessage($id: String!, $callID: String!, $message: String!, $type: String!) { sendWebRTCMessage(_id: $id, callID: $callID, message: $message, type: $type) { message } } ` const CallSub = gql` subscription CallScreenSub($id: String!) { webRTCMessage(yourUser: $id) { callID type message chat { _id } } } ` const CallScreen = (props: Props) => { const { loading, error } = props.data const [localVideo, setLocalVideo] = React.useState(true) const [localMic, setLocalMic] = React.useState(true) const [peerVideo, setPeerVideo] = React.useState(true) const [stream, setStream] = React.useState<MediaStream | null>(null) const [remoteStream, setRemoteStream] = React.useState<any>(null) const [callState, setCallState] = React.useState<'Ringing' | 'Connecting' | 'Connected'>( 'Ringing', ) const mutation = Apollo.useMutation(mutationDoc) const pc = new RTCPeerConnection({ iceServers, }) const sendSDP = async (sdp: object, type: string) => { const parsedSDP = JSON.stringify(sdp) await mutation({ variables: { id: idx(props.navigation.state.params, _ => _.chatId), callID: idx(props.navigation.state.params, _ => _.callID), message: parsedSDP, type, } as SendRTCMessageVariables, }) .then(() => console.log('MANDOU SDP')) .catch(() => { Alert.alert('Error', 'An Unexpected Error Occurred') }) } const hangupCall = async () => { await mutation({ variables: { id: idx(props.navigation.state.params, _ => _.chatId), callID: idx(props.navigation.state.params, _ => _.callID), message: 'HANGUP', type: CALL_TYPES.HANGUP, } as SendRTCMessageVariables, }) .then(() => { pc.close() return props.navigation.goBack() }) .catch(() => { Alert.alert('Error', 'An Unexpected Error Occurred') }) } const sendCandidate = async (candidate: object) => { const parsedCandidate = JSON.stringify(candidate) await mutation({ variables: { id: idx(props.navigation.state.params, _ => _.chatId), callID: idx(props.navigation.state.params, _ => _.callID), message: parsedCandidate, type: CALL_TYPES.ICE_CANDIDATE, } as SendRTCMessageVariables, }).catch(() => { Alert.alert('Error', 'An Unexpected Error Occurred') }) } React.useEffect(() => { if (!loading && !error) { MediaStreamTrack.getSources((sourceInfos: SourceInfo[]) => { console.log('MediaStreamTrack.getSources', sourceInfos) let videoSourceId for (let i = 0; i < sourceInfos.length; i++) { const sourceInfo = sourceInfos[i] if (sourceInfo.kind === 'video' && sourceInfo.facing === 'front') { videoSourceId = sourceInfo.id } } getUserMedia( { audio: true, video: { mandatory: { minWidth: 1280, minHeight: 720, minFrameRate: 30, }, facingMode: 'user', optional: videoSourceId ? [{ sourceId: videoSourceId }] : [], }, }, (receivedStream: any) => { setStream(receivedStream) pc.addStream(receivedStream) }, e => { console.log('Oops, we getting error', e) }, ) setTimeout(() => { const sdp = idx(props.navigation.state.params, _ => _.sdp) const calling = idx(props.navigation.state.params, _ => _.calling) // Starts the WebRTC Logic if (calling === true) { pc.createOffer( desc => { pc.setLocalDescription( desc, () => { sendSDP(desc, CALL_TYPES.DIAL_SDP) }, e => console.log(e), ) }, e => console.log(e), ) } else { // Receives the sdp and parse const remoteDescription = new RTCSessionDescription(JSON.parse(sdp || '')) pc.setRemoteDescription( remoteDescription, () => { pc.createAnswer( answer => { pc.setLocalDescription( answer, () => { setCallState('Connecting') sendSDP(answer, CALL_TYPES.ANSWER_SDP) }, e => console.log(e), ) }, e => console.log(e), ) }, e => console.log(e), ) } props.data.subscribeToMore({ document: CallSub, onError: e => console.log('Subscription Error: ', e), variables: { id: props.data.me._id, }, updateQuery: (_, { subscriptionData }) => { const { type, message } = subscriptionData.data.webRTCMessage console.log(subscriptionData.data.webRTCMessage) // Other peer answered if (type === CALL_TYPES.ANSWER_SDP) { if (props.navigation.getParam('calling')) setCallState('Connecting') const answerSDP = new RTCSessionDescription(JSON.parse(message)) return pc.setRemoteDescription(answerSDP, () => { setCallState('Connecting') }) } // Other peer sended a ice candidate if (type === CALL_TYPES.ICE_CANDIDATE) { const iceCandidate = new RTCIceCandidate(JSON.parse(message)) return pc.addIceCandidate(iceCandidate) } // Other peer is Busy if (type === CALL_TYPES.BUSY) { pc.close() Alert.alert('Busy', 'The other peer is on a call right now') return props.navigation.goBack() } // Other peer rejected the call or hangup if (type === CALL_TYPES.REJECT || type === CALL_TYPES.HANGUP) { pc.close() return props.navigation.goBack() } // Other peer enabled the camera if (type === CALL_TYPES.ENABLE_CAMERA) { return setPeerVideo(true) } // Other peer disabled the camera if (type === CALL_TYPES.DISABLE_CAMERA) { return setPeerVideo(false) } }, }) pc.onicecandidate = (event: any) => { // Send Candidate to the other peer if (event.candidate) { console.log('SEND CANDIDATE') sendCandidate(event.candidate) } } pc.oniceconnectionstatechange = () => { console.log('Ice Connection State', pc.iceConnectionState) } }, 2000) }) } }, [loading]) const muteMicrophone = () => { console.log(pc) console.log(pc.getLocalStreams()) if (!stream) { return } stream.getAudioTracks().forEach(track => { console.log('Track', track) setLocalMic(!localMic) track.enabled = !localMic }) } const sendVideoState = async (videoState: boolean) => { await mutation({ variables: { id: idx(props.navigation.state.params, _ => _.chatId), callID: idx(props.navigation.state.params, _ => _.callID), message: 'Change Camera State', type: videoState ? CALL_TYPES.ENABLE_CAMERA : CALL_TYPES.DISABLE_CAMERA, } as SendRTCMessageVariables, }) .then(() => console.log('MANDOU SDP')) .catch(() => { Alert.alert('Error', 'An Unexpected Error Occurred') }) } const muteVideo = () => { console.log(pc) if (!stream) { return } stream.getVideoTracks().forEach(track => { setLocalVideo(!localVideo) sendVideoState(!localVideo) track.enabled = !localVideo }) } pc.onaddstream = (event: any) => { setCallState('Connected') setRemoteStream(event.stream) } if (loading) { return ( <AlignAtCenter> <ActivityIndicator animating color='white' /> </AlignAtCenter> ) } if (error) { return ( <AlignAtCenter> <Logo /> <ChatifyText>No Connection 😢</ChatifyText> <ButtonWrapper onPress={() => props.data.refetch()}> <ButtonText>Retry</ButtonText> </ButtonWrapper> </AlignAtCenter> ) } return ( <Wrapper> {!remoteStream || !peerVideo ? ( <PeerVideoPlaceHolder> <WrapperImageAndName> <UserProfile source={{ uri: gravatarURL(props.navigation.getParam('callUserEmail')) }} /> <ChatifyState>{peerVideo ? callState : `Video Disabled`}</ChatifyState> <ChatifyUser>{props.navigation.getParam('callUser')}</ChatifyUser> </WrapperImageAndName> </PeerVideoPlaceHolder> ) : ( <PeerVideo mirror streamURL={remoteStream.toURL()} /> )} {!stream || !localVideo ? ( <LocalVideoPlaceHolder /> ) : ( <LocalVideo mirror streamURL={stream.toURL()} /> )} <ButtonsContainer> <ActionButtons onPress={() => muteVideo()}> <Icon source={localVideo ? Theme.images.video : Theme.images.videoOff} /> </ActionButtons> <HangupButton onPress={() => hangupCall()}> <CallIcon /> </HangupButton> <ActionButtons onPress={() => muteMicrophone()}> <Icon source={localMic ? Theme.images.mic : Theme.images.micOff} /> </ActionButtons> </ButtonsContainer> </Wrapper> ) } const query = gql` query CallScreenQuery { me { _id } } ` export default graphql<Props>(query)(CallScreen)
the_stack
import * as pako from 'pako'; import crc32 from '../helpers/crc32'; import decodeIDAT from './decode-idat'; import Metadata from '../helpers/metadata'; import PNG_SIGNATURE from '../helpers/signature'; import { GAMMA_DIVISION } from '../helpers/gamma'; import { COLOR_TYPES } from '../helpers/color-types'; import rescaleSample from '../helpers/rescale-sample'; import { decode as decodeUTF8 } from '../helpers/utf8'; import { concatUInt8Array } from '../helpers/typed-array'; import { CHROMATICITIES_DIVISION } from '../helpers/chromaticities'; export default function decode(arrayBuffer: ArrayBuffer) { const typedArray = new Uint8Array(arrayBuffer); let idatUint8Array = new Uint8Array(); const metadata: Metadata = { width: 0, height: 0, depth: 0, colorType: 0, compression: 0, interlace: 0, filter: 0, data: [], }; // Helpers let index = 0; function readUInt32BE() { return ( (typedArray[index++] << 24) | (typedArray[index++] << 16) | (typedArray[index++] << 8) | typedArray[index++] ); } function readUInt16BE() { return (typedArray[index++] << 8) | typedArray[index++]; } function readUInt8() { return typedArray[index++]; } function readBytesBeforeNull() { const results = []; let byte: number = 0; while ((byte = typedArray[index++]) !== 0) { results.push(byte); } return new Uint8Array(results); } function readStringBeforeNull(maxLength: number) { const maxIndex = index + maxLength; let result = ''; while (index < maxIndex) { const byte = readUInt8(); if (byte === 0) { break; } result += String.fromCharCode(byte); } return result; } function readStringBeforeEnd(endIndex: number) { let result = ''; while (index < endIndex) { const byte = readUInt8(); result += String.fromCharCode(byte); } return result; } function readCompressedData(endIndex: number) { const compressedData = typedArray.slice(index, endIndex); index = endIndex; return pako.inflate(compressedData); } function readChunkType() { let name = ''; for (const end = index + 4; index < end; index++) { name += String.fromCharCode(typedArray[index]); } return name; } // Signature for (; index < PNG_SIGNATURE.length; index++) { if (typedArray[index] !== PNG_SIGNATURE[index]) { throw new Error( `Invalid file signature, at position ${index}: ${typedArray[index]} !== ${PNG_SIGNATURE[index]}`, ); } } // Chunks const chunkHandlers: { [key: string]: (length: number) => void; } = { IHDR: parseIHDR, PLTE: parsePLTE, IDAT: parseIDAT, IEND: parseIEND, tRNS: parseTRNS, cHRM: parseCHRM, gAMA: parseGAMA, iCCP: parseICCP, sBIT: parseSBIT, sRGB: parseSRGB, tEXt: parseTEXT, zTXt: parseZTXT, iTXt: parseITXT, bKGD: parseBKGD, hIST: parseHIST, pHYs: parsePHYS, sPLT: parseSPLT, tIME: parseTIME, }; function parseIHDR() { metadata.width = readUInt32BE(); metadata.height = readUInt32BE(); metadata.depth = readUInt8(); const colorType = readUInt8(); // bits: 1 palette, 2 color, 4 alpha if (!(colorType in COLOR_TYPES)) { throw new Error('Unsupported color type: ' + colorType); } metadata.colorType = colorType; metadata.compression = readUInt8(); metadata.filter = readUInt8(); metadata.interlace = readUInt8(); } function parsePLTE(length: number) { const palette: [number, number, number, number][] = []; for (let i = 0; i < length; i += 3) { palette.push([ typedArray[index++], typedArray[index++], typedArray[index++], 0xff, // default to opaque ]); } metadata.palette = palette; } function parseIDAT(length: number) { // save data, decode later idatUint8Array = concatUInt8Array( idatUint8Array, typedArray.slice(index, index + length), ); index += length; } function parseIEND(length: number) { index += length; } function parseTRNS(length: number) { if (metadata.colorType === COLOR_TYPES.GRAYSCALE) { const color = rescaleSample( (typedArray[index++] << 8) | typedArray[index++], metadata.depth, 8, ); metadata.transparent = [color, color, color, 0xff]; } else if (metadata.colorType === COLOR_TYPES.TRUE_COLOR) { metadata.transparent = [ rescaleSample( (typedArray[index++] << 8) | typedArray[index++], metadata.depth, 8, ), rescaleSample( (typedArray[index++] << 8) | typedArray[index++], metadata.depth, 8, ), rescaleSample( (typedArray[index++] << 8) | typedArray[index++], metadata.depth, 8, ), 0xff, ]; } else if (metadata.colorType === COLOR_TYPES.PALETTE) { if (!metadata.palette) { throw new Error('Missing chunk: PLTE'); } for (let i = 0; i < length; i++) { metadata.palette[i][3] = typedArray[index++]; } } else { // throw new Error('Prohibited tRNS for colorType ' + metadata.colorType); } } function parseCHRM() { metadata.chromaticities = { white: { x: readUInt32BE() / CHROMATICITIES_DIVISION, y: readUInt32BE() / CHROMATICITIES_DIVISION, }, red: { x: readUInt32BE() / CHROMATICITIES_DIVISION, y: readUInt32BE() / CHROMATICITIES_DIVISION, }, green: { x: readUInt32BE() / CHROMATICITIES_DIVISION, y: readUInt32BE() / CHROMATICITIES_DIVISION, }, blue: { x: readUInt32BE() / CHROMATICITIES_DIVISION, y: readUInt32BE() / CHROMATICITIES_DIVISION, }, }; } function parseGAMA() { metadata.gamma = readUInt32BE() / GAMMA_DIVISION; } function parseICCP(length: number) { const endIndex = index + length; const profileName = readStringBeforeNull(80); const compressionMethod = readUInt8(); if (compressionMethod !== 0) { // throw new Error( // 'Unsupported iCCP compression method: ' + compressionMethod, // ); } const profile = readCompressedData(endIndex); metadata.icc = { name: profileName, profile: Array.from(profile), }; } function parseSBIT() { if (metadata.colorType === COLOR_TYPES.GRAYSCALE) { const sBit = readUInt8(); metadata.significantBits = [sBit, sBit, sBit, metadata.depth]; } else if ( metadata.colorType === COLOR_TYPES.TRUE_COLOR || metadata.colorType === COLOR_TYPES.PALETTE ) { metadata.significantBits = [ readUInt8(), readUInt8(), readUInt8(), metadata.depth, ]; } else if (metadata.colorType === COLOR_TYPES.GRAYSCALE_WITH_ALPHA) { const sBit = readUInt8(); metadata.significantBits = [sBit, sBit, sBit, readUInt8()]; } else if (metadata.colorType === COLOR_TYPES.TRUE_COLOR_WITH_ALPHA) { metadata.significantBits = [ readUInt8(), readUInt8(), readUInt8(), readUInt8(), ]; } } function parseSRGB() { metadata.sRGB = readUInt8(); } function parseTEXT(length: number) { const endIndex = index + length; const keyword = readStringBeforeNull(80); const value = readStringBeforeEnd(endIndex); if (!metadata.text) { metadata.text = {}; } metadata.text[keyword] = value; } function parseZTXT(length: number) { const endIndex = index + length; const keyword = readStringBeforeNull(80); const compressionMethod = readUInt8(); if (compressionMethod !== 0) { // throw new Error( // 'Unsupported zTXt compression method: ' + compressionMethod, // ); } const data = readCompressedData(endIndex); let value = ''; for (let i = 0; i < data.length; i++) { value += String.fromCharCode(data[i]); } if (!metadata.compressedText) { metadata.compressedText = {}; } metadata.compressedText[keyword] = value; } function parseITXT(length: number) { const endIndex = index + length; const keyword = readStringBeforeNull(80); const compressionFlag = readUInt8(); const compressionMethod = readUInt8(); const languageTag = readStringBeforeNull(Infinity); const translatedKeyword = decodeUTF8(readBytesBeforeNull()); let text = ''; if (compressionFlag === 0) { text = decodeUTF8(typedArray.slice(index, endIndex)); index = endIndex; } else { if (compressionMethod !== 0) { // throw new Error( // 'Unsupported iTXt compression method: ' + compressionMethod, // ); } const data = readCompressedData(endIndex); text = decodeUTF8(data); } if (!metadata.internationalText) { metadata.internationalText = {}; } metadata.internationalText[keyword] = { languageTag, translatedKeyword, text, }; } function parseBKGD() { if ((metadata.colorType & 3) === COLOR_TYPES.GRAYSCALE) { const color = rescaleSample( (typedArray[index++] << 8) | typedArray[index++], metadata.depth, 8, ); metadata.background = [color, color, color, 0xff]; } else if ((metadata.colorType & 3) === COLOR_TYPES.TRUE_COLOR) { metadata.background = [ rescaleSample( (typedArray[index++] << 8) | typedArray[index++], metadata.depth, 8, ), rescaleSample( (typedArray[index++] << 8) | typedArray[index++], metadata.depth, 8, ), rescaleSample( (typedArray[index++] << 8) | typedArray[index++], metadata.depth, 8, ), 0xff, ]; } else if (metadata.colorType === COLOR_TYPES.PALETTE) { if (!metadata.palette) { throw new Error('Missing chunk: PLTE'); } metadata.background = metadata.palette[typedArray[index++]]; } } function parseHIST(length: number) { const endIndex = index + length; const histogram = []; while (index < endIndex) { histogram.push(readUInt16BE()); } metadata.histogram = histogram; } function parsePHYS() { const pixelPerUnitX = readUInt32BE(); const pixelPerUnitY = readUInt32BE(); const unit = readUInt8(); metadata.physicalDimensions = { pixelPerUnitX, pixelPerUnitY, unit, }; } function parseSPLT(length: number) { const endIndex = index + length; const name = readStringBeforeNull(80); const depth = readUInt8(); const palette: [number, number, number, number, number][] = []; if (depth === 8) { while (index < endIndex) { palette.push([ readUInt8(), readUInt8(), readUInt8(), readUInt8(), readUInt16BE(), ]); } } else if (depth === 16) { while (index < endIndex) { palette.push([ readUInt16BE(), readUInt16BE(), readUInt16BE(), readUInt16BE(), readUInt16BE(), ]); } } else { // throw new Error('Unsupported sPLT depth: ' + depth); } metadata.suggestedPalette = { name, depth, palette: palette, }; } function parseTIME() { const year = readUInt16BE(); const month = readUInt8(); const day = readUInt8(); const hour = readUInt8(); const minute = readUInt8(); const second = readUInt8(); metadata.lastModificationTime = Date.UTC( year, month - 1, day, hour, minute, second, ); } function parseChunkBegin() { const startIndex = index; const length = readUInt32BE(); const type = readChunkType(); if (chunkHandlers[type]) { chunkHandlers[type](length); } else { const ancillary = Boolean(type.charCodeAt(0) & 0x20); // or critical if (!ancillary) { // throw new Error('Unsupported critical chunk type: ' + type); } // Skip chunk index += length; } parseChunkEnd(startIndex, length); } function parseChunkEnd(startIndex: number, length: number) { const fileCrc32 = readUInt32BE(); const calculatedCrc32 = crc32( typedArray.slice(startIndex + 4, startIndex + 8 + length), ); if (fileCrc32 !== calculatedCrc32) { throw new Error( 'Crc32 error: calculated ' + calculatedCrc32 + ', expected ' + fileCrc32, ); } if (index < typedArray.length) { parseChunkBegin(); } } parseChunkBegin(); // Decode all IDAT metadata.data = decodeIDAT( idatUint8Array, metadata.interlace, metadata.colorType, metadata.width, metadata.height, metadata.depth, metadata.palette, metadata.transparent, ); return metadata; }
the_stack
import type { IBooleanValueSource, ColumnsForSetOf, IIfValueSource, IValueSource, InputTypeOfColumnAllowing } from "./values" import type { ITableOrView, ITableOrViewOf, NoTableOrViewRequired, OLD, OuterJoinSource } from "../utils/ITableOrView" import type { AnyDB, MariaDB, MySql, NoopDB, Oracle, PostgreSql, Sqlite, SqlServer, TypeSafeDB } from "../databases" import type { int } from "ts-extended-types" import type { database, tableOrView, tableOrViewRef, valueType } from "../utils/symbols" import type { RawFragment } from "../utils/RawFragment" import { OuterJoinTableOrView } from "../utils/tableOrViewUtils" export interface UpdateCustomization<DB extends AnyDB> { afterUpdateKeyword?: RawFragment<DB> afterQuery?: RawFragment<DB> } export interface UpdateExpressionOf<DB extends AnyDB> { [database]: DB } export interface UpdateExpressionBase<TABLE extends ITableOrView<any>> extends UpdateExpressionOf<TABLE[typeof database]> { [tableOrView]: TABLE } export interface ExecutableUpdate<TABLE extends ITableOrView<any>> extends UpdateExpressionBase<TABLE> { executeUpdate(this: UpdateExpressionOf<TypeSafeDB>, min?: number, max?: number): Promise<int> executeUpdate(min?: number, max?: number): Promise<number> query(): string params(): any[] } export interface CustomizableExecutableUpdate<TABLE extends ITableOrView<any>> extends ExecutableUpdate<TABLE> { customizeQuery(customization: UpdateCustomization<TABLE[typeof database]>): ExecutableUpdate<TABLE> } export interface ExecutableUpdateExpression<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends ReturnableExecutableUpdate<TABLE, USING> { set(columns: UpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> setIfValue(columns: OptionalUpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> setIfSet(columns: UpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> setIfSetIfValue(columns: OptionalUpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> setIfNotSet(columns: UpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> setIfNotSetIfValue(columns: OptionalUpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> ignoreIfSet(...columns: ColumnsForSetOf<TABLE>[]): ExecutableUpdateExpression<TABLE, USING> setIfHasValue(columns: UpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> setIfHasValueIfValue(columns: OptionalUpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> setIfHasNoValue(columns: UpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> setIfHasNoValueIfValue(columns: OptionalUpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> ignoreIfHasValue(...columns: ColumnsForSetOf<TABLE>[]): ExecutableUpdateExpression<TABLE, USING> ignoreIfHasNoValue(...columns: ColumnsForSetOf<TABLE>[]): ExecutableUpdateExpression<TABLE, USING> ignoreAnySetWithNoValue(): ExecutableUpdateExpression<TABLE, USING> dynamicWhere() : DynamicExecutableUpdateExpression<TABLE, USING> where(condition: IIfValueSource<TABLE[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicExecutableUpdateExpression<TABLE, USING> where(condition: IBooleanValueSource<TABLE[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicExecutableUpdateExpression<TABLE, USING> } export interface NotExecutableUpdateExpression<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateExpressionBase<TABLE> { set(columns: UpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> setIfValue(columns: OptionalUpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> setIfSet(columns: UpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> setIfSetIfValue(columns: OptionalUpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> setIfNotSet(columns: UpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> setIfNotSetIfValue(columns: OptionalUpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> ignoreIfSet(...columns: ColumnsForSetOf<TABLE>[]): NotExecutableUpdateExpression<TABLE, USING> setIfHasValue(columns: UpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> setIfHasValueIfValue(columns: OptionalUpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> setIfHasNoValue(columns: UpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> setIfHasNoValueIfValue(columns: OptionalUpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> ignoreIfHasValue(...columns: ColumnsForSetOf<TABLE>[]): NotExecutableUpdateExpression<TABLE, USING> ignoreIfHasNoValue(...columns: ColumnsForSetOf<TABLE>[]): NotExecutableUpdateExpression<TABLE, USING> ignoreAnySetWithNoValue(): NotExecutableUpdateExpression<TABLE, USING> dynamicWhere() : DynamicExecutableUpdateExpression<TABLE, USING> where(condition: IIfValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicExecutableUpdateExpression<TABLE, USING> where(condition: IBooleanValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicExecutableUpdateExpression<TABLE, USING> } export interface DynamicExecutableUpdateExpression<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends ReturnableExecutableUpdate<TABLE, USING> { and(condition: IIfValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicExecutableUpdateExpression<TABLE, USING> and(condition: IBooleanValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicExecutableUpdateExpression<TABLE, USING> or(condition: IIfValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicExecutableUpdateExpression<TABLE, USING> or(condition: IBooleanValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicExecutableUpdateExpression<TABLE, USING> } export interface UpdateSetExpression<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateExpressionBase<TABLE> { dynamicSet(): NotExecutableUpdateExpression<TABLE, USING> set(columns: UpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> setIfValue(columns: OptionalUpdateSets<TABLE, USING>): NotExecutableUpdateExpression<TABLE, USING> } export interface UpdateExpression<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetExpression<TABLE, USING> { from: FromFnType<TABLE, USING> join: OnExpressionFnType<TABLE, USING> innerJoin: OnExpressionFnType<TABLE, USING> leftJoin: OuterJoinOnExpressionFnType<TABLE, USING> leftOuterJoin: OuterJoinOnExpressionFnType<TABLE, USING> } export interface UpdateSetExpressionAllowingNoWhere<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateExpressionBase<TABLE> { dynamicSet(): ExecutableUpdateExpression<TABLE, USING> set(columns: UpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> setIfValue(columns: OptionalUpdateSets<TABLE, USING>): ExecutableUpdateExpression<TABLE, USING> } export interface UpdateExpressionAllowingNoWhere<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetExpressionAllowingNoWhere<TABLE, USING> { from: FromFnTypeAllowingNoWhere<TABLE, USING> join: OnExpressionFnTypeAllowingNoWhere<TABLE, USING> innerJoin: OnExpressionFnTypeAllowingNoWhere<TABLE, USING> leftJoin: OuterJoinOnExpressionFnTypeAllowingNoWhere<TABLE, USING> leftOuterJoin: OuterJoinOnExpressionFnTypeAllowingNoWhere<TABLE, USING> } export type UpdateSets<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = { [P in ColumnsForSetOf<TABLE>]?: InputTypeOfColumnAllowing<TABLE, P, USING> } export type OptionalUpdateSets<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = { [P in ColumnsForSetOf<TABLE>]?: InputTypeOfColumnAllowing<TABLE, P, USING> | null | undefined } export interface UpdateSetJoinExpression<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetExpression<TABLE, USING> { join<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2): OnExpression<TABLE, USING | TABLE_OR_VIEW2> innerJoin<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2): OnExpression<TABLE, USING | TABLE_OR_VIEW2> leftJoin<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>, ALIAS>(source: OuterJoinSource<TABLE_OR_VIEW2, ALIAS>): OnExpression<TABLE, USING | OuterJoinTableOrView<TABLE_OR_VIEW2, ALIAS>> leftOuterJoin<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>, ALIAS>(source: OuterJoinSource<TABLE_OR_VIEW2, ALIAS>): OnExpression<TABLE, USING | OuterJoinTableOrView<TABLE_OR_VIEW2, ALIAS>> } export interface DynamicOnExpression<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetJoinExpression<TABLE, USING> { and(condition: IIfValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpression<TABLE, USING> and(condition: IBooleanValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpression<TABLE, USING> or(condition: IIfValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpression<TABLE, USING> or(condition: IBooleanValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpression<TABLE, USING> } export interface OnExpression<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetJoinExpression<TABLE, USING> { dynamicOn(): DynamicOnExpression<TABLE, USING> on(condition: IIfValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpression<TABLE, USING> on(condition: IBooleanValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpression<TABLE, USING> } export interface UpdateExpressionWithoutJoin<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetExpression<TABLE, USING> { from<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2): UpdateExpressionWithoutJoin<TABLE, USING | TABLE_OR_VIEW2> } export interface UpdateFromExpression<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetJoinExpression<TABLE, USING> { from<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2): UpdateExpressionWithoutJoin<TABLE, USING | TABLE_OR_VIEW2> } type FromFnType<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = TABLE[typeof database] extends (NoopDB | PostgreSql | SqlServer | Sqlite | MariaDB | MySql) ? <TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2) => UpdateFromExpression<TABLE, USING | TABLE_OR_VIEW2> : never type OnExpressionFnType<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = TABLE[typeof database] extends (NoopDB | MariaDB | MySql) ? <TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2) => OnExpression<TABLE, USING | TABLE_OR_VIEW2> : never type OuterJoinOnExpressionFnType<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = TABLE[typeof database] extends (NoopDB | MariaDB | MySql) ? <TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>, ALIAS>(source: OuterJoinSource<TABLE_OR_VIEW2, ALIAS>) => OnExpression<TABLE, USING | OuterJoinTableOrView<TABLE_OR_VIEW2, ALIAS>> : never export interface UpdateSetJoinExpressionAllowingNoWhere<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetExpressionAllowingNoWhere<TABLE, USING> { join<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2): OnExpressionAllowingNoWhere<TABLE, USING | TABLE_OR_VIEW2> innerJoin<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2): OnExpressionAllowingNoWhere<TABLE, USING | TABLE_OR_VIEW2> leftJoin<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>, ALIAS>(source: OuterJoinSource<TABLE_OR_VIEW2, ALIAS>): OnExpressionAllowingNoWhere<TABLE, USING | OuterJoinTableOrView<TABLE_OR_VIEW2, ALIAS>> leftOuterJoin<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>, ALIAS>(source: OuterJoinSource<TABLE_OR_VIEW2, ALIAS>): OnExpressionAllowingNoWhere<TABLE, USING | OuterJoinTableOrView<TABLE_OR_VIEW2, ALIAS>> } export interface DynamicOnExpressionAllowingNoWhere<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetJoinExpressionAllowingNoWhere<TABLE, USING> { and(condition: IIfValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpressionAllowingNoWhere<TABLE, USING> and(condition: IBooleanValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpressionAllowingNoWhere<TABLE, USING> or(condition: IIfValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpressionAllowingNoWhere<TABLE, USING> or(condition: IBooleanValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpressionAllowingNoWhere<TABLE, USING> } export interface OnExpressionAllowingNoWhere<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetJoinExpressionAllowingNoWhere<TABLE, USING> { dynamicOn(): DynamicOnExpressionAllowingNoWhere<TABLE, USING> on(condition: IIfValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpressionAllowingNoWhere<TABLE, USING> on(condition: IBooleanValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]>, boolean | null | undefined>): DynamicOnExpressionAllowingNoWhere<TABLE, USING> } export interface UpdateExpressionWithoutJoinAllowingNoWhere<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetExpressionAllowingNoWhere<TABLE, USING> { from<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2): UpdateExpressionWithoutJoinAllowingNoWhere<TABLE, USING | TABLE_OR_VIEW2> } export interface UpdateFromExpressionAllowingNoWhere<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends UpdateSetJoinExpressionAllowingNoWhere<TABLE, USING> { from<TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2): UpdateExpressionWithoutJoinAllowingNoWhere<TABLE, USING | TABLE_OR_VIEW2> } type FromFnTypeAllowingNoWhere<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = TABLE[typeof database] extends (NoopDB | PostgreSql | SqlServer | Sqlite | MariaDB | MySql) ? <TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2) => UpdateFromExpressionAllowingNoWhere<TABLE, USING | TABLE_OR_VIEW2> : never type OnExpressionFnTypeAllowingNoWhere<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = TABLE[typeof database] extends (NoopDB | MariaDB | MySql) ? <TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>>(table: TABLE_OR_VIEW2) => OnExpressionAllowingNoWhere<TABLE, USING | TABLE_OR_VIEW2> : never type OuterJoinOnExpressionFnTypeAllowingNoWhere<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = TABLE[typeof database] extends (NoopDB | MariaDB | MySql) ? <TABLE_OR_VIEW2 extends ITableOrViewOf<TABLE[typeof database], any>, ALIAS>(source: OuterJoinSource<TABLE_OR_VIEW2, ALIAS>) => OnExpressionAllowingNoWhere<TABLE, USING | OuterJoinTableOrView<TABLE_OR_VIEW2, ALIAS>> : never export interface ReturnableExecutableUpdate<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> extends CustomizableExecutableUpdate<TABLE> { returning: ReturningFnType<TABLE, USING> returningOneColumn: ReturningOneColumnFnType<TABLE, USING> } export interface ExecutableUpdateReturning<TABLE extends ITableOrView<any>, COLUMNS, RESULT> extends UpdateExpressionBase<TABLE> { executeUpdateNoneOrOne(): Promise<( COLUMNS extends IValueSource<any, any> ? RESULT : { [P in keyof RESULT]: RESULT[P] }) | null> executeUpdateOne(): Promise<( COLUMNS extends IValueSource<any, any> ? RESULT : { [P in keyof RESULT]: RESULT[P] })> executeUpdateMany(min?: number, max?: number): Promise<( COLUMNS extends IValueSource<any, any> ? RESULT : { [P in keyof RESULT]: RESULT[P] })[]> query(): string params(): any[] } export interface ComposableExecutableUpdate<TABLE extends ITableOrView<any>, COLUMNS, RESULT> extends ExecutableUpdateReturning<TABLE, COLUMNS, RESULT> { compose<EXTERNAL_PROP extends keyof RESULT & ColumnGuard<COLUMNS>, INTERNAL_PROP extends string, RESULT_PROP extends string>(config: { externalProperty: EXTERNAL_PROP, internalProperty: INTERNAL_PROP, propertyName: RESULT_PROP }): ComposeExpression<EXTERNAL_PROP, INTERNAL_PROP, RESULT_PROP, TABLE, COLUMNS, RESULT> composeDeletingInternalProperty<EXTERNAL_PROP extends keyof RESULT & ColumnGuard<COLUMNS>, INTERNAL_PROP extends string, RESULT_PROP extends string>(config: { externalProperty: EXTERNAL_PROP, internalProperty: INTERNAL_PROP, propertyName: RESULT_PROP }): ComposeExpressionDeletingInternalProperty<EXTERNAL_PROP, INTERNAL_PROP, RESULT_PROP, TABLE, COLUMNS, RESULT> composeDeletingExternalProperty<EXTERNAL_PROP extends keyof RESULT & ColumnGuard<COLUMNS>, INTERNAL_PROP extends string, RESULT_PROP extends string>(config: { externalProperty: EXTERNAL_PROP, internalProperty: INTERNAL_PROP, propertyName: RESULT_PROP }): ComposeExpressionDeletingExternalProperty<EXTERNAL_PROP, INTERNAL_PROP, RESULT_PROP, TABLE, COLUMNS, RESULT> // Note: { [Q in keyof SelectResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }>]: SelectResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }>[Q] } is used to define the internal object because { [P in keyof MAPPING]: RESULT[MAPPING[P]] } doesn't respect the optional typing of the props splitRequired<RESULT_PROP extends string, MAPPED_PROPS extends keyof RESULT & ColumnGuard<COLUMNS>, MAPPING extends { [P: string]: MAPPED_PROPS }>(propertyName: RESULT_PROP, mappig: MAPPING): ComposableExecutableUpdate<TABLE, COLUMNS, Omit<RESULT, ValueOf<MAPPING>> & { [key in RESULT_PROP]: { [Q in keyof UpdateResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }>]: UpdateResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }>[Q] }}> splitOptional<RESULT_PROP extends string, MAPPED_PROPS extends keyof RESULT & ColumnGuard<COLUMNS>, MAPPING extends { [P: string]: MAPPED_PROPS }>(propertyName: RESULT_PROP, mappig: MAPPING): ComposableExecutableUpdate<TABLE, COLUMNS, Omit<RESULT, ValueOf<MAPPING>> & { [key in RESULT_PROP]?: { [Q in keyof UpdateResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }>]: UpdateResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }>[Q] }}> split<RESULT_PROP extends string, MAPPED_PROPS extends keyof RESULT & ColumnGuard<COLUMNS>, MAPPING extends { [P: string]: MAPPED_PROPS }>(propertyName: RESULT_PROP, mappig: MAPPING): ComposableExecutableUpdate<TABLE, COLUMNS, Omit<RESULT, ValueOf<MAPPING>> & ( {} extends UpdateResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }> ? { [key in RESULT_PROP]?: { [Q in keyof UpdateResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }>]: UpdateResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }>[Q] }} : { [key in RESULT_PROP]: { [Q in keyof UpdateResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }>]: UpdateResult<{ [P in keyof MAPPING]: RESULT[MAPPING[P]] }>[Q] }})> guidedSplitRequired<RESULT_PROP extends string, MAPPED_PROPS extends keyof GuidedObj<RESULT> & ColumnGuard<COLUMNS>, MAPPING extends { [P: string]: MAPPED_PROPS }>(propertyName: RESULT_PROP, mappig: MAPPING): ComposableExecutableUpdate<TABLE, COLUMNS, Omit<RESULT, GuidedPropName<ValueOf<MAPPING>>> & { [key in RESULT_PROP]: { [Q in keyof UpdateResult<{ [P in keyof MAPPING]: GuidedObj<RESULT>[MAPPING[P]] }>]: UpdateResult<{ [P in keyof MAPPING]: GuidedObj<RESULT>[MAPPING[P]] }>[Q] }}> guidedSplitOptional<RESULT_PROP extends string, MAPPED_PROPS extends keyof GuidedObj<RESULT> & ColumnGuard<COLUMNS>, MAPPING extends { [P: string]: MAPPED_PROPS }>(propertyName: RESULT_PROP, mappig: MAPPING): ComposableExecutableUpdate<TABLE, COLUMNS, Omit<RESULT, GuidedPropName<ValueOf<MAPPING>>> & { [key in RESULT_PROP]?: { [Q in keyof UpdateResult<{ [P in keyof MAPPING]: GuidedObj<RESULT>[MAPPING[P]] }>]: UpdateResult<{ [P in keyof MAPPING]: GuidedObj<RESULT>[MAPPING[P]] }>[Q] }}> } export interface ComposeExpression<EXTERNAL_PROP extends keyof RESULT, INTERNAL_PROP extends string, RESULT_PROP extends string, TABLE extends ITableOrView<any>, COLUMNS, RESULT> { withNoneOrOne<INTERNAL extends {[key in INTERNAL_PROP]: RESULT[EXTERNAL_PROP]}>(fn: (ids: Array<RESULT[EXTERNAL_PROP]>) => Promise<INTERNAL[]>): ComposableExecutableUpdate<TABLE, COLUMNS, RESULT & { [key in RESULT_PROP]?: INTERNAL }> withOne<INTERNAL extends {[key in INTERNAL_PROP]: RESULT[EXTERNAL_PROP]}>(fn: (ids: Array<RESULT[EXTERNAL_PROP]>) => Promise<INTERNAL[]>): ComposableExecutableUpdate<TABLE, COLUMNS, RESULT & ( EXTERNAL_PROP extends RequiredKeys<COLUMNS> ? { [key in RESULT_PROP]: INTERNAL } : { [key in RESULT_PROP]?: INTERNAL })> withMany<INTERNAL extends {[key in INTERNAL_PROP]: RESULT[EXTERNAL_PROP]}>(fn: (ids: Array<RESULT[EXTERNAL_PROP]>) => Promise<INTERNAL[]>): ComposableExecutableUpdate<TABLE, COLUMNS, RESULT & ( EXTERNAL_PROP extends RequiredKeys<COLUMNS> ? { [key in RESULT_PROP]: INTERNAL[] } : { [key in RESULT_PROP]?: INTERNAL[] })> } export interface ComposeExpressionDeletingInternalProperty<EXTERNAL_PROP extends keyof RESULT, INTERNAL_PROP extends string, RESULT_PROP extends string, TABLE extends ITableOrView<any>, COLUMNS, RESULT> { // Note: { [P in keyof Omit<INTERNAL, INTERNAL_PROP>]: Omit<INTERNAL, INTERNAL_PROP>[P] } is used to delete the internal prop because Omit<INTERNAL, INTERNAL_PROP> is not expanded in the editor (when see the type) withNoneOrOne<INTERNAL extends {[key in INTERNAL_PROP]: RESULT[EXTERNAL_PROP]}>(fn: (ids: Array<RESULT[EXTERNAL_PROP]>) => Promise<INTERNAL[]>): ComposableExecutableUpdate<TABLE, COLUMNS, RESULT & { [key in RESULT_PROP]?: { [P in keyof Omit<INTERNAL, INTERNAL_PROP>]: Omit<INTERNAL, INTERNAL_PROP>[P] }}> withOne<INTERNAL extends {[key in INTERNAL_PROP]: RESULT[EXTERNAL_PROP]}>(fn: (ids: Array<RESULT[EXTERNAL_PROP]>) => Promise<INTERNAL[]>): ComposableExecutableUpdate<TABLE, COLUMNS, RESULT & ( EXTERNAL_PROP extends RequiredKeys<COLUMNS> ? { [key in RESULT_PROP]: { [P in keyof Omit<INTERNAL, INTERNAL_PROP>]: Omit<INTERNAL, INTERNAL_PROP>[P] }} : { [key in RESULT_PROP]?: { [P in keyof Omit<INTERNAL, INTERNAL_PROP>]: Omit<INTERNAL, INTERNAL_PROP>[P] }} )> withMany<INTERNAL extends {[key in INTERNAL_PROP]: RESULT[EXTERNAL_PROP]}>(fn: (ids: Array<RESULT[EXTERNAL_PROP]>) => Promise<INTERNAL[]>): ComposableExecutableUpdate<TABLE, COLUMNS, RESULT & ( EXTERNAL_PROP extends RequiredKeys<COLUMNS> ? { [key in RESULT_PROP]: Array<{ [P in keyof Omit<INTERNAL, INTERNAL_PROP>]: Omit<INTERNAL, INTERNAL_PROP>[P] }> } : { [key in RESULT_PROP]?: Array<{ [P in keyof Omit<INTERNAL, INTERNAL_PROP>]: Omit<INTERNAL, INTERNAL_PROP>[P] }> })> } export interface ComposeExpressionDeletingExternalProperty<EXTERNAL_PROP extends keyof RESULT, INTERNAL_PROP extends string, RESULT_PROP extends string, TABLE extends ITableOrView<any>, COLUMNS, RESULT> { withNoneOrOne<INTERNAL extends {[key in INTERNAL_PROP]: RESULT[EXTERNAL_PROP]}>(fn: (ids: Array<RESULT[EXTERNAL_PROP]>) => Promise<INTERNAL[]>): ComposableExecutableUpdate<TABLE, COLUMNS, Omit<RESULT, EXTERNAL_PROP> & { [key in RESULT_PROP]?: INTERNAL }> withOne<INTERNAL extends {[key in INTERNAL_PROP]: RESULT[EXTERNAL_PROP]}>(fn: (ids: Array<RESULT[EXTERNAL_PROP]>) => Promise<INTERNAL[]>): ComposableExecutableUpdate<TABLE, COLUMNS, Omit<RESULT, EXTERNAL_PROP> & ( EXTERNAL_PROP extends RequiredKeys<COLUMNS> ? { [key in RESULT_PROP]: INTERNAL } : { [key in RESULT_PROP]?: INTERNAL })> withMany<INTERNAL extends {[key in INTERNAL_PROP]: RESULT[EXTERNAL_PROP]}>(fn: (ids: Array<RESULT[EXTERNAL_PROP]>) => Promise<INTERNAL[]>): ComposableExecutableUpdate<TABLE, COLUMNS, Omit<RESULT, EXTERNAL_PROP> & ( EXTERNAL_PROP extends RequiredKeys<COLUMNS> ? { [key in RESULT_PROP]: INTERNAL[] } : { [key in RESULT_PROP]?: INTERNAL[] })> } export interface ComposableCustomizableExecutableUpdate<TABLE extends ITableOrView<any>, COLUMNS, RESULT> extends ComposableExecutableUpdate<TABLE, COLUMNS, RESULT> { customizeQuery(customization: UpdateCustomization<TABLE[typeof database]>): ComposableExecutableUpdate<TABLE, COLUMNS, RESULT> } type ReturningFnType<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = TABLE[typeof database] extends (NoopDB | PostgreSql | SqlServer | Oracle) ? <COLUMNS extends UpdateColumns<TABLE, USING>>(columns: COLUMNS) => ComposableCustomizableExecutableUpdate<TABLE, COLUMNS, UpdateResult<ResultValues<COLUMNS>>> : (TABLE[typeof database] extends Sqlite ? <COLUMNS extends UpdateColumns<TABLE, TABLE>>(columns: COLUMNS) => ComposableCustomizableExecutableUpdate<TABLE, COLUMNS, UpdateResult<ResultValues<COLUMNS>>> : never) type ReturningOneColumnFnType<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = TABLE[typeof database] extends (NoopDB | PostgreSql | SqlServer | Oracle) ? <COLUMN extends IValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]> | OLD<TABLE[typeof tableOrViewRef]>, any>>(column: COLUMN) => ComposableCustomizableExecutableUpdate<TABLE, COLUMN, FixUpdateOneResult<COLUMN[typeof valueType]>> : (TABLE[typeof database] extends Sqlite ? <COLUMN extends IValueSource<TABLE[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]> | OLD<TABLE[typeof tableOrViewRef]>, any>>(column: COLUMN) => ComposableCustomizableExecutableUpdate<TABLE, COLUMN, FixUpdateOneResult<COLUMN[typeof valueType]>> : never) export type UpdateColumns<TABLE extends ITableOrView<any>, USING extends ITableOrView<any>> = { [P: string]: IValueSource<USING[typeof tableOrViewRef] | NoTableOrViewRequired<TABLE[typeof database]> | OLD<TABLE[typeof tableOrViewRef]>, any> } type ColumnGuard<T> = T extends null | undefined ? never : T extends never ? never : T extends IValueSource<any, any> ? never : unknown type GuidedObj<T> = T & { [K in keyof T as K extends string | number ? `${K}!` : never]-?: NonNullable<T[K]>} & { [K in keyof T as K extends string | number ? `${K}?` : never]?: T[K]} type GuidedPropName<T> = T extends `${infer Q}!` ? Q : T extends `${infer Q}?` ? Q : T type ValueOf<T> = T[keyof T] type RequiredKeys<T> = T extends IValueSource<any, any> ? never : { [K in keyof T]-?: {} extends Pick<T, K> ? never : K }[keyof T] type UpdateResult<RESULT> = undefined extends string ? RESULT // tsc is working with strict mode disabled. There is no way to infer the optional properties. Keep as required is a better approximation. : { [P in MandatoryPropertiesOf<RESULT>]: RESULT[P] } & { [P in OptionalPropertiesOf<RESULT>]?: NonNullable<RESULT[P]> } type MandatoryPropertiesOf<TYPE> = ({ [K in keyof TYPE]-?: null | undefined extends TYPE[K] ? never : (null extends TYPE[K] ? never : (undefined extends TYPE[K] ? never : K)) })[keyof TYPE] type OptionalPropertiesOf<TYPE> = ({ [K in keyof TYPE]-?: null | undefined extends TYPE[K] ? K : (null extends TYPE[K] ? K : (undefined extends TYPE[K] ? K : never)) })[keyof TYPE] type FixUpdateOneResult<T> = T extends undefined ? null : T type ResultValues<COLUMNS> = { [P in keyof COLUMNS]: ValueSourceResult<COLUMNS[P]> } type ValueSourceResult<T> = T extends IValueSource<any, infer R> ? R : never
the_stack
import { convertToAbsolute, decodeMappings, findInnermostEnclosingFunction, SourceMapDecoder, } from "../src/decoder"; import { FunctionDesc } from "../src/functionDesc"; import { RelativeFunctionDesc } from "../src/types"; import { JSONFromFile as JSONFromFileInFolder } from "./helper.t"; const test: typeof import("tape") = require("tape"); function JSONFromFile(file: string) { return JSONFromFileInFolder(file, "codec"); } test("decoder module test: bad sourcemap", (t) => { const badSourceMapFiles = [ "invalid.lengthMismatch.enrichedSourceMap.json", // source.length != x_com_bloomberg_sourcesFunctionMappings.length "invalid.badVLQ1.enrichedSourceMap.json", // "foo.js" mappings is an array of 7 elements "invalid.badVLQ2.enrichedSourceMap.json", // "foo.js" mappings contains invalid (unterminated) VLQ "invalid.badVLQ3.enrichedSourceMap.json", // "foo.js" mappings contains illegal characters VLQ "invalid.emptyStringMapping.enrichedSourceMap.json", // "foo.js" mappings is an empty string ]; t.plan(badSourceMapFiles.length); for (const file of badSourceMapFiles) { const sourceMap = JSONFromFile(file); t.throws(() => { new SourceMapDecoder(sourceMap); // tslint:disable-line no-unused-expression }); } }); test("decoder module test: empty sources", (t) => { t.plan(1); const sourceMap = JSONFromFile("emptySources.enrichedSourceMap.json"); const decoder = new SourceMapDecoder(sourceMap); t.throws(() => { decoder.decode("foo.js", 0, 0); }); }); test("decoder module test: simple", (t) => { t.plan(11); const sourceMap = JSONFromFile("simple.enrichedSourceMap.json"); const decoder = new SourceMapDecoder(sourceMap); // "bar.js" not in sources t.throws(() => { decoder.decode("bar.js", 0, 0); }); // "foo.js" present in sources, but mappings = "" let actual = decoder.decode("foo.js", 1, 1); let expected = null; t.deepEqual(actual, expected, "no mappings available for source"); // "bob.js" present in sources, but mappings = null actual = decoder.decode("bob.js", 1, 1); expected = null; t.deepEqual(actual, expected, "no mappings available for source"); // line out of range, expect null actual = decoder.decode("simple.js", 50, 0); expected = null; t.deepEqual(actual, expected); // top-level match actual = decoder.decode("simple.js", 0, 5); expected = "<top-level>"; t.deepEqual(actual, expected); // no column 20 in the file, but that's ok actual = decoder.decode("simple.js", 0, 20); expected = "f1"; t.deepEqual(actual, expected); // function match actual = decoder.decode("simple.js", 2, 0); expected = "f1"; t.deepEqual(actual, expected); // function match actual = decoder.decode("simple.js", 5, 1); expected = "real"; t.deepEqual(actual, expected); // nested function match actual = decoder.decode("simple.js", 6, 1); expected = "<anonymous>"; t.deepEqual(actual, expected); // function match actual = decoder.decode("simple.js", 8, 1); expected = "real"; t.deepEqual(actual, expected); // top-level match actual = decoder.decode("simple.js", 11, 1); expected = "<top-level>"; t.deepEqual(actual, expected); }); test("decoder module test: complex", (t) => { t.plan(12); const sourceMap = JSONFromFile("complex.enrichedSourceMap.json"); const decoder = new SourceMapDecoder(sourceMap); // function match let actual = decoder.decode("complex.js", 1, 0); let expected = "f1"; t.deepEqual(actual, expected); // function match actual = decoder.decode("complex.js", 2, 20); expected = "f1"; t.deepEqual(actual, expected); // nested match (anon function expression) actual = decoder.decode("complex.js", 3, 20); expected = "<anonymous>"; t.deepEqual(actual, expected); // nested match (arrow function) actual = decoder.decode("complex.js", 4, 25); expected = "<anonymous>"; t.deepEqual(actual, expected); // function match actual = decoder.decode("complex.js", 5, 10); expected = "f1"; t.deepEqual(actual, expected); // top-level match actual = decoder.decode("complex.js", 8, 0); expected = "<top-level>"; t.deepEqual(actual, expected); // function match actual = decoder.decode("complex.js", 10, 1); expected = "x"; t.deepEqual(actual, expected); // nested match actual = decoder.decode("complex.js", 11, 2); expected = "y"; t.deepEqual(actual, expected); // double nested match actual = decoder.decode("complex.js", 12, 10); expected = "z"; t.deepEqual(actual, expected); // nested match actual = decoder.decode("complex.js", 14, 15); expected = "y"; t.deepEqual(actual, expected); // function match actual = decoder.decode("complex.js", 16, 5); expected = "x"; t.deepEqual(actual, expected); // top-level match actual = decoder.decode("complex.js", 18, 5); expected = "<top-level>"; t.deepEqual(actual, expected); }); test("decoder unit test: decodeMappings", (t) => { t.plan(8); let actual = decodeMappings(null); let expected: RelativeFunctionDesc[] = []; t.deepEqual(actual, expected); // empty string expected = []; actual = decodeMappings(""); t.deepEqual(actual, expected); // valid VLQ but decoded value contains 2 elements instead of 5 t.throws(() => { decodeMappings("AB"); }); // bad VLQ - illegal characters t.throws(() => { decodeMappings("%£@"); }); // bad VLQ - unterminated sequence t.throws(() => { decodeMappings("ASFs"); }); // VLQ good but decoded array has 3 elements instead of 5 t.throws(() => { decodeMappings("XHF"); }); actual = decodeMappings("AAAWM"); expected = [new RelativeFunctionDesc(0, 0, 0, 11, 6)]; t.deepEqual(actual, expected); actual = decodeMappings("AAAWM,CVcEL,ECEKA"); expected = [ new RelativeFunctionDesc(0, 0, 0, 11, 6), new RelativeFunctionDesc(1, -10, 14, 2, -5), new RelativeFunctionDesc(2, 1, 2, 5, 0), ]; t.deepEqual(actual, expected); }); test("decoder unit test: convertToAbsolute", (t) => { t.plan(2); const sourceMap = JSONFromFile("simple.enrichedSourceMap.json"); // good input let relativeDescs = [ new RelativeFunctionDesc(5, 0, 0, 11, 6), new RelativeFunctionDesc(1, -10, 14, 2, -5), new RelativeFunctionDesc(-3, 1, 2, 5, 0), new RelativeFunctionDesc(4, -4, 0, 2, 5), ]; let actual = convertToAbsolute(relativeDescs, sourceMap.names); let expected = [ new FunctionDesc("<top-level>", 0, 0, 11, 6), new FunctionDesc("f1", 1, 14, 3, 1), new FunctionDesc("real", 4, 16, 9, 1), new FunctionDesc("<anonymous>", 5, 16, 7, 6), ]; t.deepEqual(actual, expected); // empty input relativeDescs = []; actual = convertToAbsolute(relativeDescs, sourceMap.names); expected = []; t.deepEqual(actual, expected); }); test("decoder unit test: convertToAbsolute bad inputs", (t) => { const sourceMap = JSONFromFile("simple.enrichedSourceMap.json"); const badInputs = [ [new RelativeFunctionDesc(0, -1, 0, -1, 0)], // negative positions [new RelativeFunctionDesc(0, 10, 0, -5, 0)], // startLine > endLine [new RelativeFunctionDesc(0, 10, 5, 0, 0)], // startLine === endLine, startColumn > endColumn [new RelativeFunctionDesc(-4, 0, 0, 0, 0)], // name index negative for first element [ new RelativeFunctionDesc(2, 0, 0, 0, 0), new RelativeFunctionDesc(-3, 2, 5, 2, 5), ], // name index negative for second element [new RelativeFunctionDesc(20, 0, 0, 0, 0)], // name index out of range for first element [ new RelativeFunctionDesc(5, 0, 0, 0, 0), new RelativeFunctionDesc(15, 2, 2, 10, 10), ], // name index out of range for second element [ new RelativeFunctionDesc(0, 0, 0, 1, 0), new RelativeFunctionDesc(1, 10, 0, 10, 0), new RelativeFunctionDesc(1, -15, 0, 3, 0), ], // functions not ordered by line number [ new RelativeFunctionDesc(0, 0, 0, 1, 0), new RelativeFunctionDesc(1, 10, 0, 10, 0), new RelativeFunctionDesc(1, -5, 0, 10, 0), ], // bad nesting ]; t.plan(badInputs.length); for (const relDescs of badInputs) { t.throws(() => { convertToAbsolute(relDescs, sourceMap.names); }); } }); test("decoder unit test: findInnermostEnclosingFunction", (t) => { t.plan(14); let functionDescs = [ new FunctionDesc("<top-level>", 0, 0, 21, 0), new FunctionDesc("f1", 1, 0, 8, 0), new FunctionDesc("f2", 4, 5, 6, 3), new FunctionDesc("<anonymous>", 5, 10, 5, 20), new FunctionDesc("x", 10, 0, 18, 1), ]; let actual = findInnermostEnclosingFunction(0, 1, functionDescs); let expected = "<top-level>"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(3, 5, functionDescs); expected = "f1"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(5, 1, functionDescs); expected = "f2"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(5, 12, functionDescs); expected = "<anonymous>"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(9, 0, functionDescs); expected = "<top-level>"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(13, 20, functionDescs); expected = "x"; t.deepEqual(actual, expected); // all functions on one line functionDescs = [ new FunctionDesc("<top-level>", 0, 0, 10, 0), new FunctionDesc("f1", 1, 0, 1, 20), new FunctionDesc("f2", 1, 2, 1, 18), new FunctionDesc("f3", 1, 4, 1, 16), ]; actual = findInnermostEnclosingFunction(0, 5, functionDescs.slice()); expected = "<top-level>"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(1, 1, functionDescs.slice()); expected = "f1"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(1, 3, functionDescs.slice()); expected = "f2"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(1, 5, functionDescs.slice()); expected = "f3"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(1, 15, functionDescs.slice()); expected = "f3"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(1, 17, functionDescs.slice()); expected = "f2"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(1, 19, functionDescs.slice()); expected = "f1"; t.deepEqual(actual, expected); actual = findInnermostEnclosingFunction(1, 21, functionDescs.slice()); expected = "<top-level>"; t.deepEqual(actual, expected); });
the_stack
import * as d3 from 'd3'; import {action, computed, observable, reaction} from 'mobx'; import {ColorOption, D3Scale, FacetedData, GroupedExamples, IndexedInput, Preds, Spec} from '../lib/types'; import {findSpecKeys} from '../lib/utils'; import {BINARY_POS_NEG, CATEGORICAL_NORMAL} from '../lib/colors'; import {LitService} from './lit_service'; import {ApiService, AppState, GroupService} from './services'; import {FacetingConfig, FacetingMethod} from './group_service'; interface AllClassificationInfo { [id: string]: PerExampleClassificationInfo; } interface PerExampleClassificationInfo { [model: string]: PerExamplePerModelClassificationInfo; } interface PerExamplePerModelClassificationInfo { [predKey: string]: ClassificationInfo; } /** * Info about individual classifications including computed properties. * These interface field names should be in sync with the * fieldsToDisplayNames Map. */ export interface ClassificationInfo { predictions: number[]; predictedClassIdx: number; predictionCorrect?: boolean; } /** * A map from classification info field names to their display names. */ const classificationDisplayNames = new Map([ ['predictions', 'predictions'], ['predictedClassIdx', 'predicted class index'], ['predictionCorrect', 'prediction correct'], ]); /** * A margin setting is the margin value and the facet information for which * datapoints from a dataset that margin value applies to. */ interface MarginSetting { facetData?: FacetedData; margin: number; } /** * Any facet of a dataset can have its own margin value. Key string represents * the facet key/value pairs. */ interface MarginsPerFacet { [facetString: string]: MarginSetting; } /** Each output field has its own margin settings. */ export interface MarginsPerField { [fieldName: string]: MarginsPerFacet; } /** * Classification margin settings across all models and prediction heads. * * Margins are a generalized way to define classification thresholds beyond * binary classification score threshoods. */ export interface MarginSettings { [model: string]: MarginsPerField; } /** * Given an example and the margins for a field, return the appropriate margin * to use for the example. */ function getMarginSettingForExample( input: IndexedInput, marginsPerFacet: MarginsPerFacet, groupService?: GroupService) { // If there is an empty string entry, this represents the margin for the // entire dataset. if ("" in marginsPerFacet) { return marginsPerFacet[""]; } // Find the facet that matches the example provided. for (const group of Object.values(marginsPerFacet)) { let matches = true; for (const field of Object.keys(group.facetData!.facets!)) { if (groupService != null && groupService.numericalFeatureNames.includes(field)) { const facetConfig: FacetingConfig = { featureName: field, method: FacetingMethod.EQUAL_INTERVAL, numBins: 0 }; const bins = groupService.numericalFeatureBins([facetConfig]); const bin = groupService.getNumericalBinForExample(bins, input, field)!; const groupRange = group.facetData!.facets![field].val as number[]; if (bin[0] !== groupRange[0] || bin[1] !== groupRange[1]) { matches = false; break; } } else if (input.data[field] !== group.facetData!.facets![field].val) { matches = false; break; } } if (matches) { return group; } } return null; } /** * Return the predicted class index given prediction scores and settings. */ export function getPredictionClass( scores: number[], predKey: string, outputSpec: Spec, input: IndexedInput, groupService?: GroupService, margins?: MarginsPerField) { let margin = 0; if (margins?.[predKey] != null) { const group = getMarginSettingForExample( input, margins[predKey], groupService); if (group != null) { margin = margins[predKey][group.facetData?.displayName || ""].margin; } } const nullIdx = outputSpec[predKey].null_idx; let maxScore = -Infinity; let maxIndex = 0; // Find max of the log prediction scores, adding any provided margin // to the null class, if there is one set. for (let i = 0; i < scores.length; i++) { let score = Math.log(scores[i]); if (nullIdx === i) { score += margin; } if (maxScore < score) { maxScore = score; maxIndex = i; } } return maxIndex; } /** * A singleton class that handles calculating and storing per-input * classification response information. */ export class ClassificationService extends LitService { @observable classificationInfo: AllClassificationInfo = {}; @observable marginSettings: MarginSettings = {}; // Stores list of possible labels for a given model/prediction-key // combination. @observable private readonly labelNames: {[modelAndKey: string]: string[]} = {}; constructor( private readonly apiService: ApiService, private readonly appState: AppState, private readonly groupService: GroupService) { super(); reaction(() => this.allMarginSettings, margins => { this.updateClassifications(); }); reaction(() => appState.currentModels, currentModels => { this.reset(); }); } // Returns all margin settings for use as a reaction input function when // setting up observers. // TODO(lit-team): Remove need for this intermediate object (b/156100081) @computed get allMarginSettings(): number[] { const res: number[] = []; for (const settingsPerModel of Object.values(this.marginSettings)) { for (const settingsPerPredKey of Object.values(settingsPerModel)) { for (const settingsPerFacet of Object.values(settingsPerPredKey)) { res.push(settingsPerFacet.margin); } } } return res; } /** * Reset the facet groups that store margins for a field based on the * facets from the groupedExamples. */ @action setMarginGroups(model: string, fieldName: string, groupedExamples: GroupedExamples) { if (this.marginSettings[model] == null) { this.marginSettings[model] = {}; } this.marginSettings[model][fieldName] = {}; for (const group of Object.values(groupedExamples)) { this.marginSettings[model][fieldName][group.displayName!] = {facetData: group, margin: 0}; } } @action setMargin(model: string, fieldName: string, value: number, facet?: FacetedData) { console.log('setMargin'); if (this.marginSettings[model] == null) { this.marginSettings[model] = {}; } if (this.marginSettings[model][fieldName] == null) { this.marginSettings[model][fieldName] = {}; } if (facet == null) { // If no facet provided, then update the facet for the entire dataset // if one exists, otherwise update all facets with the provided margin. if ("" in this.marginSettings[model][fieldName]) { this.marginSettings[model][fieldName][""] = {facetData: facet, margin: value}; } else { for (const key of Object.keys(this.marginSettings[model][fieldName])) { this.marginSettings[model][fieldName][key].margin = value; } } } else { this.marginSettings[model][fieldName][facet.displayName!] = {facetData: facet, margin: value}; } } getMargin(model: string, fieldName: string, facet?: FacetedData) { if (this.marginSettings[model] == null || this.marginSettings[model][fieldName] == null) { return 0; } if (facet == null) { if (this.marginSettings[model][fieldName][""] == null) { return 0; } return this.marginSettings[model][fieldName][""].margin; } else { if (this.marginSettings[model][fieldName][facet.displayName!] == null) { return 0; } return this.marginSettings[model][fieldName][facet.displayName!].margin; } } /** * Calls the server to get multiclass predictions and calculate related info. * @param inputs inputs to run model on * @param model model to query * @param datasetName current dataset (for caching) */ async getClassificationPreds( inputs: IndexedInput[], model: string, datasetName: string): Promise<Preds[]> { // TODO(lit-team): Use client-side cache when available. const result = this.apiService.getPreds( inputs, model, datasetName, ['MulticlassPreds']); const preds = await result; if (preds != null && preds.length > 0) { this.processNewPreds(inputs, model, preds); } return result; } /** * Get labels list for a given prediction task. */ getLabelNames(model: string, predKey: string) { return this.labelNames[`${model}:${predKey}`]; } getInfoFields() { return Array.from(classificationDisplayNames.keys()); } getDisplayNames() { return Array.from(classificationDisplayNames.values()); } private updateClassifications() { for (const input of this.appState.currentInputData) { const info = this.classificationInfo[input.id]; if (info == null) { continue; } const models = Object.keys(info); for (const model of models) { const predKeys = Object.keys(info[model]); for (const predKey of predKeys) { const fields = info[model][predKey]; this.updateClassification(fields, input, predKey, model); } } } } private updateClassification( fields: ClassificationInfo, input: IndexedInput, predKey: string, model: string) { const outputSpec = this.appState.currentModelSpecs[model].spec.output; fields.predictedClassIdx = getPredictionClass( fields.predictions, predKey, outputSpec, input, this.groupService, this.marginSettings[model]); // If there are labels, use those. Otherwise just use prediction // array indices. const labelKey = `${model}:${predKey}`; if (this.labelNames[labelKey] == null) { this.labelNames[labelKey] = outputSpec[predKey].vocab || Array.from({length: fields.predictions.length}, (v, k) => `${k}`); } const labelField = outputSpec[predKey].parent; if (labelField != null) { fields.predictionCorrect = input.data[labelField] === this.labelNames[labelKey][fields.predictedClassIdx]; } } /** * Reset stored info. Used when active models change. */ reset() { this.classificationInfo = {}; } /** * Gets stored results for the given datapoints and predictions. */ async getResults(ids: string[], model: string, predKey: string): Promise<ClassificationInfo[]> { // TODO(lit-dev): rate-limit this and batch requests, otherwise if this is // called on individual datapoints it will make a massive number of backend // requests. const unstoredIds: string[] = []; ids.forEach((id) => { if (this.classificationInfo[ids[0]]?.[model]?.[predKey] == null) { unstoredIds.push(id); } }); // If any results aren't yet stored in the front-end, then get them. if (unstoredIds.length > 0) { await this.getClassificationPreds( this.appState.getExamplesById(unstoredIds), model, this.appState.currentDataset); } const results: ClassificationInfo[] = []; ids.forEach((id) => { const classificationInfo = this.classificationInfo[id]?.[model]?.[predKey]; if (classificationInfo != null) { results.push(classificationInfo); } }); return results; } private processNewPreds( inputs: IndexedInput[], model: string, preds: Preds[]) { const outputSpec = this.appState.currentModelSpecs[model].spec.output; const multiclassKeys = findSpecKeys(outputSpec, 'MulticlassPreds'); const predictedKeys = Object.keys(preds[0]); for (let i = 0; i < preds.length; i++) { const input = inputs[i]; const pred = preds[i]; if (this.classificationInfo[input.id] == null) { this.classificationInfo[input.id] = {} as PerExampleClassificationInfo; } if (this.classificationInfo[input.id][model] == null) { this.classificationInfo[input.id][model] = {} as PerExamplePerModelClassificationInfo; } for (let predIndex = 0; predIndex < predictedKeys.length; predIndex++) { const predKey = predictedKeys[predIndex]; if (!multiclassKeys.includes(predKey)) { continue; } const fields = {} as ClassificationInfo; fields.predictions = pred[predKey] as number[]; this.updateClassification(fields, input, predKey, model); if (this.classificationInfo[input.id][model][predKey] == null) { this.classificationInfo[input.id][model][predKey] = fields; } } } } @computed get colorOptions(): ColorOption[] { const ids = Object.keys(this.classificationInfo); if (ids.length === 0) { return []; } const options: ColorOption[] = []; const info = this.classificationInfo[ids[0]]; const models = Object.keys(info); for (const model of models) { const predKeys = Object.keys(info[model]); for (const predKey of predKeys) { options.push({ name: `${model}:${predKey} class`, getValue: (input: IndexedInput) => this.labelNames[`${model}:${predKey}`] [this.classificationInfo[input.id][model][predKey] .predictedClassIdx], scale: d3.scaleOrdinal(CATEGORICAL_NORMAL) .domain(this.labelNames[`${model}:${predKey}`]) as D3Scale }); if (info[model][predKey].predictionCorrect != null) { options.push({ name: `${model}:${predKey} correct`, getValue: (input: IndexedInput) => this.classificationInfo[input.id][model][predKey] .predictionCorrect ? 'correct' : 'incorrect', scale: d3.scaleOrdinal(BINARY_POS_NEG) .domain(['correct', 'incorrect']) as D3Scale }); } } } return options; } }
the_stack
import { ECSchemaToTs } from "../ecschema2ts"; import { assert } from "chai"; import * as utils from "./utilities/utils"; import { SchemaContext } from "@itwin/ecschema-metadata"; import { SchemaXmlFileLocater } from "@itwin/ecschema-locaters"; describe("BisCore test correct inheritance", () => { let ecschema2ts: ECSchemaToTs; beforeEach(() => { ecschema2ts = new ECSchemaToTs(); }); it("of class that subclasses Element with additional properties", () => { const schemaXml = ` <?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="BisCore" alias="bis" version="01.00.00" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="Element" modifier="Abstract"> <ECCustomAttributes> <CustomHandledProperty xmlns="BisCore.1.0.0"/> </ECCustomAttributes> <ECProperty propertyName="TestProp" typeName="string"/> </ECEntityClass> <ECEntityClass typeName="DerivedElement"> <BaseClass>Element</BaseClass> <ECProperty propertyName="DerivedTestProp" typeName="string"/> </ECEntityClass> <ECCustomAttributeClass typeName="CustomHandledProperty" description="Applied to an element's property to indicate that the property's value is handled specially by a C++ class." appliesTo="AnyProperty"> <ECProperty propertyName="StatementTypes" typeName="CustomHandledPropertyStatementType"/> </ECCustomAttributeClass> <ECEnumeration typeName="CustomHandledPropertyStatementType" backingTypeName="int" isStrict="true"> <ECEnumerator name="CustomHandledPropertyStatementType0" value="0" displayLabel="None"/> <ECEnumerator name="CustomHandledPropertyStatementType1" value="1" displayLabel="Select"/> <ECEnumerator name="CustomHandledPropertyStatementType2" value="2" displayLabel="Insert"/> <ECEnumerator name="CustomHandledPropertyStatementType3" value="3" displayLabel="ReadOnly = Select|Insert"/> <ECEnumerator name="CustomHandledPropertyStatementType4" value="4" displayLabel="Update"/> <ECEnumerator name="CustomHandledPropertyStatementType6" value="6" displayLabel="InsertUpdate = Insert | Update"/> <ECEnumerator name="CustomHandledPropertyStatementType7" value="7" displayLabel="All = Select | Insert | Update"/> </ECEnumeration> </ECSchema>`; const expectedElementSchemaString = `import { Entity, IModelDb } from "@itwin/core-backend"; import { EntityProps } from "@itwin/core-common"; import { DerivedElementProps } from "./BisCoreElementProps"; export abstract class Element extends Entity { public static get className(): string { return "Element"; } public constructor (props: EntityProps, iModel: IModelDb) { super(props, iModel); } } export const enum CustomHandledPropertyStatementType { None = 0, Select = 1, Insert = 2, ReadOnly = Select|Insert = 3, Update = 4, InsertUpdate = Insert | Update = 6, All = Select | Insert | Update = 7, } export class DerivedElement extends Element implements DerivedElementProps { public static get className(): string { return "DerivedElement"; } public constructor (props: DerivedElementProps, iModel: IModelDb) { super(props, iModel); } }\n\n`; const expectedPropsSchemaString = `import { ElementProps } from "@itwin/core-common"; export interface DerivedElementProps extends ElementProps { derivedTestProp?: string; }\n\n`; const context = new SchemaContext(); const schema = utils.deserializeXml(context, schemaXml); const { elemTsString, propsTsString } = ecschema2ts.convertSchemaToTs(schema); assert.equal(propsTsString, expectedPropsSchemaString); assert.equal(elemTsString, expectedElementSchemaString); }); it("of class that subclasses Element without additional properties", () => { const schemaXml = `<?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="BisCore" alias="bis" version="01.00.00" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="Element" modifier="Abstract"> <ECCustomAttributes> <CustomHandledProperty xmlns="BisCore.01.00.00"/> </ECCustomAttributes> <ECProperty propertyName="TestProp" typeName="string"/> </ECEntityClass> <ECEntityClass typeName="DerivedElement"> <BaseClass>Element</BaseClass> </ECEntityClass> <ECCustomAttributeClass typeName="CustomHandledProperty" description="Applied to an element's property to indicate that the property's value is handled specially by a C++ class." appliesTo="AnyProperty"> <ECProperty propertyName="StatementTypes" typeName="CustomHandledPropertyStatementType"/> </ECCustomAttributeClass> <ECEnumeration typeName="CustomHandledPropertyStatementType" backingTypeName="int" isStrict="true"> <ECEnumerator name="CustomHandledPropertyStatementType0" value="0" displayLabel="None"/> <ECEnumerator name="CustomHandledPropertyStatementType1" value="1" displayLabel="Select"/> <ECEnumerator name="CustomHandledPropertyStatementType2" value="2" displayLabel="Insert"/> <ECEnumerator name="CustomHandledPropertyStatementType3" value="3" displayLabel="ReadOnly = Select|Insert"/> <ECEnumerator name="CustomHandledPropertyStatementType4" value="4" displayLabel="Update"/> <ECEnumerator name="CustomHandledPropertyStatementType6" value="6" displayLabel="InsertUpdate = Insert | Update"/> <ECEnumerator name="CustomHandledPropertyStatementType7" value="7" displayLabel="All = Select | Insert | Update"/> </ECEnumeration> </ECSchema>`; const expectedElementSchemaString = `import { Entity, IModelDb } from "@itwin/core-backend"; import { EntityProps, ElementProps } from "@itwin/core-common"; export abstract class Element extends Entity { public static get className(): string { return "Element"; } public constructor (props: EntityProps, iModel: IModelDb) { super(props, iModel); } } export const enum CustomHandledPropertyStatementType { None = 0, Select = 1, Insert = 2, ReadOnly = Select|Insert = 3, Update = 4, InsertUpdate = Insert | Update = 6, All = Select | Insert | Update = 7, } export class DerivedElement extends Element { public static get className(): string { return "DerivedElement"; } public constructor (props: ElementProps, iModel: IModelDb) { super(props, iModel); } }\n\n`; const context = new SchemaContext(); const schema = utils.deserializeXml(context, schemaXml); const { elemTsString, propsTsString } = ecschema2ts.convertSchemaToTs(schema); assert.equal(propsTsString, `\n`); assert.equal(elemTsString, expectedElementSchemaString); }); it("with multiple levels derived from Element without properties", () => { // A modified heirarchy of the bis schema to test a specific use case. const schemaXml = ` <?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="BisCore" alias="bis" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECEntityClass typeName="Element" modifier="Abstract"> <ECProperty propertyName="LastMod" typeName="int"> <ECCustomAttributes> <CustomHandledProperty xmlns="BisCore.01.00.00"> <StatementTypes>0</StatementTypes> </CustomHandledProperty> </ECCustomAttributes> </ECProperty> </ECEntityClass> <ECEntityClass typeName="InformationContentElement" modifier="Abstract"> <BaseClass>Element</BaseClass> </ECEntityClass> <ECEntityClass typeName="InformationReferenceElement" modifier="Abstract"> <BaseClass>InformationContentElement</BaseClass> </ECEntityClass> <ECEntityClass typeName="Subject" modifier="Sealed"> <BaseClass>InformationReferenceElement</BaseClass> <BaseClass>IParentElement</BaseClass> <ECProperty propertyName="Description" typeName="string"/> </ECEntityClass> <ECEntityClass typeName="IParentElement" modifier="Abstract"> <ECCustomAttributes> <IsMixin xmlns="CoreCustomAttributes.1.0"> <AppliesToEntityClass>Element</AppliesToEntityClass> </IsMixin> </ECCustomAttributes> </ECEntityClass> <ECCustomAttributeClass typeName="CustomHandledProperty" description="Applied to an element's property to indicate that the property's value is handled specially by a C++ class." appliesTo="AnyProperty"> <ECProperty propertyName="StatementTypes" typeName="CustomHandledPropertyStatementType"/> </ECCustomAttributeClass> <ECEnumeration typeName="CustomHandledPropertyStatementType" backingTypeName="int" isStrict="true"> <ECEnumerator name="CustomHandledPropertyStatementType0" value="0" displayLabel="None"/> <ECEnumerator name="CustomHandledPropertyStatementType1" value="1" displayLabel="Select"/> <ECEnumerator name="CustomHandledPropertyStatementType2" value="2" displayLabel="Insert"/> <ECEnumerator name="CustomHandledPropertyStatementType3" value="3" displayLabel="ReadOnly = Select|Insert"/> <ECEnumerator name="CustomHandledPropertyStatementType4" value="4" displayLabel="Update"/> <ECEnumerator name="CustomHandledPropertyStatementType6" value="6" displayLabel="InsertUpdate = Insert | Update"/> <ECEnumerator name="CustomHandledPropertyStatementType7" value="7" displayLabel="All = Select | Insert | Update"/> </ECEnumeration> </ECSchema>`; const expectedElementSchemaString = `import { Entity, IModelDb } from "@itwin/core-backend"; import { EntityProps, ElementProps } from "@itwin/core-common"; import { SubjectProps } from "./BisCoreElementProps"; export abstract class Element extends Entity { public static get className(): string { return "Element"; } public constructor (props: EntityProps, iModel: IModelDb) { super(props, iModel); } } export const enum CustomHandledPropertyStatementType { None = 0, Select = 1, Insert = 2, ReadOnly = Select|Insert = 3, Update = 4, InsertUpdate = Insert | Update = 6, All = Select | Insert | Update = 7, } export abstract class InformationContentElement extends Element { public static get className(): string { return "InformationContentElement"; } public constructor (props: ElementProps, iModel: IModelDb) { super(props, iModel); } } export abstract class InformationReferenceElement extends InformationContentElement { public static get className(): string { return "InformationReferenceElement"; } public constructor (props: ElementProps, iModel: IModelDb) { super(props, iModel); } } export class Subject extends InformationReferenceElement implements SubjectProps { public static get className(): string { return "Subject"; } public constructor (props: SubjectProps, iModel: IModelDb) { super(props, iModel); } }\n\n`; const expectedPropSchemaString = `import { ElementProps } from "@itwin/core-common"; export interface IParentElement { } export interface SubjectProps extends ElementProps { description?: string; }\n\n`; const context = new SchemaContext(); const schema = utils.deserializeXml(context, schemaXml); const { elemTsString, propsTsString } = ecschema2ts.convertSchemaToTs(schema); assert.equal(elemTsString, expectedElementSchemaString); assert.equal(propsTsString, expectedPropSchemaString); }); }); describe("Referencing BisCore", () => { it("as a base class", () => { const schemaXml = ` <?xml version="1.0" encoding="UTF-8"?> <ECSchema schemaName="ECObjects" alias="eco" version="02.00.00" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2"> <ECSchemaReference name="BisCore" version="01.00.00" alias="bis"/> <ECEntityClass typeName="SchemaDictionary" modifer="Sealed" description="The singleton container of SchemaDef Elements"> <BaseClass>bis:DefinitionModel</BaseClass> </ECEntityClass> <!-- A Model that models SchemaDef elements contained in the SchemasDefinitionModel --> <ECEntityClass typeName="SchemaModel" modifier="Sealed" description="A container for SchemaChild elements"> <BaseClass>bis:DefinitionModel</BaseClass> </ECEntityClass> </ECSchema>`; const expectedElementSchemaString = `import { DefinitionModel, IModelDb } from "@itwin/core-backend"; import { ModelProps } from "@itwin/core-common"; /** * The singleton container of SchemaDef Elements */ export class SchemaDictionary extends DefinitionModel { public static get className(): string { return "SchemaDictionary"; } public constructor (props: ModelProps, iModel: IModelDb) { super(props, iModel); } } /** * A container for SchemaChild elements */ export class SchemaModel extends DefinitionModel { public static get className(): string { return "SchemaModel"; } public constructor (props: ModelProps, iModel: IModelDb) { super(props, iModel); } }\n\n`; const schemaLocator = new SchemaXmlFileLocater(); schemaLocator.addSchemaSearchPath(`${utils.getAssetsDir()}schema3.2`); const context = new SchemaContext(); context.addLocater(schemaLocator); const schema = utils.deserializeXml(context, schemaXml); const ecschema2ts = new ECSchemaToTs(); const { elemTsString, propsTsString } = ecschema2ts.convertSchemaToTs(schema); assert.equal(propsTsString, `\n`); assert.equal(elemTsString, expectedElementSchemaString); }); });
the_stack
// TODO(crbug.com/1203307): Auto-generate this file. import {ChromeEvent} from './chrome_event.js'; declare global { export namespace chrome { export namespace developerPrivate { export enum ItemType { HOSTED_APP = 'hosted_app', PACKAGED_APP = 'packaged_app', LEGACY_PACKAGED_APP = 'legacy_packaged_app', EXTENSION = 'extension', THEME = 'theme', } export type ItemInspectView = { path: string, render_process_id: number, render_view_id: number, incognito: boolean, generatedBackgroundPage: boolean, }; export type InstallWarning = { message: string, }; export enum ExtensionType { HOSTED_APP = 'HOSTED_APP', PLATFORM_APP = 'PLATFORM_APP', LEGACY_PACKAGED_APP = 'LEGACY_PACKAGED_APP', EXTENSION = 'EXTENSION', THEME = 'THEME', SHARED_MODULE = 'SHARED_MODULE', } export enum Location { FROM_STORE = 'FROM_STORE', UNPACKED = 'UNPACKED', THIRD_PARTY = 'THIRD_PARTY', UNKNOWN = 'UNKNOWN', } export enum ViewType { APP_WINDOW = 'APP_WINDOW', BACKGROUND_CONTENTS = 'BACKGROUND_CONTENTS', COMPONENT = 'COMPONENT', EXTENSION_BACKGROUND_PAGE = 'EXTENSION_BACKGROUND_PAGE', EXTENSION_DIALOG = 'EXTENSION_DIALOG', EXTENSION_GUEST = 'EXTENSION_GUEST', EXTENSION_POPUP = 'EXTENSION_POPUP', EXTENSION_SERVICE_WORKER_BACKGROUND = 'EXTENSION_SERVICE_WORKER_BACKGROUND', TAB_CONTENTS = 'TAB_CONTENTS', } export enum ErrorType { MANIFEST = 'MANIFEST', RUNTIME = 'RUNTIME', } export enum ErrorLevel { LOG = 'LOG', WARN = 'WARN', ERROR = 'ERROR', } export enum ExtensionState { ENABLED = 'ENABLED', DISABLED = 'DISABLED', TERMINATED = 'TERMINATED', BLACKLISTED = 'BLACKLISTED', } export enum ComandScope { GLOBAL = 'GLOBAL', CHROME = 'CHROME', } export type GetExtensionsInfoOptions = { includeDisabled?: boolean, includeTerminated?: boolean, }; export enum CommandScope { GLOBAL = 'GLOBAL', CHROME = 'CHROME', } export type AccessModifier = { isEnabled: boolean, isActive: boolean, }; export type StackFrame = { lineNumber: number, columnNumber: number, url: string, functionName: string, }; export type ManifestError = { type: ErrorType, extensionId: string, fromIncognito: boolean, source: string, message: string, id: number, manifestKey: string, manifestSpecific?: string, }; export type RuntimeError = { type: ErrorType, extensionId: string, fromIncognito: boolean, source: string, message: string, id: number, severity: ErrorLevel, contextUrl: string, occurrences: number, renderViewId: number, renderProcessId: number, canInspect: boolean, stackTrace: StackFrame[], }; export type DisableReasons = { suspiciousInstall: boolean, corruptInstall: boolean, updateRequired: boolean, blockedByPolicy: boolean, reloading: boolean, custodianApprovalRequired: boolean, parentDisabledPermissions: boolean, }; export type OptionsPage = { openInTab: boolean, url: string, }; export type HomePage = { url: string, specified: boolean, }; export type ExtensionView = { url: string, renderProcessId: number, renderViewId: number, incognito: boolean, isIframe: boolean, type: ViewType, }; export enum HostAccess { ON_CLICK = 'ON_CLICK', ON_SPECIFIC_SITES = 'ON_SPECIFIC_SITES', ON_ALL_SITES = 'ON_ALL_SITES', } export type ControlledInfo = { text: string, }; export type Command = { description: string, keybinding: string, name: string, isActive: boolean, scope: CommandScope, isExtensionAction: boolean, }; export type DependentExtension = { id: string, name: string, }; export type Permission = { message: string, submessages: string[], }; export type SiteControl = { host: string, granted: boolean, }; export type RuntimeHostPermissions = { hasAllHosts: boolean, hostAccess: HostAccess, hosts: chrome.developerPrivate.SiteControl[], }; export type Permissions = { simplePermissions: chrome.developerPrivate.Permission[], runtimeHostPermissions?: RuntimeHostPermissions, }; export type ExtensionInfo = { blacklistText?: string, commands: Command[], controlledInfo?: ControlledInfo, dependentExtensions: DependentExtension[], description: string, disableReasons: DisableReasons, errorCollection: AccessModifier, fileAccess: AccessModifier, homePage: HomePage, iconUrl: string, id: string, incognitoAccess: AccessModifier, installWarnings: string[], launchUrl?: string, location: Location, locationText?: string, manifestErrors: ManifestError[], manifestHomePageUrl: string, mustRemainInstalled: boolean, name: string, offlineEnabled: boolean, optionsPage?: OptionsPage, path?: string, permissions: Permissions, prettifiedPath?: string, runtimeErrors: RuntimeError[], runtimeWarnings: string[], state: ExtensionState, type: ExtensionType, updateUrl: string, userMayModify: boolean, version: string, views: ExtensionView[], webStoreUrl: string, showSafeBrowsingAllowlistWarning: boolean, }; export type ProfileInfo = { canLoadUnpacked: boolean, inDeveloperMode: boolean, isDeveloperModeControlledByPolicy: boolean, isIncognitoAvailable: boolean, isSupervised: boolean, }; export type ExtensionConfigurationUpdate = { extensionId: string, fileAccess?: boolean, incognitoAccess?: boolean, errorCollection?: boolean, hostAccess?: HostAccess, }; export type ProfileConfigurationUpdate = { inDeveloperMode: boolean, }; export type ExtensionCommandUpdate = { extensionId: string, commandName: string, scope?: CommandScope, keybinding?: string, }; export type ReloadOptions = { failQuietly?: boolean, populateErrorForUnpacked?: boolean, }; export type LoadUnpackedOptions = { failQuietly?: boolean, populateError?: boolean, retryGuid?: string, useDraggedPath?: boolean, }; export enum PackStatus { SUCCESS = 'SUCCESS', ERROR = 'ERROR', WARNING = 'WARNING', } export enum FileType { LOAD = 'LOAD', PEM = 'PEM', } export enum SelectType { FILE = 'FILE', FOLDER = 'FOLDER', } export enum EventType { INSTALLED = 'INSTALLED', UNINSTALLED = 'UNINSTALLED', LOADED = 'LOADED', UNLOADED = 'UNLOADED', VIEW_REGISTERED = 'VIEW_REGISTERED', VIEW_UNREGISTERED = 'VIEW_UNREGISTERED', ERROR_ADDED = 'ERROR_ADDED', ERRORS_REMOVED = 'ERRORS_REMOVED', PREFS_CHANGED = 'PREFS_CHANGED', WARNINGS_CHANGED = 'WARNINGS_CHANGED', COMMAND_ADDED = 'COMMAND_ADDED', COMMAND_REMOVED = 'COMMAND_REMOVED', PERMISSIONS_CHANGED = 'PERMISSIONS_CHANGED', SERVICE_WORKER_STARTED = 'SERVICE_WORKER_STARTED', SERVICE_WORKER_STOPPED = 'SERVICE_WORKER_STOPPED', } export type PackDirectoryResponse = { message: string, item_path: string, pem_path: string, override_flags: number, status: PackStatus, }; export type EventData = { event_type: EventType, item_id: string, extensionInfo?: ExtensionInfo, }; export type ErrorFileSource = { beforeHighlight: string, highlight: string, afterHighlight: string, }; export type LoadError = { error: string, path: string, source?: ErrorFileSource, retryGuid: string, }; export type RequestFileSourceProperties = { extensionId: string, pathSuffix: string, message: string, manifestKey?: string, manifestSpecific?: string, lineNumber?: number, }; export type RequestFileSourceResponse = { highlight: string, beforeHighlight: string, afterHighlight: string, title: string, message: string }; export type OpenDevToolsProperties = { extensionId?: string, renderViewId: number, renderProcessId: number, isServiceWorker?: boolean, incognito?: boolean, url?: string, lineNumber?: number, columnNumber?: number }; export type DeleteExtensionErrorsProperties = { extensionId: string, errorIds?: number[], type?: ErrorType, }; type VoidCallback = () => void; type StringCallback = (s: string) => void; export function addHostPermission( extensionId: string, host: string, callback: VoidCallback): void; export function autoUpdate(callback: VoidCallback): void; export function choosePath( selectType: SelectType, fileType: FileType, callback: StringCallback): void; export function deleteExtensionErrors( properties: DeleteExtensionErrorsProperties, callback?: VoidCallback): void; export function getExtensionsInfo( options: GetExtensionsInfoOptions, callback: (info: ExtensionInfo[]) => void): void; export function getExtensionSize(id: string, callback: StringCallback): void; export function getProfileConfiguration( callback: (info: ProfileInfo) => void): void; export function installDroppedFile(callback?: VoidCallback): void; export function loadUnpacked( options: LoadUnpackedOptions, callback: (error?: LoadError) => void): void; export function notifyDragInstallInProgress(): void; export function openDevTools( properties: OpenDevToolsProperties, callback?: VoidCallback): void; export function packDirectory( path: string, privateKeyPath: string, flags?: number, callback?: (response: PackDirectoryResponse) => void): void; export function reload( extensionId: string, options?: ReloadOptions, callback?: (error?: LoadError) => void): void; export function removeHostPermission( extensionId: string, host: string, callback: VoidCallback): void; export function repairExtension( extensionId: string, callback?: VoidCallback): void; export function requestFileSource( properties: RequestFileSourceProperties, callback: (response: RequestFileSourceResponse) => void): void; export function setShortcutHandlingSuspended( isSuspended: boolean, callback?: VoidCallback): void; export function showOptions(extensionId: string, callback?: VoidCallback): void; export function showPath(extensionId: string, callback?: VoidCallback): void; export function updateExtensionCommand( update: ExtensionCommandUpdate, callback?: VoidCallback): void; export function updateExtensionConfiguration( update: ExtensionConfigurationUpdate, callback?: VoidCallback): void; export function updateProfileConfiguration( update: ProfileConfigurationUpdate, callback?: VoidCallback): void; export const onItemStateChanged: ChromeEvent<(data: EventData) => void>; export const onProfileStateChanged: ChromeEvent<(info: ProfileInfo) => void>; } } }
the_stack
import React, { PureComponent } from 'react' import classnames from 'classnames' import { uuid } from 'utils/util' import { FormComponentProps } from 'antd/lib/form/Form' import { Form, Input, InputNumber, Select, Radio, Button, Icon } from 'antd' const Option = Select.Option const FormItem = Form.Item const RadioGroup = Radio.Group const RadioButton = Radio.Button const styles = require('./Workbench.less') interface IConditionalFilterPanelProps { filterTree: object name: string type: string onAddRoot: () => void onAddTreeNode: (tree) => void onDeleteTreeNode: () => void } interface IConditionalFilterPanelStates { flattenTree: object } export class ConditionalFilterPanel extends PureComponent<IConditionalFilterPanelProps & FormComponentProps, IConditionalFilterPanelStates> { constructor (props) { super(props) this.state = { flattenTree: null } } public componentWillMount () { const { filterTree } = this.props if (Object.keys(filterTree).length > 0) { this.setState({ flattenTree: this.initFlattenTree(filterTree, {}) }) } } public componentWillReceiveProps (nextProps) { const { filterTree } = nextProps const { flattenTree } = this.state if (Object.keys(filterTree).length > 0 && !flattenTree) { this.setState({ flattenTree: this.initFlattenTree(filterTree, {}) }) } } private initFlattenTree = (tree, flatten) => { flatten[tree.id] = tree if (tree.children) { tree.children.forEach((c) => { this.initFlattenTree(c, flatten) }) } return flatten } private renderFilterList = (filter, items) => { const { getFieldDecorator } = this.props.form const itemClass = classnames({ [styles.filterItem]: true, [styles.noPadding]: true, [styles.root]: filter.root }) return ( <div key={filter.id} className={itemClass}> <div className={styles.filterBlock}> <div className={styles.filterRel}> <FormItem className={styles.filterFormItem}> {getFieldDecorator(`${filter.id}Rel`, { initialValue: filter.rel })( <RadioGroup onChange={this.changeLinkRel(filter)} size="small"> <RadioButton value="and">And</RadioButton> <RadioButton value="or">Or</RadioButton> </RadioGroup> )} </FormItem> </div> <div className={styles.filterList}> {items} </div> </div> </div> ) } private renderFilterItem = (filter) => { const { form, name, type } = this.props const { getFieldDecorator } = form const itemClass = classnames({ [styles.filterItem]: true, [styles.root]: filter.root }) const forkButton = filter.root || ( <Button shape="circle" icon="fork" type="primary" onClick={this.forkNode(filter.id)} /> ) const operatorSelectOptions = this.generateFilterOperatorOptions(type) const valueInput = this.generateFilterValueInput(filter) return ( <div className={itemClass} key={filter.id}> <FormItem className={`${styles.filterFormItem} ${styles.filterFormKey}`}> <p>{name}</p> </FormItem> <FormItem className={`${styles.filterFormItem} ${styles.filterFormOperator}`}> {getFieldDecorator(`${filter.id}OperatorSelect`, { rules: [{ required: true, message: 'Operator 不能为空' }], initialValue: filter.filterOperator })( <Select onSelect={this.changeFilterOperator(filter)}> {operatorSelectOptions} </Select> )} </FormItem> <FormItem className={`${styles.filterFormItem} ${styles.filterFormInput}`}> {getFieldDecorator(`${filter.id}Input`, { rules: [{ required: true, message: 'Value 不能为空' }], initialValue: filter.filterValue })( valueInput )} </FormItem> <Button shape="circle" icon="plus" type="primary" onClick={this.addParallelNode(filter.id)} /> {forkButton} <Button shape="circle" icon="minus" onClick={this.deleteNode(filter.id)} /> </div> ) } private renderFilters (filter) { if (filter.type === 'link') { const items = filter.children.map((c) => this.renderFilters(c)) return this.renderFilterList(filter, items) } else if (filter.type === 'node') { return this.renderFilterItem(filter) } else { return ( <div className={styles.empty} onClick={this.props.onAddRoot}> <h3> <Icon type="plus" /> 点击添加 </h3> </div> ) } } private generateFilterOperatorOptions = (type) => { const operators = [ ['=', 'like', '>', '<', '>=', '<=', '!='], ['=', '>', '<', '>=', '<=', '!='] ] const stringOptions = operators[0].slice().map((o) => ( <Option key={o} value={o}>{o}</Option> )) const numbersAndDateOptions = operators[1].slice().map((o) => ( <Option key={o} value={o}>{o}</Option> )) if (type === 'number' || type === 'date') { return numbersAndDateOptions } else { return stringOptions } } private generateFilterValueInput = (filter) => { const { type } = this.props const stringInput = ( <Input onChange={this.changeStringFilterValue(filter)} /> ) const numberInput = ( <InputNumber className={styles.inputNumber} onChange={this.changeNumberFilterValue(filter)} /> ) if (type === 'number') { return numberInput } else { return stringInput } } private addParallelNode = (nodeId) => () => { const { flattenTree } = this.state const currentNode = flattenTree[nodeId] const newNode = { id: uuid(8, 16), type: 'node', parent: void 0 } if (currentNode.parent) { const parent = flattenTree[currentNode.parent] newNode.parent = parent.id parent.children.push(newNode) flattenTree[newNode.id] = newNode this.setState({ flattenTree: {...flattenTree} }) } else { const parent = { id: uuid(8, 16), root: true, type: 'link', rel: 'and', children: [] } newNode.parent = parent.id parent.children.push(currentNode) parent.children.push(newNode) delete currentNode.root delete flattenTree[currentNode.id] currentNode.id = uuid(8, 16) currentNode.parent = parent.id flattenTree[currentNode.id] = currentNode flattenTree[parent.id] = parent flattenTree[newNode.id] = newNode this.setState({ flattenTree: {...flattenTree} }) this.props.onAddTreeNode(parent) } } private forkNode = (nodeId) => () => { const { flattenTree } = this.state const currentNode = flattenTree[nodeId] const cloneNode = { ...currentNode, id: uuid(8, 16), parent: currentNode.id } const newNode = { id: uuid(8, 16), type: 'node', parent: currentNode.id } currentNode.type = 'link' currentNode.rel = 'and' currentNode.children = [cloneNode, newNode] flattenTree[cloneNode.id] = cloneNode flattenTree[newNode.id] = newNode this.setState({ flattenTree: {...flattenTree} }) } private deleteNode = (nodeId) => () => { const { flattenTree } = this.state const currentNode = flattenTree[nodeId] delete flattenTree[nodeId] if (currentNode.parent) { const parent = flattenTree[currentNode.parent] parent.children = parent.children.filter((c) => c.id !== nodeId) if (parent.children.length === 1) { const onlyChild = parent.children[0] this.refreshTreeId(onlyChild) const originParentId = parent.id parent.id = onlyChild.id parent.type = onlyChild.type parent.rel = onlyChild.rel parent.filterKey = onlyChild.filterKey parent.filterOperator = onlyChild.filterOperator parent.filterValue = onlyChild.filterValue parent.children = onlyChild.children delete flattenTree[originParentId] flattenTree[onlyChild.id] = parent } this.setState({ flattenTree: {...flattenTree} }) } else { this.setState({ flattenTree: null }) this.props.onDeleteTreeNode() } } private refreshTreeId = (treeNode) => { const { flattenTree } = this.state const oldId = treeNode.id delete flattenTree[oldId] treeNode.id = uuid(8, 16) flattenTree[treeNode.id] = treeNode if (treeNode.children) { treeNode.children.forEach((c) => { c.parent = treeNode.id this.refreshTreeId(c) }) } } private changeLinkRel = (filter) => (e) => { filter.rel = e.target.value } // private changeFilterKey = (filter) => (val) => { // const keyAndType = val.split(':') // filter.filterKey = keyAndType[0] // filter.filterType = keyAndType[1] // filter.filterValue = '' // filter.inputUuid = uuid(8, 16) // } private changeFilterOperator = (filter) => (val) => { filter.filterOperator = val } private changeStringFilterValue = (filter) => (event) => { filter.filterValue = event.target.value } private changeNumberFilterValue = (filter) => (val) => { filter.filterValue = val } private changeDateFilterValue = (filter) => (date) => { filter.filterValue = date } public resetTree = () => { this.setState({ flattenTree: null }) } public render () { const { filterTree } = this.props return ( <div className={styles.conditionalFilterPanel}> <Form className={styles.conditionalFilterForm}> {this.renderFilters(filterTree)} </Form> </div> ) } } export default Form.create<IConditionalFilterPanelProps & FormComponentProps>()(ConditionalFilterPanel)
the_stack
import {Bounds} from '../css/layout/bounds'; import {BACKGROUND_ORIGIN} from '../css/property-descriptors/background-origin'; import {ElementContainer} from '../dom/element-container'; import {BACKGROUND_SIZE, BackgroundSizeInfo} from '../css/property-descriptors/background-size'; import {Vector} from './vector'; import {BACKGROUND_REPEAT} from '../css/property-descriptors/background-repeat'; import {getAbsoluteValue, getAbsoluteValueForTuple, isLengthPercentage} from '../css/types/length-percentage'; import {CSSValue, isIdentToken} from '../css/syntax/parser'; import {contentBox, paddingBox} from './box-sizing'; import {Path} from './path'; import {BACKGROUND_CLIP} from '../css/property-descriptors/background-clip'; export const calculateBackgroundPositioningArea = ( backgroundOrigin: BACKGROUND_ORIGIN, element: ElementContainer ): Bounds => { if (backgroundOrigin === BACKGROUND_ORIGIN.BORDER_BOX) { return element.bounds; } if (backgroundOrigin === BACKGROUND_ORIGIN.CONTENT_BOX) { return contentBox(element); } return paddingBox(element); }; export const calculateBackgroundPaintingArea = (backgroundClip: BACKGROUND_CLIP, element: ElementContainer): Bounds => { if (backgroundClip === BACKGROUND_CLIP.BORDER_BOX) { return element.bounds; } if (backgroundClip === BACKGROUND_CLIP.CONTENT_BOX) { return contentBox(element); } return paddingBox(element); }; export const calculateBackgroundRendering = ( container: ElementContainer, index: number, intrinsicSize: [number | null, number | null, number | null] ): [Path[], number, number, number, number] => { const backgroundPositioningArea = calculateBackgroundPositioningArea( getBackgroundValueForIndex(container.styles.backgroundOrigin, index), container ); const backgroundPaintingArea = calculateBackgroundPaintingArea( getBackgroundValueForIndex(container.styles.backgroundClip, index), container ); const backgroundImageSize = calculateBackgroundSize( getBackgroundValueForIndex(container.styles.backgroundSize, index), intrinsicSize, backgroundPositioningArea ); const [sizeWidth, sizeHeight] = backgroundImageSize; const position = getAbsoluteValueForTuple( getBackgroundValueForIndex(container.styles.backgroundPosition, index), backgroundPositioningArea.width - sizeWidth, backgroundPositioningArea.height - sizeHeight ); const path = calculateBackgroundRepeatPath( getBackgroundValueForIndex(container.styles.backgroundRepeat, index), position, backgroundImageSize, backgroundPositioningArea, backgroundPaintingArea ); const offsetX = Math.round(backgroundPositioningArea.left + position[0]); const offsetY = Math.round(backgroundPositioningArea.top + position[1]); return [path, offsetX, offsetY, sizeWidth, sizeHeight]; }; export const isAuto = (token: CSSValue): boolean => isIdentToken(token) && token.value === BACKGROUND_SIZE.AUTO; const hasIntrinsicValue = (value: number | null): value is number => typeof value === 'number'; export const calculateBackgroundSize = ( size: BackgroundSizeInfo[], [intrinsicWidth, intrinsicHeight, intrinsicProportion]: [number | null, number | null, number | null], bounds: Bounds ): [number, number] => { const [first, second] = size; if (!first) { return [0, 0]; } if (isLengthPercentage(first) && second && isLengthPercentage(second)) { return [getAbsoluteValue(first, bounds.width), getAbsoluteValue(second, bounds.height)]; } const hasIntrinsicProportion = hasIntrinsicValue(intrinsicProportion); if (isIdentToken(first) && (first.value === BACKGROUND_SIZE.CONTAIN || first.value === BACKGROUND_SIZE.COVER)) { if (hasIntrinsicValue(intrinsicProportion)) { const targetRatio = bounds.width / bounds.height; return targetRatio < intrinsicProportion !== (first.value === BACKGROUND_SIZE.COVER) ? [bounds.width, bounds.width / intrinsicProportion] : [bounds.height * intrinsicProportion, bounds.height]; } return [bounds.width, bounds.height]; } const hasIntrinsicWidth = hasIntrinsicValue(intrinsicWidth); const hasIntrinsicHeight = hasIntrinsicValue(intrinsicHeight); const hasIntrinsicDimensions = hasIntrinsicWidth || hasIntrinsicHeight; // If the background-size is auto or auto auto: if (isAuto(first) && (!second || isAuto(second))) { // If the image has both horizontal and vertical intrinsic dimensions, it's rendered at that size. if (hasIntrinsicWidth && hasIntrinsicHeight) { return [intrinsicWidth as number, intrinsicHeight as number]; } // If the image has no intrinsic dimensions and has no intrinsic proportions, // it's rendered at the size of the background positioning area. if (!hasIntrinsicProportion && !hasIntrinsicDimensions) { return [bounds.width, bounds.height]; } // TODO If the image has no intrinsic dimensions but has intrinsic proportions, it's rendered as if contain had been specified instead. // If the image has only one intrinsic dimension and has intrinsic proportions, it's rendered at the size corresponding to that one dimension. // The other dimension is computed using the specified dimension and the intrinsic proportions. if (hasIntrinsicDimensions && hasIntrinsicProportion) { const width = hasIntrinsicWidth ? (intrinsicWidth as number) : (intrinsicHeight as number) * (intrinsicProportion as number); const height = hasIntrinsicHeight ? (intrinsicHeight as number) : (intrinsicWidth as number) / (intrinsicProportion as number); return [width, height]; } // If the image has only one intrinsic dimension but has no intrinsic proportions, // it's rendered using the specified dimension and the other dimension of the background positioning area. const width = hasIntrinsicWidth ? (intrinsicWidth as number) : bounds.width; const height = hasIntrinsicHeight ? (intrinsicHeight as number) : bounds.height; return [width, height]; } // If the image has intrinsic proportions, it's stretched to the specified dimension. // The unspecified dimension is computed using the specified dimension and the intrinsic proportions. if (hasIntrinsicProportion) { let width = 0; let height = 0; if (isLengthPercentage(first)) { width = getAbsoluteValue(first, bounds.width); } else if (isLengthPercentage(second)) { height = getAbsoluteValue(second, bounds.height); } if (isAuto(first)) { width = height * (intrinsicProportion as number); } else if (!second || isAuto(second)) { height = width / (intrinsicProportion as number); } return [width, height]; } // If the image has no intrinsic proportions, it's stretched to the specified dimension. // The unspecified dimension is computed using the image's corresponding intrinsic dimension, // if there is one. If there is no such intrinsic dimension, // it becomes the corresponding dimension of the background positioning area. let width = null; let height = null; if (isLengthPercentage(first)) { width = getAbsoluteValue(first, bounds.width); } else if (second && isLengthPercentage(second)) { height = getAbsoluteValue(second, bounds.height); } if (width !== null && (!second || isAuto(second))) { height = hasIntrinsicWidth && hasIntrinsicHeight ? (width / (intrinsicWidth as number)) * (intrinsicHeight as number) : bounds.height; } if (height !== null && isAuto(first)) { width = hasIntrinsicWidth && hasIntrinsicHeight ? (height / (intrinsicHeight as number)) * (intrinsicWidth as number) : bounds.width; } if (width !== null && height !== null) { return [width, height]; } throw new Error(`Unable to calculate background-size for element`); }; export const getBackgroundValueForIndex = <T>(values: T[], index: number): T => { const value = values[index]; if (typeof value === 'undefined') { return values[0]; } return value; }; export const calculateBackgroundRepeatPath = ( repeat: BACKGROUND_REPEAT, [x, y]: [number, number], [width, height]: [number, number], backgroundPositioningArea: Bounds, backgroundPaintingArea: Bounds ): [Vector, Vector, Vector, Vector] => { switch (repeat) { case BACKGROUND_REPEAT.REPEAT_X: return [ new Vector(Math.round(backgroundPositioningArea.left), Math.round(backgroundPositioningArea.top + y)), new Vector( Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width), Math.round(backgroundPositioningArea.top + y) ), new Vector( Math.round(backgroundPositioningArea.left + backgroundPositioningArea.width), Math.round(height + backgroundPositioningArea.top + y) ), new Vector( Math.round(backgroundPositioningArea.left), Math.round(height + backgroundPositioningArea.top + y) ) ]; case BACKGROUND_REPEAT.REPEAT_Y: return [ new Vector(Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top)), new Vector( Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top) ), new Vector( Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top) ), new Vector( Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.height + backgroundPositioningArea.top) ) ]; case BACKGROUND_REPEAT.NO_REPEAT: return [ new Vector( Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top + y) ), new Vector( Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top + y) ), new Vector( Math.round(backgroundPositioningArea.left + x + width), Math.round(backgroundPositioningArea.top + y + height) ), new Vector( Math.round(backgroundPositioningArea.left + x), Math.round(backgroundPositioningArea.top + y + height) ) ]; default: return [ new Vector(Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.top)), new Vector( Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width), Math.round(backgroundPaintingArea.top) ), new Vector( Math.round(backgroundPaintingArea.left + backgroundPaintingArea.width), Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top) ), new Vector( Math.round(backgroundPaintingArea.left), Math.round(backgroundPaintingArea.height + backgroundPaintingArea.top) ) ]; } };
the_stack
import cp from 'child_process'; import http from 'http'; import https from 'https'; import net from 'net'; import os from 'os'; import path from 'path'; import Koa from 'koa'; import { Injector, ConstructorOf } from '@opensumi/di'; import { WebSocketHandler } from '@opensumi/ide-connection/lib/node'; import { MaybePromise, ContributionProvider, createContributionProvider, isWindows } from '@opensumi/ide-core-common'; import { LogLevel, ILogServiceManager, ILogService, SupportLogNamespace, StoragePaths, } from '@opensumi/ide-core-common'; import { DEFAULT_OPENVSX_REGISTRY } from '@opensumi/ide-core-common/lib/const'; import { createServerConnection2, createNetServerConnection, RPCServiceCenter } from '../connection'; import { NodeModule } from '../node-module'; import { injectInnerProviders } from './inner-providers'; export type ModuleConstructor = ConstructorOf<NodeModule>; export type ContributionConstructor = ConstructorOf<ServerAppContribution>; export const AppConfig = Symbol('AppConfig'); export interface MarketplaceRequest { path?: string; headers?: { [header: string]: string | string[] | undefined; }; } export interface MarketplaceConfig { endpoint: string; // 插件市场下载到本地的位置,默认 ~/.sumi/extensions extensionDir: string; // 是否显示内置插件,默认隐藏 showBuiltinExtensions: boolean; // 插件市场中申请到的客户端的 accountId accountId: string; // 插件市场中申请到的客户端的 masterKey masterKey: string; // 插件市场参数转换函数 transformRequest?: (request: MarketplaceRequest) => MarketplaceRequest; // 在热门插件、搜索插件时忽略的插件 id ignoreId: string[]; } interface Config { /** * 初始化的 DI 实例,一般可在外部进行 DI 初始化之后传入,便于提前进行一些依赖的初始化 */ injector: Injector; /** * 设置落盘日志级别,默认为 Info 级别的log落盘 */ logLevel?: LogLevel; /** * 设置日志的目录,默认:~/.sumi/logs */ logDir?: string; /** * @deprecated 可通过在传入的 `injector` 初始化 `ILogService` 进行实现替换 * 外部设置的 ILogService,替换默认的 logService */ LogServiceClass?: ConstructorOf<ILogService>; /** * 启用插件进程的最大个数 */ maxExtProcessCount?: number; /** * 插件日志自定义实现路径 */ extLogServiceClassPath?: string; /** * 插件进程关闭时间 */ processCloseExitThreshold?: number; /** * 终端 pty 进程退出时间 */ terminalPtyCloseThreshold?: number; /** * 访问静态资源允许的 origin */ staticAllowOrigin?: string; /** * 访问静态资源允许的路径,用于配置静态资源的白名单规则 */ staticAllowPath?: string[]; /** * 文件服务禁止访问的路径,使用 glob 匹配 */ blockPatterns?: string[]; /** * 获取插件进程句柄方法 * @deprecated 自测 1.30.0 后,不在提供给 IDE 后端发送插件进程的方法 */ onDidCreateExtensionHostProcess?: (cp: cp.ChildProcess) => void; /** * 插件 Node 进程入口文件 */ extHost?: string; /** * 插件进程存放用于通信的 sock 地址 * 默认为 /tmp */ extHostIPCSockPath?: string; /** * 插件进程 fork 配置 */ extHostForkOptions?: Partial<cp.ForkOptions>; /** * 配置关闭 keytar 校验能力,默认开启 */ disableKeytar?: boolean; } export interface AppConfig extends Partial<Config> { marketplace: MarketplaceConfig; } export interface IServerAppOpts extends Partial<Config> { modules?: ModuleConstructor[]; contributions?: ContributionConstructor[]; modulesInstances?: NodeModule[]; webSocketHandler?: WebSocketHandler[]; marketplace?: Partial<MarketplaceConfig>; use?(middleware: Koa.Middleware<Koa.ParameterizedContext<any, any>>): void; } export const ServerAppContribution = Symbol('ServerAppContribution'); export interface ServerAppContribution { initialize?(app: IServerApp): MaybePromise<void>; onStart?(app: IServerApp): MaybePromise<void>; onStop?(app: IServerApp): MaybePromise<void>; onWillUseElectronMain?(): void; } export interface IServerApp { use(middleware: Koa.Middleware<Koa.ParameterizedContext<any, any>>): void; start(server: http.Server | https.Server): Promise<void>; } export class ServerApp implements IServerApp { private injector: Injector; private config: AppConfig; private logger: ILogService; private webSocketHandler: WebSocketHandler[]; private modulesInstances: NodeModule[]; use: (middleware: Koa.Middleware<Koa.ParameterizedContext<any, any>>) => void; protected contributionsProvider: ContributionProvider<ServerAppContribution>; /** * 启动初始化 * 1. 绑定 process 报错处理 * 2. 初始化内置的 Provider * 3. 获取 Modules 的实例 * 4. 设置默认的实例 * @param opts */ constructor(opts: IServerAppOpts) { this.injector = opts.injector || new Injector(); this.webSocketHandler = opts.webSocketHandler || []; // 使用外部传入的中间件 this.use = opts.use || ((middleware) => null); this.config = { injector: this.injector, logDir: opts.logDir, logLevel: opts.logLevel, LogServiceClass: opts.LogServiceClass, marketplace: Object.assign( { endpoint: DEFAULT_OPENVSX_REGISTRY, extensionDir: path.join( os.homedir(), ...(isWindows ? [StoragePaths.WINDOWS_APP_DATA_DIR, StoragePaths.WINDOWS_ROAMING_DIR] : ['']), StoragePaths.DEFAULT_STORAGE_DIR_NAME, StoragePaths.MARKETPLACE_DIR, ), showBuiltinExtensions: false, accountId: '', masterKey: '', ignoreId: [], }, opts.marketplace, ), processCloseExitThreshold: opts.processCloseExitThreshold, terminalPtyCloseThreshold: opts.terminalPtyCloseThreshold, staticAllowOrigin: opts.staticAllowOrigin, staticAllowPath: opts.staticAllowPath, extLogServiceClassPath: opts.extLogServiceClassPath, maxExtProcessCount: opts.maxExtProcessCount, onDidCreateExtensionHostProcess: opts.onDidCreateExtensionHostProcess, extHost: process.env.EXTENSION_HOST_ENTRY || opts.extHost, blockPatterns: opts.blockPatterns, extHostIPCSockPath: opts.extHostIPCSockPath, extHostForkOptions: opts.extHostForkOptions, }; this.bindProcessHandler(); this.initBaseProvider(opts); this.createNodeModules(opts.modules, opts.modulesInstances); this.logger = this.injector.get(ILogServiceManager).getLogger(SupportLogNamespace.App); this.contributionsProvider = this.injector.get(ServerAppContribution); } /** * 将被依赖但未被加入modules的模块加入到待加载模块最后 */ public resolveModuleDeps(moduleConstructor: ModuleConstructor, modules: any[]) { const dependencies = Reflect.getMetadata('dependencies', moduleConstructor) as []; if (dependencies) { dependencies.forEach((dep) => { if (modules.indexOf(dep) === -1) { modules.push(dep); } }); } } private get contributions(): ServerAppContribution[] { return this.contributionsProvider.getContributions(); } private initBaseProvider(opts: IServerAppOpts) { // 创建 contributionsProvider createContributionProvider(this.injector, ServerAppContribution); this.injector.addProviders({ token: AppConfig, useValue: this.config, }); injectInnerProviders(this.injector); } private async initializeContribution() { for (const contribution of this.contributions) { if (contribution.initialize) { try { await contribution.initialize(this); } catch (error) { this.logger.error('Could not initialize contribution', error); } } } } private async startContribution() { for (const contrib of this.contributions) { if (contrib.onStart) { try { await contrib.onStart(this); } catch (error) { this.logger.error('Could not start contribution', error); } } } } async start( server: http.Server | https.Server | net.Server, serviceHandler?: (serviceCenter: RPCServiceCenter) => void, ) { await this.initializeContribution(); let serviceCenter; if (serviceHandler) { serviceCenter = new RPCServiceCenter(); serviceHandler(serviceCenter); } else { if (server instanceof http.Server || server instanceof https.Server) { // 创建 websocket 通道 serviceCenter = createServerConnection2(server, this.injector, this.modulesInstances, this.webSocketHandler); } else if (server instanceof net.Server) { serviceCenter = createNetServerConnection(server, this.injector, this.modulesInstances); } } // TODO: 每次链接来的时候绑定一次,或者是服务获取的时候多实例化出来 // bindModuleBackService(this.injector, this.modulesInstances, serviceCenter); await this.startContribution(); } private async onStop() { for (const contrib of this.contributions) { if (contrib.onStop) { try { await contrib.onStop(this); } catch (error) { this.logger.error('Could not stop contribution', error); } } } } /** * 绑定 process 退出逻辑 */ private bindProcessHandler() { process.on('uncaughtException', (error) => { if (error) { this.logger.error('Uncaught Exception: ', error.toString()); if (error.stack) { this.logger.error(error.stack); } } }); // Handles normal process termination. process.on('exit', () => { this.logger.log('process exit'); }); // Handles `Ctrl+C`. process.on('SIGINT', async () => { this.logger.log('process SIGINT'); await this.onStop(); this.logger.log('process SIGINT DONE'); process.exit(0); }); // Handles `kill pid`. process.on('SIGTERM', async () => { this.logger.log('process SIGTERM'); await this.onStop(); this.logger.log('process SIGTERM DONE'); process.exit(0); }); } /** * 收集 module 实例 * @param Constructors * @param modules */ private createNodeModules(Constructors: ModuleConstructor[] = [], modules: NodeModule[] = []) { const allModules = [...modules]; Constructors.forEach((c) => { this.resolveModuleDeps(c, Constructors); }); for (const Constructor of Constructors) { allModules.push(this.injector.get(Constructor)); } for (const instance of allModules) { if (instance.providers) { this.injector.addProviders(...instance.providers); } if (instance.contributionProvider) { if (Array.isArray(instance.contributionProvider)) { for (const contributionProvider of instance.contributionProvider) { createContributionProvider(this.injector, contributionProvider); } } else { createContributionProvider(this.injector, instance.contributionProvider); } } } this.modulesInstances = allModules; } }
the_stack
import {runIfMain} from "../../../deps/mocha.ts"; import {expect} from "../../../deps/chai.ts"; import {closeTestingConnections, createTestingConnections, reloadTestingDatabases} from "../../../utils/test-utils.ts"; import {Connection} from "../../../../src/connection/Connection.ts"; import {User} from "./entity/User.ts"; import {Category} from "./entity/Category.ts"; import {Post} from "./entity/Post.ts"; import {Photo} from "./entity/Photo.ts"; import {Counters} from "./entity/Counters.ts"; import {FindRelationsNotFoundError} from "../../../../src/error/FindRelationsNotFoundError.ts"; describe("repository > find options > relations", () => { // ------------------------------------------------------------------------- // Configuration // ------------------------------------------------------------------------- let connections: Connection[]; before(async () => connections = await createTestingConnections({ entities: [Category, Counters, Photo, Post, User], })); beforeEach(() => reloadTestingDatabases(connections)); after(() => closeTestingConnections(connections)); // ------------------------------------------------------------------------- // Setup // ------------------------------------------------------------------------- beforeEach(() => Promise.all(connections.map(async connection => { const postUser = new User(); postUser.name = "Timber"; await connection.manager.save(postUser); const postCountersUser = new User(); postCountersUser.name = "Post Counters Timber"; await connection.manager.save(postCountersUser); const photoCountersUser = new User(); photoCountersUser.name = "Photo Counters Timber"; await connection.manager.save(photoCountersUser); const photoUser = new User(); photoUser.name = "Photo Timber"; await connection.manager.save(photoUser); const category1 = new Category(); category1.name = "category1"; await connection.manager.save(category1); const category2 = new Category(); category2.name = "category2"; await connection.manager.save(category2); const photo1 = new Photo(); photo1.filename = "photo1.jpg"; photo1.counters = new Counters(); photo1.counters.stars = 2; photo1.counters.commentCount = 19; photo1.counters.author = photoCountersUser; photo1.user = photoUser; await connection.manager.save(photo1); const photo2 = new Photo(); photo2.filename = "photo2.jpg"; photo2.counters = new Counters(); photo2.counters.stars = 3; photo2.counters.commentCount = 20; await connection.manager.save(photo2); const photo3 = new Photo(); photo3.filename = "photo3.jpg"; photo3.counters = new Counters(); photo3.counters.stars = 4; photo3.counters.commentCount = 21; await connection.manager.save(photo3); const postCounters = new Counters(); postCounters.commentCount = 1; postCounters.author = postCountersUser; postCounters.stars = 101; const post = new Post(); post.title = "About Timber"; post.counters = postCounters; post.user = postUser; post.categories = [category1, category2]; post.photos = [photo1, photo2, photo3]; await connection.manager.save(post); }))); // ------------------------------------------------------------------------- // Specifications // ------------------------------------------------------------------------- it("should not any relations if they are not specified", () => Promise.all(connections.map(async connection => { const loadedPost = await connection.getRepository(Post).findOne(1); loadedPost!.should.be.eql({ id: 1, title: "About Timber", counters: { commentCount: 1, stars: 101 } }); }))); it("should load specified relations case 1", () => Promise.all(connections.map(async connection => { const loadedPost = await connection.getRepository(Post).findOne(1, { relations: ["photos"] }); loadedPost!.id.should.be.equal(1); loadedPost!.title.should.be.equal("About Timber"); loadedPost!.counters.commentCount.should.be.equal(1); loadedPost!.counters.stars.should.be.equal(101); loadedPost!.photos.should.deep.include({ id: 1, filename: "photo1.jpg", counters: { stars: 2, commentCount: 19 } }); loadedPost!.photos.should.deep.include({ id: 2, filename: "photo2.jpg", counters: { stars: 3, commentCount: 20 } }); loadedPost!.photos.should.deep.include({ id: 3, filename: "photo3.jpg", counters: { stars: 4, commentCount: 21 } }); }))); it("should load specified relations case 2", () => Promise.all(connections.map(async connection => { const loadedPost = await connection.getRepository(Post).findOne(1, { relations: ["photos", "user", "categories"] }); loadedPost!.id.should.be.equal(1); loadedPost!.title.should.be.equal("About Timber"); loadedPost!.counters.commentCount.should.be.equal(1); loadedPost!.counters.stars.should.be.equal(101); loadedPost!.photos.should.deep.include({ id: 1, filename: "photo1.jpg", counters: { stars: 2, commentCount: 19 } }); loadedPost!.photos.should.deep.include({ id: 2, filename: "photo2.jpg", counters: { stars: 3, commentCount: 20 } }); loadedPost!.photos.should.deep.include({ id: 3, filename: "photo3.jpg", counters: { stars: 4, commentCount: 21 } }); loadedPost!.user.should.be.eql({ id: 1, name: "Timber" }); loadedPost!.categories.should.deep.include({ id: 1, name: "category1" }); loadedPost!.categories.should.deep.include({ id: 2, name: "category2" }); }))); it("should load specified relations and their sub-relations case 1", () => Promise.all(connections.map(async connection => { const loadedPost = await connection.getRepository(Post).findOne(1, { relations: ["photos", "user", "categories", "photos.user"] }); loadedPost!.id.should.be.equal(1); loadedPost!.title.should.be.equal("About Timber"); loadedPost!.counters.commentCount.should.be.equal(1); loadedPost!.counters.stars.should.be.equal(101); loadedPost!.photos.should.deep.include({ id: 1, filename: "photo1.jpg", counters: { stars: 2, commentCount: 19 }, user: { id: 4, name: "Photo Timber" } }); loadedPost!.photos.should.deep.include({ id: 2, filename: "photo2.jpg", counters: { stars: 3, commentCount: 20 }, user: null }); loadedPost!.photos.should.deep.include({ id: 3, filename: "photo3.jpg", counters: { stars: 4, commentCount: 21 }, user: null }); loadedPost!.user.should.be.eql({ id: 1, name: "Timber" }); loadedPost!.categories.should.deep.include({ id: 1, name: "category1" }); loadedPost!.categories.should.deep.include({ id: 2, name: "category2" }); }))); it("should load specified relations and their sub-relations case 2", () => Promise.all(connections.map(async connection => { const loadedPost = await connection.getRepository(Post).findOne(1, { relations: ["photos", "user", "photos.user", "counters.author"] }); loadedPost!.id.should.be.equal(1); loadedPost!.title.should.be.equal("About Timber"); loadedPost!.counters.commentCount.should.be.equal(1); loadedPost!.counters.stars.should.be.equal(101); loadedPost!.photos.should.deep.include({ id: 1, filename: "photo1.jpg", counters: { stars: 2, commentCount: 19 }, user: { id: 4, name: "Photo Timber" } }); loadedPost!.photos.should.deep.include({ id: 2, filename: "photo2.jpg", counters: { stars: 3, commentCount: 20 }, user: null }); loadedPost!.photos.should.deep.include({ id: 3, filename: "photo3.jpg", counters: { stars: 4, commentCount: 21 }, user: null }); loadedPost!.user.should.be.eql({ id: 1, name: "Timber" }); loadedPost!.counters.author.should.be.eql({ id: 2, name: "Post Counters Timber" }); }))); it("should load specified relations and their sub-relations case 3", () => Promise.all(connections.map(async connection => { const loadedPost = await connection.getRepository(Post).findOne(1, { relations: ["photos", "user", "photos.user", "counters.author", "photos.counters.author"] }); loadedPost!.id.should.be.equal(1); loadedPost!.title.should.be.equal("About Timber"); loadedPost!.counters.commentCount.should.be.equal(1); loadedPost!.counters.stars.should.be.equal(101); loadedPost!.photos.should.deep.include({ id: 1, filename: "photo1.jpg", counters: { stars: 2, commentCount: 19, author: { id: 3, name: "Photo Counters Timber" } }, user: { id: 4, name: "Photo Timber" } }); loadedPost!.photos.should.deep.include({ id: 2, filename: "photo2.jpg", counters: { stars: 3, commentCount: 20, author: null }, user: null }); loadedPost!.photos.should.deep.include({ id: 3, filename: "photo3.jpg", counters: { stars: 4, commentCount: 21, author: null }, user: null }); loadedPost!.user.should.be.eql({ id: 1, name: "Timber" }); loadedPost!.counters.author.should.be.eql({ id: 2, name: "Post Counters Timber" }); }))); it("should throw error if specified relations were not found case 1", () => Promise.all(connections.map(async connection => { let error; try { await connection.getRepository(Post).findOne(1, { relations: ["photos2"] }); } catch (err) { error = err; } expect(error).to.be.instanceOf(FindRelationsNotFoundError); }))); it("should throw error if specified relations were not found case 2", () => Promise.all(connections.map(async connection => { let error; try { await connection.getRepository(Post).findOne(1, { relations: ["photos", "counters.author2"] }); } catch (err) { error = err; } expect(error).to.be.instanceOf(FindRelationsNotFoundError); }))); it("should throw error if specified relations were not found case 3", () => Promise.all(connections.map(async connection => { let error; try { await connection.getRepository(Post).findOne(1, { relations: ["photos", "counters2.author"] }); } catch (err) { error = err; } expect(error).to.be.instanceOf(FindRelationsNotFoundError); }))); it("should throw error if specified relations were not found case 4", () => Promise.all(connections.map(async connection => { let error; try { await connection.getRepository(Post).findOne(1, { relations: ["photos", "photos.user.haha"] }); } catch (err) { error = err; } expect(error).to.be.instanceOf(FindRelationsNotFoundError); }))); it("should throw error if specified relations were not found case 5", () => Promise.all(connections.map(async connection => { let error; try { await connection.getRepository(Post).findOne(1, { relations: ["questions"] }); } catch (err) { error = err; } expect(error).to.be.instanceOf(FindRelationsNotFoundError); }))); it("should throw error if specified relations were not found case 6", () => Promise.all(connections.map(async connection => { let error; try { await connection.getRepository(Post).findOne(1, { relations: ["questions.haha"] }); } catch (err) { error = err; } expect(error).to.be.instanceOf(FindRelationsNotFoundError); }))); }); runIfMain(import.meta);
the_stack
import { Component, OnInit, Input,ChangeDetectorRef } from '@angular/core'; import { PaginationInstance } from 'ngx-pagination'; import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; import { DataApiService } from '../../../shared/data-api.service'; import { RestApiService } from '../../../shared/rest-api.service'; import { ResponseOptions } from '@angular/http/src/base_response_options'; import 'chartjs-plugin-streaming'; import { ChartsModule } from 'ng2-charts'; import { DatePipe } from '@angular/common'; @Component({ selector: 'app-trends', templateUrl: './trends.component.html', styles:[` .table tr.active td { background-color:#dummy56 !important; color: white; }`] }) export class TrendsComponent implements OnInit { selectedRow ; notifications =[]; selected_value = ''; id : any; noti : any; activatedTabs = {}; anamolyException = []; containerName = ''; instanceName = ''; period = ''; release1 = ''; release2 = ''; testing = ''; instanceList = []; selectedRange = { 'x': '', 'y': '' } elkIndex = ''; elkHost = ''; elkPort : any; periodList = ["Last30Min" , "Last1Hr" , "Last5Hr" , "Last1Day" , "Last1Week" , "Last1Month"]; lineData = { 'data' : [], 'label' : '' }; cpulineData = { 'data' : [], 'label' : '' }; @Input() trendsAppName: string; @Input() containerList = []; // Modal public myModal; // lineChart public lineChartData: Array<any> = [ // {data: [65, 59, 80, 81, 56, 55, 40], label: 'IDPLINV01'} ]; public lineCPUChardData: Array<any> = []; public lineChartLabels: Array<any> = [] ;// = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; chartColors = { red: 'rgb(255, 99, 132)', orange: 'rgb(255, 159, 64)', yellow: 'rgb(255, 205, 86)', green: 'rgb(75, 192, 192)', blue: 'rgb(54, 162, 235)', purple: 'rgb(153, 102, 255)', grey: 'rgb(201, 203, 207)' }; datasets = [{ label: 'Memory Usage(in MBs)', backgroundColor: this.chartColors.red, borderColor: this.chartColors.red, fill: false, lineTension: 0, borderDash: [8, 4], type: 'line', data: [], pointRadius: 5, pointHoverRadius: 15, pointHitRadius: 10, pointHoverBackgroundColor: this.chartColors.red }]; CPUdatasets = [{ label: 'CPU Usage(in %)', backgroundColor: this.chartColors.blue, borderColor: this.chartColors.blue, fill: false, lineTension: 0, borderDash: [8, 4], type: 'line', data: [], pointRadius: 5, pointHoverRadius: 15, pointHitRadius: 10, pointHoverBackgroundColor: this.chartColors.red }]; options = { // responsive: true, // maintainAspectRatio: false, animation: { duration: 0 // general animation time }, responsiveAnimationDuration: 0, // animation duration after a resize scales: { xAxes: [{ type: 'realtime', // x axis will auto-scroll from right to left scaleLabel: { display: true, labelString: 'Time' } }], yAxes: [{ type: 'linear', display: true, scaleLabel: { display: true, labelString: 'Value' } }] }, tooltips: { mode: 'nearest', intersect: false }, hover: { mode: 'nearest', intersect: false, animationDuration: 0 // duration of animations when hovering an item }, plugins: { streaming: { // enabled by default duration: 360000, // data in the past 20000 ms will be displayed refresh: 10000, // onRefresh callback will be called every 1000 ms delay: 10000, // delay of 1000 ms, so upcoming values are known before plotting a line frameRate: 20, // chart is drawn n times every second pause: false, // chart is not paused } } }; public config: PaginationInstance = { // id: 'advanced', itemsPerPage: 5, currentPage: 1 }; public labels: any = { previousLabel: 'Previous', nextLabel: 'Next', screenReaderPaginationLabel: 'Pagination', screenReaderPageLabel: 'page', screenReaderCurrentLabel: `You're on page` }; public lineChartColours: Array<any> = [ { // grey backgroundColor: 'rgba(148,159,177,0.2)', borderColor: 'rgba(148,159,177,1)', pointBackgroundColor: 'rgba(148,159,177,1)', pointBorderColor: '#fff', pointHoverBackgroundColor: '#fff', pointHoverBorderColor: 'rgba(148,159,177,0.8)', pointRadius : 0, fill : false } ]; public lineChartLegend = true; public lineChartType = 'line'; constructor(private dataService: DataApiService, private restService: RestApiService, private changeDetectorRef: ChangeDetectorRef, public datepipe: DatePipe ) { } ngOnInit() { this.activatedTabs = this.dataService.activatedTabs; this.getELKdetails() this.id=setInterval(() => { this.getServerUtilizationStats('30Sec'); }, 3000); this.noti=setInterval(() => { this.getNotifications(); }, 200000); this.getNotifications(); } ngOnDestroy() { if (this.id) { clearInterval(this.id); } if(this.noti){ clearInterval(this.noti); } } onPageChange(number: number) { console.log('change to page', number); this.config.currentPage = number; } getServerUtilizationStats(periodtime) { this.clearStats(); const params = { "containerName" : this.containerName, //"containerName" : this.diagnosecomp.selected_value, // "indexName": "idplinv04stats", //this is the name it had earlier "indexName": this.elkIndex, "instanceName": this.instanceName, "period" : periodtime, "elkPort" : this.elkPort, "elkserver" : this.elkHost }; let responseData : any; this.restService.getServerUtilizationStats(params).then(res => { if (res) { if (res['status'] === 200) { responseData = JSON.parse(res.json()['resource']); console.log(responseData); this.dataService.serverUtilization = responseData; console.log(this.dataService.serverUtilization); this.lineData.label = "MEMORY USAGE"; for(let i=0 ; i< this.dataService.serverUtilization.memoryData.processingTime.length; i++){ console.log("pushing data"); this.datasets[0].data.push({ x: this.dataService.serverUtilization.memoryData.processingTime[i], y: this.dataService.serverUtilization.memoryData.memoryUsage[i], }); this.CPUdatasets[0].data.push({ x: this.dataService.serverUtilization.memoryData.processingTime[i], y: this.dataService.serverUtilization.cpuData.cpuAverage[i], }); } this.cpulineData.label = "CPU USAGE" this.changeDetectorRef.detectChanges(); } } }) //this.getCriticalLogs(); } setClickedRow(index){ this.selectedRow = index; let name, name1, time; name=this.notifications[index]; name1 = name.split(':')[0] time = name.split(',')[1] this.selected_value = name1 console.log("*************") console.log(time) console.log("***call******") let ydaydate = new Date(time); let selectdate = new Date(time); console.log(ydaydate) ydaydate.setMinutes(ydaydate.getMinutes() - 60); console.log(ydaydate) selectdate.setMinutes(selectdate.getMinutes() + 60); let ydaydat=this.datepipe.transform(ydaydate, 'yyyy-MM-ddTHH:mm:ssZ'); let selecteddate=this.datepipe.transform(selectdate, 'yyyy-MM-ddTHH:mm:ssZ'); this.getCriticalLogs(selecteddate,ydaydat) } getELKdetails() { let responseData; this.notifications = [] this.selectedRow = -1; console.log("getELKDetails initialized"); // this.spinner.show(); console.log(responseData) this.restService.getELKdetails("ShoppingCart").then(res => { if (res) { if (res['status'] === 200) { responseData = res.json(); for (let key in responseData) {     console.log ('key: ' +  key + ', value: ' +responseData[key]); } console.log("ElkDetails: "+responseData["ElkIndex"]) this.elkIndex = responseData["ElkIndex"]; this.elkHost = responseData["elkHost"] this.elkPort = responseData["ElkPort"] } } }) // this.spinner.hide(); } getNotifications() { let responseData; this.notifications = [] this.selectedRow = -1; console.log("getNotifications initialized"); // this.spinner.show(); console.log(responseData) this.restService.getNotifications("ShoppingCart").then(res => { if (res) { if (res['status'] === 200) { responseData = res.json().res; for(let i=0; i<responseData.length ; i++){ this.selected_value = responseData[i][0] this.notifications.push(responseData[i][1]+": CPU/Mem spike at "+responseData[i][2]) } } } }) // this.spinner.hide(); } removeData() { this.datasets = [{ label: 'Memory Usage(in MBs)', backgroundColor: this.chartColors.red, borderColor: this.chartColors.red, fill: false, lineTension: 0, borderDash: [8, 4], type: 'line', data: [], pointRadius: 5, pointHoverRadius: 15, pointHitRadius: 10, pointHoverBackgroundColor: this.chartColors.red }]; this.CPUdatasets = [{ label: 'CPU Usage(in %)', backgroundColor: this.chartColors.blue, borderColor: this.chartColors.blue, fill: false, lineTension: 0, borderDash: [8, 4], type: 'line', data: [], pointRadius: 5, pointHoverRadius: 15, pointHitRadius: 10, pointHoverBackgroundColor: this.chartColors.red }]; } public chartClicked(e:any):void { console.log(e); if (e.active.length > 0) { const chart = e.active[0]._chart; const activePoints = chart.getElementAtEvent(e.event); if ( activePoints.length > 0) { // get the internal index of slice in pie chart const clickedElementIndex = activePoints[0]._index; const label = chart.data.labels[clickedElementIndex]; // get value by index const value = chart.data.datasets[0].data[clickedElementIndex]; console.log("x value "+ value.x) console.log("y value "+ value.y) let ydaydate = new Date(value.x); ydaydate.setMinutes(ydaydate.getMinutes() - 60); let ydaydat=this.datepipe.transform(ydaydate, 'yyyy-MM-ddTHH:mm:ssZ'); let selecteddate=this.datepipe.transform(new Date(value.x), 'yyyy-MM-ddTHH:mm:ssZ'); this.getCriticalLogs(selecteddate,ydaydat) } } } clearStats(){ this.lineCPUChardData = []; this.lineChartData = []; } changeContainerName(){ console.log(" Container Name : " + this.containerName); console.log(" App Name : " + this.trendsAppName); if(this.containerName == ''){ this.instanceList = []; this.instanceName = ''; this.period = ''; } this.datasets[0].data=[]; this.CPUdatasets[0].data=[]; this.changeDetectorRef.detectChanges(); //let localInstanceList : any; for(let i=0 ; i< this.containerList.length; i++){ if(this.containerList[i]['containerName'] === this.containerName){ this.instanceList = this.containerList[i]['instanceList']; } } console.log(this.instanceList); if(this.instanceList.length > 0){ this.instanceName = this.instanceList[0]['instanceNumber']; this.period = this.periodList[0]; } this.removeData(); this.getServerUtilizationStats(this.period) } changeContainerName1(){ this.containerName = this.selected_value console.log(" Container Name : " + this.containerName); console.log(" App Name : " + this.trendsAppName); if(this.containerName == ''){ this.instanceList = []; this.instanceName = ''; this.period = ''; } this.datasets[0].data=[]; this.CPUdatasets[0].data=[]; this.changeDetectorRef.detectChanges(); //let localInstanceList : any; for(let i=0 ; i< this.containerList.length; i++){ if(this.containerList[i]['containerName'] === this.containerName){ this.instanceList = this.containerList[i]['instanceList']; } } console.log(this.instanceList); if(this.instanceList.length > 0){ this.instanceName = this.instanceList[0]['instanceNumber']; this.period = this.periodList[0]; } this.removeData(); this.getServerUtilizationStats(this.period) } getCriticalLogs(selecteddate,ydaydat) { let exceptionDetails = []; const params = { 'AppName' : this.trendsAppName, 'StartTime':ydaydat, 'EndTime':selecteddate, 'ContainerName':this.containerName }; if (this.trendsAppName) { this.dataService.appName = this.trendsAppName; console.log("getCriticalDetails invoking") this.restService.getCriticalDetails(params).then(res => { if (res) { if (true) { exceptionDetails = JSON.parse(res["_body"]); if (exceptionDetails) { if (exceptionDetails.length > 0) { console.log(exceptionDetails); this.anamolyException = exceptionDetails; } else { this.anamolyException = []; } } else { this.anamolyException = []; } this.dataService.anamolyException = this.anamolyException; console.log(this.anamolyException); this.changeDetectorRef.detectChanges(); } } }); } } }
the_stack
import {ValueSets} from "./value_sets"; import {Constants} from "./constants"; import {COLORS} from "./colors"; enum CertificateType { Vaccination = 'Vaccination Pass', Test = 'Test Pass', Recovery = 'Recovery Pass', } enum TextAlignment { right = 'PKTextAlignmentRight', } interface Field { key: string; label: string; value: string; textAlignment?: string; } export interface PassDictionary { headerFields: Array<Field>; primaryFields: Array<Field>; secondaryFields: Array<Field>; auxiliaryFields: Array<Field>; backFields: Array<Field>; } export interface PayloadBody { color: COLORS; rawData: string; decodedData: Uint8Array; } export class Payload { certificateType: CertificateType; rawData: string; backgroundColor: string; labelColor: string; foregroundColor: string; img1x: Buffer; img2x: Buffer; dark: boolean; generic: PassDictionary; constructor(body: PayloadBody, valueSets: ValueSets) { const dark = body.color != COLORS.WHITE; const healthCertificate = body.decodedData['-260']; const covidCertificate = healthCertificate['1']; // Version number subject to change if (covidCertificate == undefined) { throw new Error('certificateData'); } // Get name and date of birth information const nameInformation = covidCertificate['nam']; const dateOfBirth = covidCertificate['dob']; if (nameInformation == undefined) { throw new Error('nameMissing'); } if (dateOfBirth == undefined) { throw new Error('dobMissing'); } const firstName = nameInformation['gn']; const lastName = nameInformation['fn']; const transliteratedFirstName = nameInformation['gnt'].replaceAll('<', ' '); const transliteratedLastName = nameInformation['fnt'].replaceAll('<', ' '); // Check if name contains non-latin characters const nameRegex = new RegExp('^[\\p{Script=Latin}\\p{P}\\p{M}\\p{Z}]+$', 'u'); let name: string; if (nameRegex.test(firstName) && nameRegex.test(lastName)) { name = `${firstName} ${lastName}`; } else { name = `${transliteratedFirstName} ${transliteratedLastName}`; } let properties: object; // Set certificate type and properties if (covidCertificate['v'] !== undefined) { this.certificateType = CertificateType.Vaccination; properties = covidCertificate['v'][0]; } if (covidCertificate['t'] !== undefined) { this.certificateType = CertificateType.Test; properties = covidCertificate['t'][0]; } if (covidCertificate['r'] !== undefined) { this.certificateType = CertificateType.Recovery; properties = covidCertificate['r'][0]; } if (this.certificateType == undefined) { throw new Error('certificateType') } // Get country, identifier and issuer const countryCode = properties['co']; const uvci = properties['ci']; const certificateIssuer = properties['is']; if (!(countryCode in valueSets.countryCodes)) { throw new Error('invalidCountryCode'); } const country = valueSets.countryCodes[countryCode].display; // Encode raw data and get url const encodedData = Buffer.from(body.rawData).toString('base64'); const url = window.location.protocol + "//" + window.location.host; const generic: PassDictionary = { headerFields: [ { key: "type", label: "EU Digital COVID", value: this.certificateType } ], primaryFields: [ { key: "name", label: "Name", value: name } ], secondaryFields: [], auxiliaryFields: [], backFields: [ { key: "enlarge", label: "Enlarging the QR Code", value: `Inside the Wallet app on iOS, press and hold the link below. This does not work when accessing the Wallet by double-clicking the side button.\n<a href='${url}/pass#${encodedData}'>Enlarge QR Code</a>` }, { key: "uvci", label: "Unique Certificate Identifier (UVCI)", value: uvci }, { key: "issuer", label: "Certificate Issuer", value: certificateIssuer } ] } // Set Values this.rawData = body.rawData; this.backgroundColor = dark ? body.color : COLORS.WHITE this.labelColor = dark ? COLORS.WHITE : COLORS.GREY this.foregroundColor = dark ? COLORS.WHITE : COLORS.BLACK this.img1x = dark ? Constants.img1xWhite : Constants.img1xBlack this.img2x = dark ? Constants.img2xWhite : Constants.img2xBlack this.dark = dark; this.generic = Payload.fillPassData( this.certificateType, generic, properties, valueSets, country, dateOfBirth, url ); } static fillPassData( type: CertificateType, data: PassDictionary, properties: Object, valueSets: ValueSets, country: string, dateOfBirth: string, url: string ): PassDictionary { switch (type) { case CertificateType.Vaccination: const dose = `${properties['dn']}/${properties['sd']}`; const dateOfVaccination = properties['dt']; const medialProductKey = properties['mp']; const manufacturerKey = properties['ma']; if (!(medialProductKey in valueSets.medicalProducts)) { throw new Error('invalidMedicalProduct'); } if (!(manufacturerKey in valueSets.manufacturers)) { throw new Error('invalidManufacturer') } const vaccineName = valueSets.medicalProducts[medialProductKey].display.replace(/\s*\([^)]*\)\s*/g, ""); const manufacturer = valueSets.manufacturers[manufacturerKey].display; data.secondaryFields.push(...[ { key: "dose", label: "Dose", value: dose }, { key: "dov", label: "Date of Vaccination", value: dateOfVaccination, textAlignment: TextAlignment.right } ]); data.auxiliaryFields.push(...[ { key: "vaccine", label: "Vaccine", value: vaccineName }, { key: "dob", label: "Date of Birth", value: dateOfBirth, textAlignment: TextAlignment.right } ]); data.backFields.push(...[ { key: "cov", label: "Country of Vaccination", value: country }, { key: "manufacturer", label: "Manufacturer", value: manufacturer }, { key: "disclaimer", label: "Disclaimer", value: "This certificate is not a travel document. It is only valid in combination with the ID card of the certificate holder and may expire one year + 14 days after the last dose. The validity of this certificate was not checked by CovidPass." } ]); break; case CertificateType.Test: const testTypeKey = properties['tt']; const testDateTimeString = properties['sc']; const testResultKey = properties['tr']; const testingCentre = properties['tc']; if (!(testResultKey in valueSets.testResults)) { throw new Error('invalidTestResult'); } if (!(testTypeKey in valueSets.testTypes)) { throw new Error('invalidTestType') } let testResult = valueSets.testResults[testResultKey].display; switch (testResult) { case 'Not detected': testResult = 'Negative'; break; case 'Detected': testResult = 'Positive'; break; } const testType = valueSets.testTypes[testTypeKey].display; const testTime = testDateTimeString.replace(/.*T/, '').replace('Z', ' ') + 'UTC'; const testDate = testDateTimeString.replace(/T.*/, ''); data.secondaryFields.push(...[ { key: "result", label: "Test Result", value: testResult }, { key: "dot", label: "Date of Test", value: testDate, textAlignment: TextAlignment.right } ]); data.auxiliaryFields.push(...[ { key: "time", label: "Time of Test", value: testTime }, { key: "dob", label: "Date of Birth", value: dateOfBirth, textAlignment: TextAlignment.right }, ]); data.backFields.push({ key: "cot", label: "Country of Test", value: country }); if (testingCentre !== undefined) data.backFields.push({ key: "centre", label: "Testing Centre", value: testingCentre }); data.backFields.push(...[ { key: "test", label: "Test Type", value: testType }, { key: "disclaimer", label: "Disclaimer", value: "This certificate is not a travel document. It is only valid in combination with the ID card of the certificate holder and may expire 24h after the test. The validity of this certificate was not checked by CovidPass." } ]); break; case CertificateType.Recovery: const firstPositiveTestDate = properties['fr']; const validFrom = properties['df']; const validUntil = properties['du']; data.secondaryFields.push(...[ { key: "until", label: "Valid Until", value: validUntil, }, { key: "dot", label: "Date of positive Test", value: firstPositiveTestDate, textAlignment: TextAlignment.right } ]); data.auxiliaryFields.push(...[ { key: "from", label: "Valid From", value: validFrom, }, { key: "dob", label: "Date of Birth", value: dateOfBirth, textAlignment: TextAlignment.right } ]); data.backFields.push(...[ { key: "cot", label: "Country of Test", value: country }, { key: "disclaimer", label: "Disclaimer", value: "This certificate is not a travel document. It is only valid in combination with the ID card of the certificate holder. The validity of this certificate was not checked by CovidPass." } ]); break; default: throw new Error('certificateType'); } data.backFields.push(...[ { key: "credits", label: "", value: `Created with <a href='${url}'>CovidPass</a>` } ]); return data; } }
the_stack
import {EventEmitter} from 'events' import {autorun, makeObservable} from 'mobx' import path from 'path' import Task, {makeGetterProps, TaskStatus} from './AbstractTask' import {fileDownUrl, parseUrl, pwdFileDownUrl, sendDownloadTask} from '../../common/core/download' import {delay, isSpecificFile, mkTempDirSync, restoreFileName, sizeToByte} from '../../common/util' import {lsFile, lsShare, lsShareFolder} from '../../common/core/ls' import requireModule from '../../common/requireModule' import merge from '../../common/merge' import {fileDetail, folderDetail} from '../../common/core/detail' import IpcEvent from '../../common/IpcEvent' import store from '../../main/store' import {message} from '../component/Message' import {persist} from 'mobx-persist' const electron = requireModule('electron') const fs = requireModule('fs-extra') interface DownloadInfo { readonly size?: number readonly resolve?: number readonly status?: TaskStatus url: string name: string pwd?: string merge?: boolean path: string tasks: DownloadTask[] } interface DownloadTask { url: string name: string resolve: number status: TaskStatus pwd?: string path: string size: number } export interface Download { on(event: 'finish', listener: (info: DownloadInfo) => void): this on(event: 'finish-task', listener: (info: DownloadInfo, task: DownloadTask) => void): this // on(event: 'error', listener: (msg: string) => void): this removeListener(event: 'finish', listener: (info: DownloadInfo) => void): this removeListener(event: 'finish-task', listener: (info: DownloadInfo, task: DownloadTask) => void): this // removeListener(event: 'error', listener: (msg: string) => void): this emit(event: 'finish', info: DownloadInfo) emit(event: 'finish-task', info: DownloadInfo, task: DownloadTask) // emit(event: 'error', msg: string) } export class Download extends EventEmitter implements Task<DownloadInfo> { handler: ReturnType<typeof autorun> taskSignal: {[taskUrl: string]: AbortController} = {} @persist('list') list: DownloadInfo[] = [] @persist('list') finishList: DownloadInfo[] = [] @persist dir = '' get queue() { return this.getList(item => item.status === TaskStatus.pending).length } constructor() { super() makeObservable(this, { list: true, finishList: true, dir: true, }) process.nextTick(this.init) } private init = () => { if (!this.dir) { store.get('downloads').then(value => (this.dir = value)) } this.startQueue() this.on('finish', info => { delay(200).then(() => this.onTaskFinish(info)) this.remove(info.url) this.finishList.push(info) }) this.on('finish-task', (info, task) => { delete this.taskSignal[task.url] if (info.tasks.every(item => item.status === TaskStatus.finish)) { this.emit('finish', info) } else { this.start(info.url) } }) } async onTaskFinish(info: DownloadInfo) { const resolveTarget = path.join(info.path, info.name) if (info.merge) { const tempDir = info.tasks[0].path const files = fs.readdirSync(tempDir).map(name => path.join(tempDir, name)) await merge(files, resolveTarget) await delay(200) // 删除临时文件夹 fs.removeSync(tempDir) } else if (isSpecificFile(info.name)) { fs.renameSync(resolveTarget, restoreFileName(resolveTarget)) } } startQueue() { this.handler = autorun( () => { this.list.length && this.checkTask() }, {delay: 300} ) } stopQueue() { this.handler?.() this.handler = null } checkTask() { const url = this.list.find(item => item.status === TaskStatus.ready)?.url if (url) { this.start(url) } } getList(filter: (item: DownloadTask) => boolean) { return this.list .map(item => item.tasks) .flat() .filter(filter) } canStart(info: DownloadInfo) { return this.queue < 3 // && info.status !== InitStatus.pending } abortTask = (task: DownloadTask) => { return new Promise(resolve => { if (this.taskSignal[task.url]) { this.taskSignal[task.url].abort() delete this.taskSignal[task.url] electron.ipcRenderer.once(`${IpcEvent.cancelled}${task.url}`, () => resolve()) } else { resolve() } }) } async pause(url: string) { await Promise.all( this.list .find(item => item.url === url) ?.tasks?.map(task => { if ([TaskStatus.ready, TaskStatus.pending].includes(task.status)) { task.status = TaskStatus.pause return this.abortTask(task) } return Promise.resolve() }) ?? [] ) } pauseAll() { this.list.forEach(item => this.pause(item.url)) } remove(url: string) { this.list.find(item => item.url === url)?.tasks?.forEach(this.abortTask) this.list = this.list.filter(item => item.url !== url) } removeAll() { this.list.forEach(info => info.tasks.forEach(this.abortTask)) this.list = [] } removeAllFinish() { this.finishList = [] } async start(url: string, resetAll = false) { const info = this.list.find(item => item.url === url) if (info && this.canStart(info)) { if (resetAll) { info.tasks.forEach(task => { if ([TaskStatus.pause, TaskStatus.fail].includes(task.status)) { task.status = TaskStatus.ready } }) } const task = info.tasks.find(task => TaskStatus.ready === task.status) if (task) { task.status = TaskStatus.pending try { const {url: downloadUrl} = task.pwd ? await pwdFileDownUrl(task.url, task.pwd) : await fileDownUrl(task.url) // const onProgress = debounce(receivedByte => { // task.resolve = receivedByte // }) // console.log('path.resolve(task.path, task.name)', path.resolve(task.path, task.name)) // console.log(downloadUrl) // const abort = new AbortController() // downloadFile({ // url: downloadUrl, // resolvePath: path.resolve(task.path, task.name), // onProgress, // signal: abort.signal, // }) // .then(() => { // task.status = TaskStatus.finish // this.emit('finish-task', info, task) // }) // .catch(msg => { // message.error(msg) // task.status = TaskStatus.fail // }) // // this.taskSignal[task.url] = abort const abort = new AbortController() const replyId = task.url const ipcMessage: IpcDownloadMsg = { replyId: task.url, downUrl: downloadUrl, folderPath: task.path, } await sendDownloadTask(ipcMessage) const removeListener = () => { electron.ipcRenderer .removeAllListeners(`${IpcEvent.progressing}${replyId}`) .removeAllListeners(`${IpcEvent.done}${replyId}`) .removeAllListeners(`${IpcEvent.failed}${replyId}`) } electron.ipcRenderer .on(`${IpcEvent.progressing}${replyId}`, (event, receivedByte) => { task.resolve = receivedByte }) .once(`${IpcEvent.done}${replyId}`, () => { task.status = TaskStatus.finish this.emit('finish-task', info, task) removeListener() }) .once(`${IpcEvent.failed}${replyId}`, (e, msg) => { message.error(msg) task.status = TaskStatus.fail removeListener() }) this.taskSignal[task.url] = abort abort.signal.onabort = () => { electron.ipcRenderer.send(IpcEvent.abort, replyId) removeListener() } } catch (e) { task.status = TaskStatus.fail message.error(e) } } } } startAll() { this.list.forEach(info => { info.tasks.forEach(task => { if (task.status === TaskStatus.pause) { task.status = TaskStatus.ready } }) this.start(info.url) }) } getFileDir() { return this.dir } /** * 新增列表文件任务 */ async addFileTask(options: {name: string; size: number; file_id: string}) { try { const folderDir = this.getFileDir() const {f_id, is_newd, pwd, onof} = await fileDetail(options.file_id) const url = `${is_newd}/${f_id}` const info: DownloadInfo = { url, path: folderDir, ...options, tasks: [ { url, name: options.name, resolve: 0, status: TaskStatus.ready, pwd: onof == '1' ? pwd : '', path: folderDir, size: options.size, }, ], } makeGetterProps(info) this.list.push(info) } catch (e) { message.error(e) } } /** * 新增分享文件任务 */ async addShareFileTask(options: {url: string; pwd?: string}) { try { const {url} = options const folderDir = this.getFileDir() const {name, size} = await lsShare(options) const task: DownloadInfo = { path: folderDir, ...options, name, tasks: [ { url, name, resolve: 0, status: TaskStatus.ready, pwd: options.pwd, path: folderDir, size: sizeToByte(size), }, ], } makeGetterProps(task) this.list.push(task) } catch (e) { message.error(e) } } /** * 下载列表文件夹文件 * @param options */ async addFolderTask(options: {folder_id: FolderId; name: string; merge?: boolean}) { try { let folderDir = this.getFileDir() const [detail, files] = await Promise.all([folderDetail(options.folder_id), lsFile(options.folder_id)]) const info: DownloadInfo = { path: folderDir, url: detail.new_url, pwd: detail.onof === '1' ? detail.pwd : '', merge: options.merge, name: options.name, // ...options, tasks: [], } if (options.merge) { folderDir = mkTempDirSync() } const fileInfos = await Promise.all(files.map(file => fileDetail(file.id))) info.tasks.push( ...fileInfos.map((info, index) => ({ url: `${info.is_newd}/${info.f_id}`, name: files[index]?.name_all, resolve: 0, status: TaskStatus.ready, pwd: info.onof === '1' ? info.pwd : '', path: folderDir, size: sizeToByte(files[index]?.size), })) ) makeGetterProps(info) this.list.push(info) } catch (e) { message.error(e) } } /** * 下载分享文件夹 * merge: 自动合并下载文件 */ async addShareFolderTask(options: {url: string; pwd?: string; merge?: boolean}) { try { const {is_newd} = parseUrl(options.url) let folderDir = this.getFileDir() const info: DownloadInfo = { path: folderDir, name: '', tasks: [], ...options, } const {name, list} = await lsShareFolder(options) if (options.merge) { folderDir = mkTempDirSync() } info.name = name info.tasks.push( ...list.map<DownloadTask>(item => ({ url: `${is_newd}/${item.id}`, name: item.name_all, resolve: 0, status: TaskStatus.ready, pwd: '', path: folderDir, size: sizeToByte(item.size), })) ) makeGetterProps(info) this.list.push(info) } catch (e) { message.error(e) } } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormServiceAppointment_Information { interface tab_bookableResourceBooking_Sections { Bookable_Resource_Bookings_Section: DevKit.Controls.Section; } interface tab_details_Sections { appointment_details: DevKit.Controls.Section; } interface tab_service_Sections { general_information: DevKit.Controls.Section; notes: DevKit.Controls.Section; scheduling_information: DevKit.Controls.Section; } interface tab_bookableResourceBooking extends DevKit.Controls.ITab { Section: tab_bookableResourceBooking_Sections; } interface tab_details extends DevKit.Controls.ITab { Section: tab_details_Sections; } interface tab_service extends DevKit.Controls.ITab { Section: tab_service_Sections; } interface Tabs { bookableResourceBooking: tab_bookableResourceBooking; details: tab_details; service: tab_service; } interface Body { Tab: Tabs; /** Type a category to identify the service activity type, such as routine maintenance or service call, to tie the service activity to a business group or function. */ Category: DevKit.Controls.String; /** Enter the accounts and contacts for whom the service activity is being performed. */ Customers: DevKit.Controls.Lookup; /** Select whether the service activity is an all-day event to make sure the required resources are scheduled for the full day. */ IsAllDayEvent: DevKit.Controls.Boolean; /** Type the location where the service activity will take place, such as a conference room, customer office, or other venue. */ Location: DevKit.Controls.String; /** OrganizationalUnit ServiceAppointment Id */ msdyn_OrganizationalUnitId: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Unique identifier of the user or team who owns the activity. */ OwnerId: DevKit.Controls.Lookup; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Unique identifier of the object with which the service activity is associated. */ RegardingObjectId: DevKit.Controls.Lookup; /** Enter the user, facility, or equipment required to complete the service activity. */ Resources: DevKit.Controls.Lookup; /** Shows the expected duration of the service activity, in minutes. */ ScheduledDurationMinutes: DevKit.Controls.Integer; /** Enter the expected due date and time. */ ScheduledEnd: DevKit.Controls.DateTime; /** Enter the expected due date and time. */ ScheduledStart: DevKit.Controls.DateTime; /** Choose the service scheduled to be performed during the service activity. */ ServiceId: DevKit.Controls.Lookup; /** Choose the site or location where the service activity will be performed. */ SiteId: DevKit.Controls.Lookup; /** Select the service activity's status. */ StatusCode: DevKit.Controls.OptionSet; /** Type a subcategory to identify the service activity type and relate the activity to a specific product, service region, business group, or other function. */ Subcategory: DevKit.Controls.String; /** Type a short description about the objective or primary topic of the service activity. */ Subject: DevKit.Controls.String; } interface Footer extends DevKit.Controls.IFooter { /** Shows whether the service activity is open, completed, or canceled. Completed and canceled service activities are read-only and can't be edited. */ StateCode: DevKit.Controls.OptionSet; } interface Grid { bookableresourcebookings: DevKit.Controls.Grid; } } class FormServiceAppointment_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form ServiceAppointment_Information * @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 ServiceAppointment_Information */ Body: DevKit.FormServiceAppointment_Information.Body; /** The Footer section of form ServiceAppointment_Information */ Footer: DevKit.FormServiceAppointment_Information.Footer; /** The Grid of form ServiceAppointment_Information */ Grid: DevKit.FormServiceAppointment_Information.Grid; } class ServiceAppointmentApi { /** * DynamicsCrm.DevKit ServiceAppointmentApi * @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; /** For internal use only. */ ActivityAdditionalParams: DevKit.WebApi.StringValue; /** Unique identifier of the service activity. */ ActivityId: DevKit.WebApi.GuidValue; /** Shows the value selected in the Duration field on the service activity at the time the service activity is closed as completed. The duration is used to report the time spent on the activity. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Enter the actual end date and time of the service activity. By default, it displays when the activity was closed or canceled. */ ActualEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Enter the actual start date and time for the service activity. By default, it displays when the activity was created. */ ActualStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Type a category to identify the service activity type, such as routine maintenance or service call, to tie the service activity to a business group or function. */ Category: DevKit.WebApi.StringValue; /** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */ Community: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who created the activity. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the activitypointer. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the delivery of the activity was last attempted. */ DeliveryLastAttemptedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Priority of delivery of the activity to the email server. */ DeliveryPriorityCode: DevKit.WebApi.OptionSetValue; /** Type additional information to describe the service activity, such as key talking points or objectives. */ Description: DevKit.WebApi.StringValue; /** The message id of activity which is returned from Exchange Server. */ ExchangeItemId: DevKit.WebApi.StringValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the web link of Activity of type email. */ ExchangeWebLink: DevKit.WebApi.StringValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Type of instance of a recurring series. */ InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly; /** Select whether the service activity is an all-day event to make sure the required resources are scheduled for the full day. */ IsAllDayEvent: DevKit.WebApi.BooleanValue; /** Information which specifies whether the service activity was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** For internal use only. */ IsMapiPrivate: DevKit.WebApi.BooleanValue; /** Information regarding whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** Information which specifies if the service activity was created from a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Left the voice mail */ LeftVoiceMail: DevKit.WebApi.BooleanValue; /** Type the location where the service activity will take place, such as a conference room, customer office, or other venue. */ Location: DevKit.WebApi.StringValue; /** Unique identifier of user who last modified the activity. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when activity was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the activitypointer. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** OrganizationalUnit ServiceAppointment Id */ msdyn_OrganizationalUnitId: DevKit.WebApi.LookupValue; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** 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 of the business unit that owns the activity. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the activity. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user that owns the activity. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** For internal use only. */ PostponeActivityProcessingUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Select the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the Process. */ ProcessId: DevKit.WebApi.GuidValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_account_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_bookableresourcebooking_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_bookableresourcebookingheader_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_bulkoperation_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_campaign_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_campaignactivity_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_contact_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_contract_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_entitlement_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_entitlementtemplate_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_incident_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_new_interactionforemail_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_invoice_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_knowledgearticle_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_knowledgebaserecord_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_lead_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_agreement_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_agreementbookingdate_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_agreementbookingincident_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_agreementbookingproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_agreementbookingservice_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_agreementbookingservicetask_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_agreementbookingsetup_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_agreementinvoicedate_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_agreementinvoiceproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_agreementinvoicesetup_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_bookingalertstatus_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_bookingrule_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_bookingtimestamp_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_customerasset_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_fieldservicesetting_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_incidenttypecharacteristic_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_incidenttypeproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_incidenttypeservice_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_inventoryadjustment_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_inventoryadjustmentproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_inventoryjournal_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_inventorytransfer_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_payment_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_paymentdetail_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_paymentmethod_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_paymentterm_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_playbookinstance_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_postalbum_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_postalcode_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_processnotes_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_productinventory_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_projectteam_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_purchaseorder_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_purchaseorderbill_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_purchaseorderproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_purchaseorderreceipt_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_purchaseorderreceiptproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_purchaseordersubstatus_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_quotebookingincident_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_quotebookingproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_quotebookingservice_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_quotebookingservicetask_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_resourceterritory_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_rma_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_rmaproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_rmareceipt_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_rmareceiptproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_rmasubstatus_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_rtv_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_rtvproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_rtvsubstatus_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_shipvia_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_systemuserschedulersetting_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_timegroup_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_timegroupdetail_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_timeoffrequest_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_warehouse_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_workorder_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_workordercharacteristic_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_workorderincident_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_workorderproduct_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_workorderresourcerestriction_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_workorderservice_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_msdyn_workorderservicetask_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_opportunity_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_quote_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_salesorder_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_site_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_uii_action_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_uii_hostedapplication_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_uii_nonhostedapplication_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_uii_option_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_uii_savedsession_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_uii_workflow_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_uii_workflowstep_serviceappointment: DevKit.WebApi.LookupValue; /** Unique identifier of the object with which the service activity is associated. */ regardingobjectid_uii_workflow_workflowstep_mapping_serviceappointment: DevKit.WebApi.LookupValue; /** Shows the expected duration of the service activity, in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValue; /** Enter the expected due date and time. */ ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Enter the expected due date and time. */ ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the mailbox associated with the sender of the email message. */ SenderMailboxId: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was sent. */ SentOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Uniqueidentifier specifying the id of recurring series of an instance. */ SeriesId: DevKit.WebApi.GuidValueReadonly; /** Choose the service scheduled to be performed during the service activity. */ ServiceId: DevKit.WebApi.LookupValue; /** Choose the site or location where the service activity will be performed. */ SiteId: DevKit.WebApi.LookupValue; /** Choose the service level agreement (SLA) that you want to apply to the service appointment record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this email. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the Stage. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the service activity is open, completed, or canceled. Completed and canceled service activities are read-only and can't be edited. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the service activity's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Type a subcategory to identify the service activity type and relate the activity to a specific product, service region, business group, or other function. */ Subcategory: DevKit.WebApi.StringValue; /** Type a short description about the objective or primary topic of the service activity. */ Subject: DevKit.WebApi.StringValue; /** For internal use only. */ SubscriptionId: DevKit.WebApi.GuidValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the activity. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** The array of object that can cast object to ActivityPartyApi class */ ActivityParties: Array<any>; } } declare namespace OptionSet { namespace ServiceAppointment { enum Community { /** 5 */ Cortana, /** 6 */ Direct_Line, /** 8 */ Direct_Line_Speech, /** 9 */ Email, /** 1 */ Facebook, /** 10 */ GroupMe, /** 11 */ Kik, /** 3 */ Line, /** 7 */ Microsoft_Teams, /** 0 */ Other, /** 13 */ Skype, /** 14 */ Slack, /** 12 */ Telegram, /** 2 */ Twitter, /** 4 */ Wechat, /** 15 */ WhatsApp } enum DeliveryPriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum InstanceTypeCode { /** 0 */ Not_Recurring, /** 3 */ Recurring_Exception, /** 4 */ Recurring_Future_Exception, /** 2 */ Recurring_Instance, /** 1 */ Recurring_Master } enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum StateCode { /** 2 */ Canceled, /** 1 */ Closed, /** 0 */ Open, /** 3 */ Scheduled } enum StatusCode { /** 7 */ Arrived, /** 9 */ Canceled, /** 8 */ Completed, /** 6 */ In_Progress, /** 10 */ No_Show, /** 3 */ Pending, /** 1 */ Requested, /** 4 */ Reserved, /** 2 */ Tentative } 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':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { expect } from "chai"; import { EntityClass, PrimitiveProperty, RelationshipClass, RelationshipConstraint, RelationshipEnd, Schema, SchemaContext, } from "@itwin/ecschema-metadata"; import * as Diagnostics from "../../Validation/Diagnostic"; describe("Diagnostics tests", () => { let testSchema: Schema; function invalidCodeMsg(code: string) { return `Diagnostic code ${code} is invalid. Expected the format <ruleSetName>-<number>.`; } beforeEach(async () => { testSchema = new Schema(new SchemaContext(), "TestSchema", "ts", 1, 0, 0); }); it("diagnosticCategoryToString, Error, proper string returned", () => { const result = Diagnostics.diagnosticCategoryToString(Diagnostics.DiagnosticCategory.Error); expect(result).to.equal("Error"); }); it("diagnosticCategoryToString, Message, proper string returned", () => { const result = Diagnostics.diagnosticCategoryToString(Diagnostics.DiagnosticCategory.Message); expect(result).to.equal("Message"); }); it("diagnosticCategoryToString, Suggestion, proper string returned", () => { const result = Diagnostics.diagnosticCategoryToString(Diagnostics.DiagnosticCategory.Suggestion); expect(result).to.equal("Suggestion"); }); it("diagnosticCategoryToString, Warning, proper string returned", () => { const result = Diagnostics.diagnosticCategoryToString(Diagnostics.DiagnosticCategory.Warning); expect(result).to.equal("Warning"); }); it("diagnosticTypeToString, CustomAttributeContainer, proper string returned", () => { const result = Diagnostics.diagnosticTypeToString(Diagnostics.DiagnosticType.CustomAttributeContainer); expect(result).to.equal("CustomAttributeContainer"); }); it("diagnosticTypeToString, None, proper string returned", () => { const result = Diagnostics.diagnosticTypeToString(Diagnostics.DiagnosticType.None); expect(result).to.equal("None"); }); it("diagnosticTypeToString, Property, proper string returned", () => { const result = Diagnostics.diagnosticTypeToString(Diagnostics.DiagnosticType.Property); expect(result).to.equal("Property"); }); it("diagnosticTypeToString, RelationshipConstraint, proper string returned", () => { const result = Diagnostics.diagnosticTypeToString(Diagnostics.DiagnosticType.RelationshipConstraint); expect(result).to.equal("RelationshipConstraint"); }); it("diagnosticTypeToString, Schema, proper string returned", () => { const result = Diagnostics.diagnosticTypeToString(Diagnostics.DiagnosticType.Schema); expect(result).to.equal("Schema"); }); it("diagnosticTypeToString, SchemaItem, proper string returned", () => { const result = Diagnostics.diagnosticTypeToString(Diagnostics.DiagnosticType.SchemaItem); expect(result).to.equal("SchemaItem"); }); it("createSchemaDiagnosticClass, class created properly", async () => { const newClass = Diagnostics.createSchemaDiagnosticClass("TestRuleSet-100", "Test Message"); expect(newClass.prototype.diagnosticType).to.equal(Diagnostics.DiagnosticType.Schema); expect(newClass.prototype.code).to.equal("TestRuleSet-100"); expect(newClass.prototype.messageText).to.equal("Test Message"); }); it("create Schema Diagnostic, instance created properly", async () => { const newClass = Diagnostics.createSchemaDiagnosticClass("TestRuleSet-100", "Test Message"); const instance = new newClass(testSchema, ["arg"], Diagnostics.DiagnosticCategory.Message); expect(instance.schema).to.equal(testSchema); expect(instance.diagnosticType).to.equal(Diagnostics.DiagnosticType.Schema); expect(instance.code).to.equal("TestRuleSet-100"); expect(instance.category).to.equal(Diagnostics.DiagnosticCategory.Message); expect(instance.messageText).to.equal("Test Message"); }); it("createSchemaDiagnosticClass, invalid code, throws", () => { let code = "InvalidCode"; expect(() => Diagnostics.createSchemaDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); code = "Invalid:NotNumber"; expect(() => Diagnostics.createSchemaDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); }); it("createSchemaItemDiagnosticClass, class created properly", async () => { const newClass = Diagnostics.createSchemaItemDiagnosticClass("TestRuleSet-100", "Test Message"); expect(newClass.prototype.diagnosticType).to.equal(Diagnostics.DiagnosticType.SchemaItem); expect(newClass.prototype.code).to.equal("TestRuleSet-100"); expect(newClass.prototype.messageText).to.equal("Test Message"); }); it("create SchemaItem Diagnostic, instance created properly", async () => { const newClass = Diagnostics.createSchemaItemDiagnosticClass("TestRuleSet-100", "Test Message"); const entityClass = new EntityClass(testSchema, "TestClass"); const instance = new newClass(entityClass, ["arg"], Diagnostics.DiagnosticCategory.Message); expect(instance.schema).to.equal(testSchema); expect(instance.diagnosticType).to.equal(Diagnostics.DiagnosticType.SchemaItem); expect(instance.code).to.equal("TestRuleSet-100"); expect(instance.category).to.equal(Diagnostics.DiagnosticCategory.Message); expect(instance.messageText).to.equal("Test Message"); }); it("createSchemaItemDiagnosticClass, invalid code, throws", () => { let code = "InvalidCode"; expect(() => Diagnostics.createSchemaItemDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); code = "Invalid:NotNumber"; expect(() => Diagnostics.createSchemaItemDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); }); it("createClassDiagnosticClass, class created properly", async () => { const newClass = Diagnostics.createClassDiagnosticClass("TestRuleSet-100", "Test Message"); expect(newClass.prototype.diagnosticType).to.equal(Diagnostics.DiagnosticType.SchemaItem); expect(newClass.prototype.code).to.equal("TestRuleSet-100"); expect(newClass.prototype.messageText).to.equal("Test Message"); }); it("create Class Diagnostic, instance created properly", async () => { const newClass = Diagnostics.createClassDiagnosticClass("TestRuleSet-100", "Test Message"); const entityClass = new EntityClass(testSchema, "TestClass"); const instance = new newClass(entityClass, ["arg"], Diagnostics.DiagnosticCategory.Message); expect(instance.schema).to.equal(testSchema); expect(instance.diagnosticType).to.equal(Diagnostics.DiagnosticType.SchemaItem); expect(instance.code).to.equal("TestRuleSet-100"); expect(instance.category).to.equal(Diagnostics.DiagnosticCategory.Message); expect(instance.messageText).to.equal("Test Message"); }); it("createClassDiagnosticClass, invalid code, throws", () => { let code = "InvalidCode"; expect(() => Diagnostics.createClassDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); code = "Invalid:NotNumber"; expect(() => Diagnostics.createClassDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); }); it("createPropertyDiagnosticClass, class created properly", async () => { const newClass = Diagnostics.createPropertyDiagnosticClass("TestRuleSet-100", "Test Message"); expect(newClass.prototype.diagnosticType).to.equal(Diagnostics.DiagnosticType.Property); expect(newClass.prototype.code).to.equal("TestRuleSet-100"); expect(newClass.prototype.messageText).to.equal("Test Message"); }); it("create Property Diagnostic, instance created properly", async () => { const newClass = Diagnostics.createPropertyDiagnosticClass("TestRuleSet-100", "Test Message"); const entityClass = new EntityClass(testSchema, "TestClass"); const property = new PrimitiveProperty(entityClass, "TestProperty"); const instance = new newClass(property, ["arg"], Diagnostics.DiagnosticCategory.Warning); expect(instance.schema).to.equal(testSchema); expect(instance.diagnosticType).to.equal(Diagnostics.DiagnosticType.Property); expect(instance.code).to.equal("TestRuleSet-100"); expect(instance.category).to.equal(Diagnostics.DiagnosticCategory.Warning); expect(instance.messageText).to.equal("Test Message"); }); it("createPropertyDiagnosticClass, invalid code, throws", () => { let code = "InvalidCode"; expect(() => Diagnostics.createPropertyDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); code = "Invalid:NotNumber"; expect(() => Diagnostics.createPropertyDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); }); it("createRelationshipConstraintDiagnosticClass, class created properly", async () => { const newClass = Diagnostics.createRelationshipConstraintDiagnosticClass("TestRuleSet-100", "Test Message"); expect(newClass.prototype.diagnosticType).to.equal(Diagnostics.DiagnosticType.RelationshipConstraint); expect(newClass.prototype.code).to.equal("TestRuleSet-100"); expect(newClass.prototype.messageText).to.equal("Test Message"); }); it("create RelationshipConstraint Diagnostic, instance created properly", async () => { const newClass = Diagnostics.createRelationshipConstraintDiagnosticClass("TestRuleSet-100", "Test Message"); const relationship = new RelationshipClass(testSchema, "TestRelationship"); const constraint = new RelationshipConstraint(relationship, RelationshipEnd.Source); const instance = new newClass(constraint, ["arg"], Diagnostics.DiagnosticCategory.Error); expect(instance.schema).to.equal(testSchema); expect(instance.diagnosticType).to.equal(Diagnostics.DiagnosticType.RelationshipConstraint); expect(instance.code).to.equal("TestRuleSet-100"); expect(instance.category).to.equal(Diagnostics.DiagnosticCategory.Error); expect(instance.messageText).to.equal("Test Message"); }); it("createRelationshipConstraintDiagnosticClass, invalid code, throws", () => { let code = "InvalidCode"; expect(() => Diagnostics.createRelationshipConstraintDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); code = "Invalid:NotNumber"; expect(() => Diagnostics.createRelationshipConstraintDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); }); it("createCustomAttributeContainerDiagnosticClass, class created properly", async () => { const newClass = Diagnostics.createCustomAttributeContainerDiagnosticClass("TestRuleSet-100", "Test Message"); expect(newClass.prototype.diagnosticType).to.equal(Diagnostics.DiagnosticType.CustomAttributeContainer); expect(newClass.prototype.code).to.equal("TestRuleSet-100"); expect(newClass.prototype.messageText).to.equal("Test Message"); }); it("create RelationshipConstraint Diagnostic, instance created properly", async () => { const newClass = Diagnostics.createCustomAttributeContainerDiagnosticClass("TestRuleSet-100", "Test Message"); const entityClass = new EntityClass(testSchema, "TestClass"); const instance = new newClass(entityClass, ["arg"], Diagnostics.DiagnosticCategory.Error); expect(instance.schema).to.equal(testSchema); expect(instance.diagnosticType).to.equal(Diagnostics.DiagnosticType.CustomAttributeContainer); expect(instance.code).to.equal("TestRuleSet-100"); expect(instance.category).to.equal(Diagnostics.DiagnosticCategory.Error); expect(instance.messageText).to.equal("Test Message"); }); it("createCustomAttributeContainerDiagnosticClass, invalid code, throws", () => { let code = "InvalidCode"; expect(() => Diagnostics.createCustomAttributeContainerDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); code = "Invalid:NotNumber"; expect(() => Diagnostics.createCustomAttributeContainerDiagnosticClass(code, "Test Message")).to.throw(Error, invalidCodeMsg(code)); }); });
the_stack
process.env.NODE_ENV = "test"; /* eslint-disable @typescript-eslint/no-unused-vars */ import * as blessed from "neo-blessed"; import { BlessedProgram, Widgets, box, text, colors, program } from "neo-blessed"; import { Logger } from "../common/Logger"; import { messageBox, MSG_BUTTON_TYPE } from "../panel_blassed/widget/MessageBox"; import mainFrame from "../panel_blassed/MainFrame"; import { ProgressBox } from "../panel_blassed/widget/ProgressBox"; import { StringUtils } from "../common/StringUtils"; import { Color } from "../common/Color"; import { inputBox } from "../panel_blassed/widget/InputBox"; import { Hint, KeyMappingInfo, menuKeyMapping, keyMappingExec, getHelpInfo } from "../config/KeyMapConfig"; import { BlessedXterm } from "../panel_blassed/BlessedXterm"; import { menuConfig } from "../config/MenuConfig"; import { BlessedMenu } from "../panel_blassed/BlessedMenu"; import { BlessedMcd } from "../panel_blassed/BlessedMcd"; import { readerControl } from "../panel/readerControl"; import { Mcd } from "../panel/Mcd"; import { FileReader } from "../panel/FileReader"; import { sprintf } from "sprintf-js"; import i18n from "i18next"; import I18nextCLILanguageDetector from "i18next-cli-language-detector"; import en from "../translation/en.json"; import ko from "../translation/ko.json"; import { button } from "../../@types/blessed"; import { BlessedEditor } from "../panel_blassed/BlessedEditor"; import { i18nInit, T, changeLanguage } from "../common/Translation"; import osLocale from "os-locale"; import { ConnectionEditor, IConnectionEditorOption } from "../panel_blassed/widget/ConnectionEditor"; import { ConnectionManager } from "../panel_blassed/widget/ConnectionManager"; const log = Logger("TEST_MAIN"); /* const T = ( ...a ) => { return i18n.t.apply( i18n, a ); }; (async () => { const T = await i18n.use(I18nextCLILanguageDetector).init({ debug: true, resources: { en: { translation: en }, ko: { translation: ko } }, // lng: "ko", }); console.log( T("Hint.Paste") ); })(); */ // menuKeyMapping( KeyMappingInfo, menuConfig ); // console.log( JSON.stringify( menuConfig, null, 4) ); const screen = blessed.screen({ smartCSR: true, fullUnicode: true, dockBorders: true, useBCE: true, ignoreDockContrast: true, // debug: true, //dump: true, //log: process.env.HOME + "/.m/m2.log" }); screen.key("q", () => { process.exit(0); }); const testTextColor = (text, fg, bg) => { const fgF = (screen.program as any)._attr(fg + " fg", true); const fgE = (screen.program as any)._attr(fg + " fg", false); const bgF = (screen.program as any)._attr(bg + " bg", true); const bgE = (screen.program as any)._attr(bg + " bg", false); return fgF + bgF + text + bgE + bgE; }; screen.key("e", () => { const test = "TEST"; const fg = 3; const bg = 8; log.debug( "[%s] [%s]", test, testTextColor(test, fg, bg) ); }); screen.key("m", async () => { const result = await messageBox({ parent: screen, title: "TEST", msg: "TEST 합니다.", textAlign: "left", buttonType: MSG_BUTTON_TYPE.AUTO, scroll: false, button: [ "OK", "Cancel", "ITEM1", "ITEM2" ] }, { parent: screen }); }); screen.key("i", async () => { const result = await inputBox( { parent: screen, title: "InputBox TITLE", defaultText: "DEFAULT TEST !!!", button: [ "OK", "Cancel" ] }); log.info( "RESULT : %j", result ); }); screen.key("t", async () => { (global as any).LOCALE = await osLocale(); await i18nInit( (global as any).LOCALE.match( /^ko/ ) ? "ko" : undefined ); const connectionInfo: IConnectionEditorOption = { name: "테스트", info: [ { protocol: "SFTP", host: "127.0.0.1", port: 22, // default 22 username: "la9527_sftp", password: "test", privateKey: "~/.ssh/id_rsa", proxyInfo: { host: "127.0.0.1", port: 4016, type: 5, username: "la9527", password: "test" }, }, { protocol: "SSH", host: "127.0.0.1", port: 22, // default 22 username: "la9527_ssh", password: "test", privateKey: "~/.ssh/id_rsa", proxyInfo: { host: "127.0.0.1", port: 4016, type: 5, username: "la9527", password: "test" }, } ], resultFunc: (result, message) => { screen.destroy(); console.log( result, JSON.stringify(message, null, 2) ); } }; new ConnectionEditor(connectionInfo, { parent: screen }); screen.render(); // new ConnectionManager({ parent: screen }); }); screen.render(); /* (async () => { const helpInfo = getHelpInfo(); let viewText = []; for ( const frame of [ "Common", "Panel", "Mcd" ] ) { viewText.push(`${frame})` ); let subText = []; for ( const item in helpInfo[frame] ) { if ( helpInfo[frame][item].humanKeyName ) { subText.push( sprintf("{yellow-fg}%14s{/yellow-fg} : %s", helpInfo[frame][item].humanKeyName, helpInfo[frame][item].text ) ); } } subText.sort(); viewText = viewText.concat( subText ); viewText.push( "" ); } log.debug( "viewText: %s", viewText ); await messageBox({ parent: screen, title: "Help", msg: viewText.join("\n"), textAlign: "left", scroll: false, button: [ "OK" ] }, { parent: screen }); })(); screen.render(); */ /* (async () => { const mcd = new BlessedMcd({ parent: screen, top: 1, left: 0, width: "100%", height: "100%-2" }); mcd.setReader(readerControl("file")); await mcd.scanCurrentDir(); mcd.setFocus(); screen.key("q", () => { process.exit(0); }); screen.key("r", () => { screen.render(); }); screen.render(); const mcd = new Mcd(readerControl("file")); await mcd.scanCurrentDir(); onst fileReader = new FileReader(); await fileReader.readdir( fileReader.currentDir() ); console.log( "END !!! "); })(); */ /* (async () => { screen.key("q", () => { process.exit(0); }); screen.key("r", () => { screen.render(); }); screen.render(); let blessedProgram = null; try { screen.key("c", async () => { blessedProgram = new BlessedXterm( { parent: screen, cursorBlink: true, label: ' multiplex.js ', left: "center", top: "center", width: '50%', height: '50%', border: 'line', style: { fg: 'default', bg: 'default', focus: { border: { fg: 'green' } } } }, null, null); blessedProgram.setFocus(); }); screen.key("k", async () => { blessedProgram && blessedProgram.destroy(); let msg = `FAIL : Common.mountListPromise()\n` + `Error: Command failed: lsblk --bytes --all --pairs\n` + `\n` + `lsblk: failed to access sysfs directory: /sys/dev/block: No such file or directory\n` + ` at ChildProcess.exithandler (child_process.js:303:12)\n` + ` at ChildProcess.emit (events.js:315:20)\n` + ` at maybeClose (internal/child_process.js:1051:16)\n` + ` at Process.ChildProcess._handle.onexit (internal/child_process.js:287:5)]\n`; await messageBox( { parent: screen, title: "TEST", msg, button: ["OK"], textAlign: "left" }); blessedProgram = null; screen.render(); }); } catch( e ) { log.error( e.stack ); } })(); */ /* try { let result = await messageBox( { title: "Copy", msg: `'TEST' file exists. What would you do want?`, button: [ "Overwrite", "Skip", "Rename", "Overwrite All", "Skip All" ] }, { parent: screen }); } catch( e ) { log.error( e ); } const progressBox = new ProgressBox( { title: "Copy", msg: "Calculating...", cancel: () => { log.debug( "Cancel Button !!!"); screen.render(); }}, { parent: screen }); progressBox.init(); let i = 0; let interval = setInterval( () => { let lastText = (new Color(3, 0)).fontHexBlessFormat(StringUtils.sizeConvert(i*1000).trim()) + "/" + (new Color(3, 0)).fontHexBlessFormat(StringUtils.sizeConvert(i*1000).trim()) + `(${StringUtils.sizeConvert(121242,false).trim()}/s)`; // progressBox.updateProgress( source.fullname, lastText, copyBytes, fullFileSize ); progressBox.updateProgress("ABCDEFGHJKLMNOPRSTUVWXYZ1234567890ABCDEFGHJKLMNOPRSTUVWXYZ1234567890ABCDEFGHJKLMNOPRSTUVWXYZ1234567890ABCDEFGHJKLMNOPRSTUVWXYZ1234567890", lastText, ++i, 100); if ( i === 100 ) { clearInterval( interval ); } }, 50); screen.render(); })(); const screen = blessed.screen({ smartCSR: true, fullUnicode: true, dockBorders: true, useBCE: true, ignoreDockContrast: true, debug: true, //dump: true, log: process.env.HOME + "/.m/m2.log" }); (async () => { menuKeyMapping( KeyMappingInfo, menuConfig ); let blessedMenu = new BlessedMenu({ parent: screen }); blessedMenu.setMainMenuConfig( menuConfig.Panel ); screen.on('keypress', async (ch, keyInfo) => { if ( await keyMappingExec( blessedMenu, keyInfo ) ) { screen.render(); } }); screen.key("q", () => { process.exit(0); }); screen.key("r", () => { screen.render(); }); screen.render(); })(); */ /* (async () => { const mcd = new BlessedMcd({ parent: screen, top: 1, left: 0, width: "100%", height: "100%-2" }); mcd.setReader(readerControl("file")); await mcd.scanCurrentDir(); mcd.setFocus(); screen.key("q", () => { process.exit(0); }); screen.key("r", () => { screen.render(); }); screen.render(); })(); const program: BlessedProgram = blessed.program(); program.alternateBuffer(); program.enableMouse(); program.hideCursor(); program.clear(); program.on("keypress", (ch, key) => { if (key.name === "q") { program.clear(); program.disableMouse(); program.showCursor(); program.normalBuffer(); process.exit(0); } }); program.move(5, 5); program.write("Hello world"); program.move(10, 10); */
the_stack
import * as spec from '@jsii/spec'; import { camel, constant as allCaps, pascal } from 'case'; import * as ts from 'typescript'; import { TypeSystemHints } from './docs'; import { WARNINGSCODE_FILE_NAME } from './transforms/deprecation-warnings'; import { JSII_DIAGNOSTICS_CODE, _formatDiagnostic } from './utils'; /** * Descriptors for all valid jsii diagnostic codes. * * The `category` or non-error codes can be updated, for example to treat * warnings as errors, or to suppress certain undesirable warnings. */ export class Code< T extends DiagnosticMessageFormatter = DiagnosticMessageFormatter, > { private static readonly byCode: { [code: number]: Code } = {}; private static readonly byName: { [name: string]: Code } = {}; /** * @internal */ public static message<T extends DiagnosticMessageFormatter>({ code, name, formatter, }: { code: number; formatter: T; name: string; }) { return new Code<T>(code, name, ts.DiagnosticCategory.Message, formatter); } /** * @internal */ public static suggestion<T extends DiagnosticMessageFormatter>({ code, name, formatter, }: { code: number; formatter: T; name: string; }) { return new Code<T>(code, name, ts.DiagnosticCategory.Suggestion, formatter); } /** * @internal */ public static warning<T extends DiagnosticMessageFormatter>({ code, name, formatter, }: { code: number; formatter: T; name: string; }) { return new Code<T>(code, name, ts.DiagnosticCategory.Warning, formatter); } /** * @internal */ public static error<T extends DiagnosticMessageFormatter>({ code, name, formatter, }: { code: number; formatter: T; name: string; }) { return new Code<T>(code, name, ts.DiagnosticCategory.Error, formatter); } /** * Get a diagnostic code by code or name. * * @param codeOrName the looked up diagnostic code or name. * * @returns the JsiiDiagnosticCode instande, if one exists, or `undefined` * * @experimental this module is under active development and the error codes * and names may change in the future. */ public static lookup(codeOrName: string | number): Code | undefined { if (typeof codeOrName === 'number') { return this.byCode[codeOrName]; } return this.byName[codeOrName]; } // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility readonly #defaultCategory: ts.DiagnosticCategory; // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility #category?: ts.DiagnosticCategory; // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility #formatter: T; /** * Registers a new diagnostic code. * * @param code the numeric code for the diagnostic * @param name the symbolic name for the diagnostic * @param defaultCategory the default category this diagnostic ransk in * @param formatter a message formatter for easy creation of diagnostics */ private constructor( public readonly code: number, public readonly name: string, defaultCategory: ts.DiagnosticCategory, formatter: T, ) { this.#defaultCategory = defaultCategory; this.#formatter = formatter; if (code in Code.byCode) { throw new Error( `Attempted to create two instances of ${this.constructor.name} with code ${code}`, ); } if (name in Code.byName) { throw new Error( `Attempted to create two instances of ${this.constructor.name} with name ${name}`, ); } Code.byCode[code] = Code.byName[name] = this; } /** * Determines whether this diagnostic is a compilation error. Diagnostics * where this is `true` cannot have their `category` overridden to a lower * category. */ public get isError(): boolean { return this.#defaultCategory === ts.DiagnosticCategory.Error; } /** * The diagnostic category this particular code is filed as. */ public get category(): ts.DiagnosticCategory { return this.#category ?? this.#defaultCategory; } /** * Update the diagnostic category for this particular code. If `isError` is * `true`, attempting to set anything other than `ts.DiagnosticCategory.Error` * will result in an error being throw. * * @param newValue the new diagnostic category to be used. */ public set category(newValue: ts.DiagnosticCategory) { if (this.isError && newValue !== ts.DiagnosticCategory.Error) { throw new Error( `Illegal attempt to override category of error ${this.code} to ${ts.DiagnosticCategory[newValue]}`, ); } this.#category = newValue; } /** * Creates a new `JsiiDiagnostic` message without any source code location * data. * * @param args the arguments to the message formatter. * * @deprecated It is preferred to specify a source code location for problem * markers. Prefer the use of `create` while providing a value * for the `location` parameter whenever possible. */ public createDetached(...args: Parameters<T>): JsiiDiagnostic { return new JsiiDiagnostic(this, this.#formatter(...args)); } /** * Creates a new `JsiiDiagnostic` message with source code location denoted * by the provided `location` node. * * @param location the source code location attachment of the message. * @param args the arguments to the message formatter. */ public create(location: ts.Node, ...args: Parameters<T>): JsiiDiagnostic { return new JsiiDiagnostic(this, this.#formatter(...args), location); } } /** * A jsii-specific diagnostic entry. */ export class JsiiDiagnostic implements ts.Diagnostic { /** * This symbol unequivocally identifies the `JsiiDiagnostic` domain. */ private static readonly DOMAIN = Symbol('jsii'); ////////////////////////////////////////////////////////////////////////////// // 0001 => 0999 -- PACKAGE METADATA PROBLEMS public static readonly JSII_0001_PKG_MISSING_DESCRIPTION = Code.suggestion({ code: 1, formatter: () => `A "description" field should be specified in "package.json"`, name: 'metadata/package-json-missing-description', }); public static readonly JSII_0002_PKG_MISSING_HOMEPAGE = Code.suggestion({ code: 2, formatter: () => `A "homepage" field should be specified in "package.json"`, name: 'metadata/package-json-missing-homepage', }); public static readonly JSII_0003_MISSING_README = Code.warning({ code: 3, formatter: () => `There is no "README.md" file. It is required in order to generate valid PyPI (Python) packages.`, name: 'metadata/missing-readme', }); public static readonly JSII_0004_COULD_NOT_FIND_ENTRYPOINT = Code.error({ code: 4, formatter: (mainFile: string) => `Could not find "main" file: ${mainFile}`, name: 'metadata/could-not-find-entrypoint', }); public static readonly JSII_0005_MISSING_PEER_DEPENDENCY = Code.warning({ code: 5, formatter: (assm: string, reference: string) => `The type "${reference}" is exposed in the public API of this module. ` + `Therefore, the module "${assm}" must also be defined under "peerDependencies". ` + 'This will be auto-corrected unless --no-fix-peer-dependencies was specified.', name: 'metadata/missing-peer-dependency', }); // NOTE: currently not possible to change the severity of this code, // as it's being emitted before the overrides have been loaded public static readonly JSII_0006_MISSING_DEV_DEPENDENCY = Code.warning({ code: 6, formatter: ( dependencyName: string, peerRange: string, minVersion: string, actual: string, ) => `A "peerDependency" on "${dependencyName}" at "${peerRange}" means you ` + `should take a "devDependency" on "${dependencyName}" at "${minVersion}" ` + `(found "${actual}")"`, name: 'metadata/missing-dev-dependency', }); public static readonly JSII_0007_MISSING_WARNINGS_EXPORT = Code.error({ code: 7, formatter: () => 'If you are compiling with --add-deprecation-warnings and your package.json ' + `declares subpath exports, you must include { "./${WARNINGSCODE_FILE_NAME}": "./${WARNINGSCODE_FILE_NAME}" } ` + 'in the set of exports.', name: 'metadata/missing-warnings-export', }); ////////////////////////////////////////////////////////////////////////////// // 1000 => 1999 -- TYPESCRIPT LANGUAGE RESTRICTIONS public static readonly JSII_1000_NO_CONST_ENUM = Code.error({ code: 1000, formatter: () => `Exported "const enum" declarations are not allowed`, name: 'typescript-restrictions/no-const-enum', }); public static readonly JSII_1001_TYPE_HAS_NO_SYMBOL = Code.error({ code: 1001, formatter: () => `Non-primitive types without a symbol cannot be processed.`, name: 'typescript-restrictions/type-has-no-symbol', }); public static readonly JSII_1002_UNSPECIFIED_PROMISE = Code.error({ code: 1002, formatter: () => `Un-specified promise type. Specify it using "Promise<T>"`, name: 'typescript-restrictions/unspecified-promise', }); public static readonly JSII_1003_UNSUPPORTED_TYPE = Code.error({ code: 1003, formatter: (messageText) => messageText, name: 'typescript-restrictions/unsupported-type', }); ////////////////////////////////////////////////////////////////////////////// // 2000 => 2999 -- RESERVED ////////////////////////////////////////////////////////////////////////////// // 3000 => 3999 -- TYPE MODEL COHERENCE public static readonly JSII_3000_EXPORTED_API_USES_HIDDEN_TYPE = Code.error({ code: 3000, formatter: (badFqn) => `Exported APIs cannot use un-exported type "${badFqn}"`, name: 'type-model/exported-api-cannot-use-unexported-type', }); public static readonly JSII_3001_EXPOSED_INTERNAL_TYPE = Code.error({ code: 3001, formatter: (symbol: ts.Symbol, isThisType: boolean, typeUse: string) => `Type ${ isThisType ? `"this" (aka: "${symbol.name}")` : `"${symbol.name}"` } cannot be used as the ${typeUse} because it is private or @internal`, name: 'type-model/use-of-internal-type', }); public static readonly JSII_3002_USE_OF_UNEXPORTED_FOREIGN_TYPE = Code.error({ code: 3002, formatter: (fqn: string, typeUse: string, pkg: { readonly name: string }) => `Type "${fqn}" cannot be used as a ${typeUse} because it is not exported from ${pkg.name}`, name: 'type-model/unexported-foreign-type', }); public static readonly JSII_3003_SYMBOL_IS_EXPORTED_TWICE = Code.error({ code: 3003, formatter: (ns1: string, ns2: string) => `Symbol is exported under two distinct submodules: ${ns1} and ${ns2}`, name: 'type-model/symbol-is-exported-twice', }); public static readonly JSII_3004_INVALID_SUPERTYPE = Code.error({ code: 3004, formatter: (clause: ts.HeritageClause, badDeclaration: ts.Declaration) => { return `Illegal ${clauseType(clause.token)} clause for an exported API: ${ ts.SyntaxKind[badDeclaration.kind] }`; function clauseType(token: ts.SyntaxKind): string { switch (token) { case ts.SyntaxKind.ExtendsKeyword: return 'extends'; case ts.SyntaxKind.ImplementsKeyword: return 'implements'; default: return ts.SyntaxKind[token]; } } }, name: 'type-model/invalid-supertype', }); public static readonly JSII_3005_TYPE_USED_AS_INTERFACE = Code.error({ code: 3005, formatter: (badType: spec.TypeReference) => `Type "${spec.describeTypeReference( badType, )}" cannot be used as an interface`, name: 'type-model/type-used-as-interface', }); public static readonly JSII_3006_TYPE_USED_AS_CLASS = Code.error({ code: 3006, formatter: (badType: spec.TypeReference) => `Type "${spec.describeTypeReference(badType)}" cannot be used as a class`, name: 'type-model/type-used-as-class', }); public static readonly JSII_3007_ILLEGAL_STRUCT_EXTENSION = Code.error({ code: 3007, formatter: (offender: spec.Type, struct: spec.InterfaceType) => `Attempt to extend or implement struct "${struct.fqn}" from "${offender.fqn}"`, name: 'type-model/illegal-struct-extension', }); public static readonly JSII_3008_STRUCT_PROPS_MUST_BE_READONLY = Code.error({ code: 3008, formatter: (propName: string, struct: spec.InterfaceType) => `The "${propName}" property of struct "${struct.fqn}" must be "readonly". Rename "${struct.fqn}" to "I${struct.name}" if it is meant to be a behavioral interface.`, name: 'type-model/struct-props-must-be-readonly', }); public static readonly JSII_3009_OPTIONAL_PARAMETER_BEFORE_REQUIRED = Code.error({ code: 3009, formatter: (param: spec.Parameter, nextParam: spec.Parameter) => `Parameter "${param.name}" cannot be optional, as it precedes required parameter "${nextParam.name}"`, name: 'type-model/optional-parameter-before-required', }); public static readonly JSII_3999_INCOHERENT_TYPE_MODEL = Code.error({ code: 3999, formatter: (messageText) => messageText, name: 'type-model/incoherent-type-model', }); ////////////////////////////////////////////////////////////////////////////// // 4000 => 4999 -- RESERVED ////////////////////////////////////////////////////////////////////////////// // 5000 => 5999 -- LANGUAGE COMPATIBILITY ERRORS public static readonly JSII_5000_JAVA_GETTERS = Code.error({ code: 5000, formatter: (badName: string, typeName: string) => `Methods and properties cannot have names like "getXxx": those conflict with Java property getters. Rename "${typeName}.${badName}"`, name: 'language-compatibility/potential-java-getter-conflict', }); public static readonly JSII_5001_JAVA_SETTERS = Code.error({ code: 5001, formatter: (badName: string, typeName: string) => `Methods and properties cannot have names like "setXxx": those conflict with Java property setters. Rename "${typeName}.${badName}"`, name: 'language-compatibility/potential-java-setter-conflict', }); public static readonly JSII_5002_OVERRIDE_CHANGES_VISIBILITY = Code.error({ code: 5002, formatter: ( newElement: string, action: string, newValue: 'protected' | 'public', oldValue: 'protected' | 'public', ) => `"${newElement}" changes visibility to ${newValue} when ${action}. Change it to ${oldValue}`, name: 'language-compatibility/override-changes-visibility', }); public static readonly JSII_5003_OVERRIDE_CHANGES_RETURN_TYPE = Code.error({ code: 5003, formatter: ( newElement: string, action: string, newValue: string, oldValue: string, ) => `"${newElement}" changes the return type to "${newValue}" when ${action}. Change it to "${oldValue}"`, name: 'language-compatibility/override-changes-return-type', }); public static readonly JSII_5004_OVERRIDE_CHANGES_PROP_TYPE = Code.error({ code: 5004, formatter: ( newElement: string, action: string, newType: spec.TypeReference, oldType: spec.TypeReference, ) => `"${newElement}" changes the property type to "${spec.describeTypeReference( newType, )}" when ${action}. Change it to "${spec.describeTypeReference( oldType, )}"`, name: 'language-compatibility/override-changes-property-type', }); public static readonly JSII_5005_OVERRIDE_CHANGES_PARAM_COUNT = Code.error({ code: 5005, formatter: ( newElement: string, action: string, newCount: number, oldCount: number, ) => `"${newElement}" has ${newCount} parameters when ${action}. It should accept ${oldCount} parameters`, name: 'language-compatibility/override-changes-param-count', }); public static readonly JSII_5006_OVERRIDE_CHANGES_PARAM_TYPE = Code.error({ code: 5006, formatter: ( newElement: string, action: string, newParam: spec.Parameter, oldParam: spec.Parameter, ) => `"${newElement}" changes the type of parameter "${ newParam.name }" to ${spec.describeTypeReference( newParam.type, )} when ${action}. Change it to ${spec.describeTypeReference( oldParam.type, )}`, name: 'language-compatibility/override-changes-param-type', }); public static readonly JSII_5007_OVERRIDE_CHANGES_VARIADIC = Code.error({ code: 5007, formatter: ( newElement: string, action: string, newVariadic = false, oldVariadic = false, ) => `"${newElement}" turns ${ newVariadic ? 'variadic' : 'non variadic' } when ${action}. Make it ${oldVariadic ? 'variadic' : 'non-variadic'}`, name: 'language-compatibility/override-changes-variadic', }); public static readonly JSII_5008_OVERRIDE_CHANGES_PARAM_OPTIONAL = Code.error( { code: 5008, formatter: ( newElement: string, action: string, newParam: spec.Parameter, oldParam: spec.Parameter, ) => `"${newElement}" turns parameter "${newParam.name}" ${ newParam.optional ? 'optional' : 'required' } when ${action}. Make it ${ oldParam.optional ? 'optional' : 'required' }`, name: 'language-compatibility/override-changes-param-optional', }, ); public static readonly JSII_5009_OVERRIDE_CHANGES_PROP_OPTIONAL = Code.error({ code: 5009, formatter: ( newElement: string, action: string, newOptional = false, oldOptional = false, ) => `"${newElement}" turns ${ newOptional ? 'optional' : 'required' } when ${action}. Make it ${oldOptional ? 'optional' : 'required'}`, name: 'language-compatibility/override-changes-prop-optional', }); public static readonly JSII_5010_OVERRIDE_CHANGES_MUTABILITY = Code.error({ code: 5010, formatter: ( newElement: string, action: string, newMutable = false, oldMutable = false, ) => `"${newElement}" turns ${ newMutable ? 'mutable' : 'readonly' } when ${action}. Make it ${oldMutable ? 'mutable' : 'readonly'}`, name: 'language-compatibility/override-changes-mutability', }); public static readonly JSII_5011_SUBMODULE_NAME_CONFLICT = Code.error({ code: 5011, formatter: ( submoduleName: string, typeName: string, reserved: readonly string[], ) => `Submodule "${submoduleName}" conflicts with "${typeName}, as different languages could represent it as: ${reserved .map((x) => `"${x}"`) .join(', ')}"`, name: 'language-compatibility/submodule-name-conflicts', }); public static readonly JSII_5012_NAMESPACE_IN_TYPE = Code.error({ code: 5012, formatter: (typeName: string, namespaceName: string) => `All entities nested under a type (e.g: "${typeName}") must be concrete types, but "${namespaceName}" is a namespace. This structure cannot be supported in all languages (e.g: Java)`, name: 'language-compatibility/namespace-in-type', }); public static readonly JSII_5013_STATIC_INSTANCE_CONFLICT = Code.error({ code: 5013, formatter: (member: string, type: spec.ClassType) => `Member "${member}" of class "${type.fqn}" has both a static and an instance delcaration`, name: 'language-compatibility/static-instance-conflict', }); public static readonly JSII_5014_INHERITED_STATIC_CONFLICT = Code.error({ code: 5014, formatter: ( member: spec.Method | spec.Property, type: spec.ClassType, baseMember: spec.Method | spec.Property, baseType: spec.ClassType, ) => `${member.static ? 'Static' : 'Instance'} member "${ member.name }" of class "${type.fqn}" conflicts with ${ baseMember.static ? 'static' : 'instance' } member in ancestor "${baseType.fqn}"`, name: 'language-compatibility/inherited-static-conflict', }); public static readonly JSII_5015_REDECLARED_INTERFACE_MEMBER = Code.error({ code: 5015, formatter: (memberName: string, iface: spec.InterfaceType) => `Interface "${iface.fqn}" re-declares member "${memberName}". This is not supported as it results in invalid C#.`, name: 'language-compatibility/redeclared-interface-member', }); public static readonly JSII_5016_PROHIBITED_MEMBER_NAME = Code.error({ code: 5016, formatter: (badName: string) => `Members cannot be named "${badName}" as it conflicts with synthetic declarations in some languages.`, name: 'language-compatibility/prohibited-member-name', }); public static readonly JSII_5017_POSITIONAL_KEYWORD_CONFLICT = Code.error({ code: 5017, formatter: (badName: string) => `Parameter name "${badName}" is also the name of a property in a struct parameter. Rename the positional parameter.`, name: 'language-compatibility/positional-keyword-conflict', }); public static readonly JSII_5018_RESERVED_WORD = Code.warning({ code: 5018, formatter: (badName: string, languages: readonly string[]) => `"${badName}" is a reserved word in ${languages.join( ', ', )}. Using this name may cause problems when generating language bindings. Consider a different name.`, name: 'language-compatibility/reserved-word', }); public static readonly JSII_5019_MEMBER_TYPE_NAME_CONFLICT = Code.warning({ code: 5019, formatter: ( memberKind: 'method' | 'property', memberSymbol: ts.Symbol, declaringType: spec.Type, ) => `The ${memberKind} name "${memberSymbol.name}" conflicts with the declaring ${declaringType.kind} "${declaringType.name}". This will result in renaming the ${declaringType.kind} to "_${declaringType.name}" in C#. Consider renaming "${memberSymbol.name}".`, name: 'language-compatibility/member-name-conflicts-with-type-name', }); public static readonly JSII_5020_STATIC_MEMBER_CONFLICTS_WITH_NESTED_TYPE = Code.error({ code: 5020, formatter: ( nestingType: spec.Type, staticMember: spec.Property | spec.Method | spec.EnumMember, nestedType: spec.Type, ) => `The static member "${nestingType.name}.${staticMember.name}" has the same PascalCased representation as nested type "${nestingType.name}.${nestedType.name}". This would result in invalid code in Go.`, name: 'language-compatibility/static-member-name-conflicts-with-nested-type', }); ////////////////////////////////////////////////////////////////////////////// // 6000 => 6999 -- RESERVED ////////////////////////////////////////////////////////////////////////////// // 7000 => 7999 -- DOCUMENTATION ERRORS public static readonly JSII_7000_NON_EXISTENT_PARAMETER = Code.warning({ code: 7000, formatter: (method: spec.Method, param: string) => `Documentation for method "${method.name}" refers to non-existent @param "${param}"`, name: 'documentation/non-existent-parameter', }); public static readonly JSII_7001_ILLEGAL_HINT = Code.error({ code: 7001, formatter: (hint: keyof TypeSystemHints, ...valid: readonly string[]) => `Illegal use of "@${hint}" hint. It is only valid on ${valid.join( ', ', )}.`, name: 'documentation/illegal-hint', }); public static readonly JSII_7999_DOCUMENTATION_ERROR = Code.error({ code: 7999, formatter: (messageText) => messageText, name: 'documentation/documentation-error', }); ////////////////////////////////////////////////////////////////////////////// // 8000 => 8999 -- JSII STYLE ENFORCEMENT public static readonly JSII_8000_PASCAL_CASED_TYPE_NAMES = Code.error({ code: 8000, formatter: (badName: string) => `Type names must be CamelCased. Rename "${badName}" to "${pascal( badName, )}"`, name: 'code-style/type-names-must-use-pascal-case', }); public static readonly JSII_8001_ALL_CAPS_ENUM_MEMBERS = Code.error({ code: 8001, formatter: (badName: string, typeName: string) => `Enum members must be ALL_CAPS. Rename "${typeName}.${badName}" to "${allCaps( badName, )}"`, name: 'code-style/enum-members-must-use-all-caps', }); public static readonly JSII_8002_CAMEL_CASED_MEMBERS = Code.error({ code: 8002, formatter: (badName: string, typeName: string) => `Method and property (unless they are static readonly) names must use camelCase. Rename "${typeName}.${badName}" to "${camel( badName, )}"`, name: 'code-style/member-names-must-use-camel-case', }); public static readonly JSII_8003_STATIC_CONST_CASING = Code.error({ code: 8003, formatter: (badName: string, typeName: string) => `Static constant names must use ALL_CAPS, PascalCase, or camelCase. Rename "${typeName}.${badName}" to "${allCaps( badName, )}"`, name: 'code-style/static-readonly-property-casing', }); public static readonly JSII_8004_SUBMOULE_NAME_CASING = Code.error({ code: 8004, formatter: (badName: string) => `Submodule namespaces must be camelCased or snake_cased. Rename "${badName}" to ${camel( badName, )}`, name: 'code-style/submodule-name-casing', }); public static readonly JSII_8005_INTERNAL_UNDERSCORE = Code.error({ code: 8005, formatter: (badName: string) => `Members marked with @internal must have a name starting with "_". Rename "${badName}" to "_${badName}"`, name: 'code-style/internal-members-underscore-prefix', }); public static readonly JSII_8006_UNDERSCORE_INTERNAL = Code.error({ code: 8006, formatter: (badName: string) => `Members with a name starting with "_" (e.g: "${badName}") must be marked @internal`, name: 'code-style/underscored-members-must-be-internal', }); public static readonly JSII_8007_BEHAVIORAL_INTERFACE_NAME = Code.error({ code: 8007, formatter: (badName: string) => `Interface contains behavior. Rename "${badName}" to "I${badName}"`, name: 'code-style/behavioral-interface-name', }); ////////////////////////////////////////////////////////////////////////////// // 9000 => 9999 -- SURPRISING ERRORS & INFORMATIONAL MESSAGES public static readonly JSII_9000_UNKNOWN_MODULE = Code.error({ code: 9000, formatter: (moduleName) => `Encountered use of module that is not declared in "dependencies" or "peerDependencies": "${moduleName}"`, name: 'miscellaneous/unknown-module', }); public static readonly JSII_9001_TYPE_NOT_FOUND = Code.error({ code: 9001, formatter: (typeRef: spec.NamedTypeReference) => `Type not found in the corresponding assembly: "${typeRef.fqn}"`, name: 'miscellaneous/type-not-found', }); public static readonly JSII_9002_UNRESOLVEABLE_TYPE = Code.error({ code: 9002, formatter: (reference: string) => `Unable to resolve type "${reference}". It may be @internal or not exported from the module's entry point (as configured in "package.json" as "main").`, name: 'miscellaneous/unresolveable-type', }); public static readonly JSII_9003_UNRESOLVEABLE_MODULE = Code.error({ code: 9003, formatter: (location: string) => `Unable to resolve module location "${location}"`, name: 'miscellaneous/unresolveable-module', }); public static readonly JSII_9004_UNABLE_TO_COMPUTE_SIGNATURE = Code.error({ code: 9004, formatter: (methodName: string, type: spec.Type) => `Unable to compute signature for method "${methodName}" of "${type.fqn}"`, name: 'miscellaneous/unable-to-compute-signature', }); public static readonly JSII_9996_UNNECESSARY_TOKEN = Code.message({ code: 9996, formatter: () => 'Unnecessary token, consider removing it', name: 'miscellaneous/unnecessary-token', }); public static readonly JSII_9997_UNKNOWN_ERROR = Code.error({ code: 9997, formatter: (error: Error) => `Unknown error: ${error.message} -- ${error.stack}`, name: 'miscellaneous/unknown-error', }); public static readonly JSII_9998_UNSUPPORTED_NODE = Code.message({ code: 9998, formatter: (kindOrMessage: ts.SyntaxKind | string) => typeof kindOrMessage === 'string' ? kindOrMessage : `Unsupported ${ts.SyntaxKind[kindOrMessage]} node. This declaration will not be accessible from other languages.`, name: 'miscellaneous/unsupported-node', }); private static readonly JSII_9999_RELATED_INFO = Code.suggestion({ code: 9999, formatter: (messageText) => messageText, name: 'miscellaneous/related-info', }); ////////////////////////////////////////////////////////////////////////////// /** * Determines whether a `Diagnostic` instance is a `JsiiDiagnostic` or not. * @param diag */ public static isJsiiDiagnostic(diag: ts.Diagnostic): diag is JsiiDiagnostic { return (diag as unknown as JsiiDiagnostic).domain === JsiiDiagnostic.DOMAIN; } private readonly domain = JsiiDiagnostic.DOMAIN; public readonly category: ts.DiagnosticCategory; public readonly code: number = JSII_DIAGNOSTICS_CODE; public readonly jsiiCode: number; public readonly messageText: string | ts.DiagnosticMessageChain; public readonly file: ts.SourceFile | undefined; public readonly start: number | undefined; public readonly length: number | undefined; public readonly relatedInformation = new Array<ts.DiagnosticRelatedInformation>(); // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility #formatted?: string; /** * Creates a new `JsiiDiagnostic` with the provided properties. * * @internal */ public constructor( code: Code, messageText: string | ts.DiagnosticMessageChain, location?: ts.Node, ) { this.category = code.category; this.jsiiCode = code.code; this.messageText = messageText; if (location != null) { this.file = location.getSourceFile(); this.start = location.getStart(this.file); this.length = location.getEnd() - this.start; } } public addRelatedInformation( node: ts.Node, message: JsiiDiagnostic['messageText'], ): this { this.relatedInformation.push( JsiiDiagnostic.JSII_9999_RELATED_INFO.create(node, message), ); // Clearing out #formatted, as this would no longer be the correct string. this.#formatted = undefined; return this; } /** * Formats this diagnostic with color and context if possible, and returns it. * The formatted diagnostic is cached, so that it can be re-used. This is * useful for diagnostic messages involving trivia -- as the trivia may have * been obliterated from the `SourceFile` by the `TsCommentReplacer`, which * makes the error messages really confusing. */ public format(projectRoot: string): string { if (this.#formatted == null) { this.#formatted = _formatDiagnostic(this, projectRoot); } return this.#formatted; } /** * Ensures the formatted diagnostic is prepared for later re-use. * * @returns `this` */ public preformat(projectRoot: string): this { this.format(projectRoot); return this; } } export type DiagnosticMessageFormatter = ( ...args: any[] ) => JsiiDiagnostic['messageText']; export function configureCategories(records: { [code: string]: ts.DiagnosticCategory; }) { for (const [code, category] of Object.entries(records)) { const diagCode = Code.lookup(diagnosticCode(code)); if (!diagCode) { throw new Error(`Unrecognized diagnostic code '${code}'`); } diagCode.category = category; } } function diagnosticCode(str: string): string | number { if (str.toLowerCase().startsWith('jsii')) { const re = /^JSII(\d+)$/i.exec(str); if (re) { return parseInt(re[1], 10); } throw new Error( `Invalid diagnostic code ${str}. A number must follow code that starts with 'JSII'`, ); } return str; }
the_stack
import CommonUtils from "../../utils/CommonUtils"; import { BlockRegData } from "../Define/BlockDef"; import { BlockPort } from "../Define/Port"; import { ValMap } from "../Define/ValMap"; export default { register, packageName: 'Dictionary', version: 1, } function register() { //#region 创建映射 let CreateDictionary = new BlockRegData("17486C99-2A43-B144-AF7D-765D117A2716", "创建映射", '创建一个映射', '', '映射') CreateDictionary.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INKEY0', paramType: 'any', name: '键0', portAnyFlexable: { flexableA: true } }, { direction: 'input', guid: 'INVAL0', paramType: 'any', name: '值0', portAnyFlexable: { flexableB: true, } }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTSET', paramType: 'any', paramDictionaryKeyType: 'any', paramSetType: 'dictionary', name: '映射', description: '生成的映射对象', portAnyFlexable: { flexableB: { get: 'paramType', set: 'paramType' }, flexableA: { get: 'paramDictionaryKeyType', set: 'paramDictionaryKeyType' }, }, } ]; CreateDictionary.portAnyFlexables = { flexableA: { setResultToOptions: 'opTypeA' }, flexableB: { setResultToOptions: 'opTypeB' }, } CreateDictionary.settings.parametersChangeSettings.userCanAddInputParameter = true; CreateDictionary.callbacks.onCreate = (block) => { if(!CommonUtils.isDefined(block.options['opTypeA'])) block.options['opTypeA'] = 'any'; if(!CommonUtils.isDefined(block.options['opTypeB'])) block.options['opTypeB'] = 'any'; }; CreateDictionary.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let INKEY0 = block.getPortByGUID('INKEY0'); let INVAL0 = block.getPortByGUID('INVAL0'); let map = new ValMap(INKEY0.paramType, INVAL0.paramType); if(!map.created()) { block.throwError('创建映射失败,因为 ' + INKEY0.paramType.getType() + ' 不可作为键值,键值类型必须含有 getHashCode 函数', INKEY0); return; } Object.keys(block.inputPorts).forEach((key) => { let port = (<BlockPort>block.inputPorts[key]); if(port.guid.startsWith('INKEY')) { let INVAL = block.inputPorts['INVAL' + port.guid.substring(5)]; if(INVAL) { let k = block.getInputParamValue(port), v = block.getInputParamValue(INVAL); if(CommonUtils.isDefinedAndNotNull(k) && CommonUtils.isDefinedAndNotNull(v)) map.set(k, v); } } }); block.setOutputParamValue('OUTSET', map); block.activeOutputPort('OUT'); } }; CreateDictionary.callbacks.onUserAddPort = (block, direction, type) => { block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 2 : 1; return [ { guid: 'INKEY' + block.data['portCount'], direction: 'input', paramType: block.options['opTypeA'], name: '键' + block.data['portCount'], portAnyFlexable: { flexableA: true } }, { guid: 'INVAL' + block.data['portCount'], direction: 'input', paramType: block.options['opTypeB'], name: '值' + block.data['portCount'], portAnyFlexable: { flexableB: true } }, ] }; CreateDictionary.callbacks.onPortRemove = (block, port) => { if(port.guid.startsWith('INKEY')) { let id = port.guid.substr(5); let port2 = block.getPortByGUID('INVAL' + id); if(port2) block.deletePort(port2); }else if(port.guid.startsWith('INVAL')) { let id = port.guid.substr(5); let port2 = block.getPortByGUID('INKEY' + id); if(port2) block.deletePort(port2); } }; //#endregion //#region 存在 let DictionaryHas = new BlockRegData("AAACBE43-B537-162D-A399-5FF58C841987", "存在", '检查某个元素是否在映射中存在', '', '映射') DictionaryHas.ports = [ { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'dictionary', description: '搜索项目的目标映射', portAnyFlexable: { flexableA: { get: 'paramDictionaryKeyType', set: 'paramDictionaryKeyType' }, flexableB: { get: 'paramType', set: 'paramType' } }, }, { direction: 'input', guid: 'INKEY', paramType: 'any', description: '要检查的键值', portAnyFlexable: { flexableA: true }, }, { direction: 'output', guid: 'OUTCONTAINS', paramType: 'boolean', description: '指定元素是否存在?', }, ]; DictionaryHas.portAnyFlexables = { flexableA: {}, flexableB: {}, } DictionaryHas.blockStyle.noTitle = true; DictionaryHas.blockStyle.logoBackground = '<span class="big-title">映射中存在</span>'; DictionaryHas.blockStyle.minWidth = '160px'; DictionaryHas.callbacks.onPortParamRequest = (block, port, context) => { if(port.guid == 'OUTCONTAINS') { let map = <ValMap>block.getInputParamValue('INSET', context); let key = block.getInputParamValue('INKEY', context); return map.has(key); } }; //#endregion //#region 添加 let DictionarySet = new BlockRegData("DF9B4BF1-8D43-1486-AE24-538B58DF9EF6", "设置", '设置映射中指定键的元素', '', '映射') DictionarySet.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'dictionary', portAnyFlexable: { flexableA: { get: 'paramDictionaryKeyType', set: 'paramDictionaryKeyType' }, flexableB: { get: 'paramType', set: 'paramType' }, }, }, { direction: 'input', guid: 'INKEY', paramType: 'any', description: '要设置的键', portAnyFlexable: { flexableA: true }, }, { direction: 'input', guid: 'INITEM', paramType: 'any', description: '要设置的元素', portAnyFlexable: { flexableB: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, ]; DictionarySet.portAnyFlexables = { flexableA: {}, flexableB: {}, } DictionarySet.blockStyle.noTitle = true; DictionarySet.blockStyle.logoBackground = '<span class="big-title">设置映射元素</span>'; DictionarySet.blockStyle.minWidth = '170px'; DictionarySet.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let map = <ValMap>block.getInputParamValue('INSET'); let key = block.getInputParamValue('INKEY'); let item = block.getInputParamValue('INITEM'); map.set(key, item); block.activeOutputPort('OUT'); } }; //#endregion //#region 移除 let DictionaryRemove = new BlockRegData("7C0959BD-DAA6-6F9B-6D72-AA33AAD47646", "移除", '从映射中移除元素', '', '映射') DictionaryRemove.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'dictionary', portAnyFlexable: { flexable: { get: 'paramDictionaryKeyType', set: 'paramDictionaryKeyType' } }, }, { direction: 'input', guid: 'INKEY', paramType: 'any', description: '要移除的元素键', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTRMED', paramType: 'boolean', description: '如果有元素被移除,返回真(返回假说明映射中没有对应的键)', }, ]; DictionaryRemove.portAnyFlexables = { flexable: {}, } DictionaryRemove.blockStyle.noTitle = true; DictionaryRemove.blockStyle.logoBackground = '<span class="big-title">映射移除元素</span>'; DictionaryRemove.blockStyle.minWidth = '170px'; DictionaryRemove.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let map = <ValMap>block.getInputParamValue('INSET'); let key = block.getInputParamValue('INKEY'); block.setOutputParamValue('OUTRMED', map.delete(key)); block.activeOutputPort('OUT'); } }; //#endregion //#region 清空映射 let DictionaryClear = new BlockRegData("040EC273-89EC-B657-C76E-7FAA821ED459", "清空映射", '清空一个映射,移除所有元素', '', '映射') DictionaryClear.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'dictionary', portAnyFlexable: { flexable: true } }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, ]; DictionaryClear.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let map = <ValMap>block.getInputParamValue('INSET'); map.clear(); block.activeOutputPort('OUT'); } }; DictionaryClear.portAnyFlexables = { flexable: {}, } DictionaryClear.blockStyle.noTitle = true; DictionaryClear.blockStyle.logoBackground = '<span class="big-title">清空映射</span>'; DictionaryClear.blockStyle.minWidth = '140px'; //#endregion //#region 映射长度 let DictionaryLength = new BlockRegData("04261532-8B7F-D8CE-837F-00B0E3787138", "映射长度", '获取映射中元素的个数', '', '映射'); DictionaryLength.ports = [ { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'dictionary', portAnyFlexable: { flexable: true } }, { direction: 'output', guid: 'OUTLEN', paramType: 'number', description: '映射中元素的个数', }, ]; DictionaryLength.callbacks.onPortParamRequest = (block, port, context) => { if(port.guid == 'OUTLEN') { let map = <ValMap>block.getInputParamValue('INSET', context); return map.map.size; } }; DictionaryLength.portAnyFlexables = { flexable: {}, } DictionaryLength.blockStyle.noTitle = true; DictionaryLength.blockStyle.logoBackground = '<span class="big-title">映射长度</span>'; DictionaryLength.blockStyle.minWidth = '150px'; //#endregion //#region 所有键 let DictionaryAllKeys = new BlockRegData("BFC4636E-5182-F9B7-FABD-676A711D8FF9", "所有键", '获取映射中所有键为数组', '', '映射') DictionaryAllKeys.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'dictionary', description: '搜索项目的目标映射', portAnyFlexable: { flexable: { get: 'paramDictionaryKeyType', set: 'paramDictionaryKeyType' } }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, { direction: 'output', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'array', description: '此映射的所有键', portAnyFlexable: { flexable: true }, }, ]; DictionaryAllKeys.portAnyFlexables = { flexable: {}, } DictionaryAllKeys.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let map = <ValMap>block.getInputParamValue('INSET'); block.setOutputParamValue('OUTARRAY', Array.from(map.map.keys())); block.activeOutputPort('OUT'); } }; DictionaryAllKeys.blockStyle.noTitle = true; DictionaryAllKeys.blockStyle.logoBackground = '<span class="big-title">映射所有键</span>'; DictionaryAllKeys.blockStyle.minWidth = '170px'; //#endregion //#region 所有值 let DictionaryAllValues = new BlockRegData("716BBE19-DCA5-13CB-7679-A87FB52714FC", "所有值", '获取映射中所有值为数组', '', '映射') DictionaryAllValues.ports = [ { direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'dictionary', description: '搜索项目的目标映射', portAnyFlexable: { flexable: { get: 'paramType', set: 'paramType' } }, }, { direction: 'input', guid: 'OUTARRAY', paramType: 'any', paramSetType: 'dictionary', description: '此映射的所有值数组', portAnyFlexable: { flexable: true }, }, { direction: 'output', guid: 'OUT', paramType: 'execute', }, ]; DictionaryAllValues.portAnyFlexables = { flexable: {}, } DictionaryAllValues.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { let map = <ValMap>block.getInputParamValue('INSET'); block.setOutputParamValue('OUTARRAY', Array.from(map.map.values())); block.activeOutputPort('OUT'); } }; DictionaryAllValues.blockStyle.noTitle = true; DictionaryAllValues.blockStyle.logoBackground = '<span class="big-title">映射所有值</span>'; DictionaryAllValues.blockStyle.minWidth = '170px'; //#endregion //#region For Each Loop let DictionaryForeach = new BlockRegData("9CE385D7-2396-E9D2-4F76-97F8CDB8DFE5", "For Each Loop (映射)", '遍历循环指定的映射', '', '映射'); DictionaryForeach.baseInfo.logo = require('../../assets/images/BlockIcon/loop.svg'); DictionaryForeach.ports = [ { name: "进入", direction: 'input', guid: 'IN', defaultConnectPort: true, paramType: 'execute', }, { name: "映射", description: '要遍历的映射', direction: 'input', guid: 'INSET', paramType: 'any', paramSetType: 'dictionary', portAnyFlexable: { flexableA: { get: 'paramDictionaryKeyType', set: 'paramDictionaryKeyType' }, flexableB: { get: 'paramType', set: 'paramType' } }, }, { name: "终止", description: '终止遍历循环', direction: 'input', guid: 'BREAK', paramType: 'execute', }, { guid: 'LOOPBODY', paramType: 'execute', direction: 'output', name: '循环体', }, { guid: 'ELEMENT', paramType: 'number', direction: 'output', name: '当前元素', portAnyFlexable: { flexableB: true }, }, { guid: 'KEY', paramType: 'any', direction: 'output', name: '当前键值', portAnyFlexable: { flexableA: true }, }, { guid: 'EXIT', paramType: 'execute', direction: 'output', name: '循环结束' }, ]; DictionaryForeach.portAnyFlexables = { flexableA: {}, flexableB: {}, } DictionaryForeach.callbacks.onPortExecuteIn = (block, port) => { if(port.guid == 'IN') { var variables = block.variables(); variables['breakActived'] = false; let KEY = block.getPortByGUID('KEY'); let EXIT = block.getPortByGUID('EXIT'); let LOOP = block.getPortByGUID('LOOP'); let ELEMENT = block.getPortByGUID('ELEMENT'); let map = <ValMap>block.getInputParamValue('SET'); let breakActived = variables['breakActived']; let keys = map.map.keys(); let key = keys.next() while(!key.done) { block.setOutputParamValue(ELEMENT, map.get(key.value)); block.setOutputParamValue(KEY, key.value); block.activeOutputPort(LOOP); breakActived = variables['breakActived']; if(breakActived) break; key = keys.next(); } block.activeOutputPort(EXIT); }else if(port.guid == 'BREAK') { var variables = block.variables(); variables['breakActived'] = true; } }; //#endregion return [ CreateDictionary, DictionaryHas, DictionarySet, DictionaryRemove, DictionaryClear, DictionaryLength, DictionaryAllKeys, DictionaryAllValues, DictionaryForeach, ]; }
the_stack
'use strict'; import { Parser as parser } from 'acorn'; import * as walk from 'acorn-walk'; import { EOL } from 'os'; function isTopLevelDeclaration(state) { return ( state.ancestors[state.ancestors.length - 2] === state.body || state.ancestors[state.ancestors.length - 2] === state.tryStatementBody ); } type State = { body: BodyDeclaration; tryStatementBody: BodyDeclaration; lines: string[]; containsAwait: boolean; containsReturn: boolean; hoistedDeclarations: string[]; variablesToDeclare: string[]; ancestors: BaseNode<string>[]; getAdjustment: (line: number) => { adjustedColumns: Map<OldColumn, NewColumn>; firstOriginallyAdjustedColumn?: number; totalAdjustment: number; }; }; export type LineNumber = number; export type OldColumn = number; export type NewColumn = number; // eslint-disable-next-line @typescript-eslint/no-empty-function const noop = () => {}; const visitorsWithoutAncestors = { ClassDeclaration(node, state: State, c) { if (isTopLevelDeclaration(state)) { const textToInsert = `this.${node.id.name} = `; // state.hoistedDeclarations.push(textToInsert); state.variablesToDeclare.push(node.id.name); const line = state.lines[node.loc.start.line - 1]; const adjustment = state.getAdjustment(node.loc.start.line); let totalAdjustment = adjustment.totalAdjustment; state.lines[node.loc.start.line - 1] = `${line.substring( 0, node.loc.start.column + totalAdjustment )}${textToInsert}${line.substring(node.loc.start.column + totalAdjustment)}`; // 1.a Track this adjustment adjustment.adjustedColumns.set( node.loc.start.column, node.loc.start.column + totalAdjustment + textToInsert.length ); adjustment.firstOriginallyAdjustedColumn = adjustment.firstOriginallyAdjustedColumn ?? node.loc.start.column; adjustment.totalAdjustment += textToInsert.length; } walk.base.ClassDeclaration(node, state, c); }, ForOfStatement(node, state: State, c) { if (node.await === true) { state.containsAwait = true; } walk.base.ForOfStatement(node, state, c); }, FunctionDeclaration(node, state) { const textToInsert = `this.${node.id.name} = ${node.id.name}; `; // state.hoistedDeclarations.push(textToInsert); state.variablesToDeclare.push(node.id.name); const line = state.lines[node.loc.start.line - 1]; const adjustment = state.getAdjustment(node.loc.start.line); let totalAdjustment = adjustment.totalAdjustment; // 1. First add the leading `(` (only if we have array or object patterns, i.e `var {a} = ...`) state.lines[node.loc.start.line - 1] = `${line.substring( 0, node.loc.start.column + totalAdjustment )}${textToInsert}${line.substring(node.loc.start.column + totalAdjustment)}`; // 1.a Track this adjustment adjustment.adjustedColumns.set( node.loc.start.column, node.loc.start.column + totalAdjustment + textToInsert.length ); adjustment.firstOriginallyAdjustedColumn = adjustment.firstOriginallyAdjustedColumn ?? node.loc.start.column; adjustment.totalAdjustment += textToInsert.length; }, FunctionExpression: noop, ArrowFunctionExpression: noop, MethodDefinition: noop, AwaitExpression(node, state: State, c) { state.containsAwait = true; walk.base.AwaitExpression(node, state, c); }, ReturnStatement(node, state: State, c) { state.containsReturn = true; walk.base.ReturnStatement(node, state, c); }, VariableDeclaration(node: VariableDeclaration, state: State, c) { const variableKind = node.kind; const isIterableForDeclaration = ['ForOfStatement', 'ForInStatement'].includes( state.ancestors[state.ancestors.length - 2].type ); if (variableKind === 'var' || isTopLevelDeclaration(state)) { const line = state.lines[node.loc.start.line - 1]; // Replace `var xyz = 1234` with `xyz = 1234` or `xyz=undefined` // Replace `var xyz ` with `xyz = undefined` // Replace `var xyz, abc ` with `xyz = undefined, abc = undefined` // Replace `var xyz = 1234` with `xyz = 1234` or `xyz=undefined` depending on the number of declarations we have // Remember for each declaration we already wrap with `(..)`, hence if we have just one variable, then // no need of wrapping with `(..)`, else we unnecessarily end up with two. const replacement = node.declarations.length === 1 ? '' : ''; state.lines[node.loc.start.line - 1] = line.replace(node.kind, replacement); const adjustment = state.getAdjustment(node.loc.start.line); // Track adjustments. adjustment.firstOriginallyAdjustedColumn = adjustment.firstOriginallyAdjustedColumn ?? node.loc.start.column; adjustment.totalAdjustment += replacement.length - node.kind.length; if (!isIterableForDeclaration) { node.declarations.forEach((decl) => { // The name of the variable will start and end in the same line, hence we can use either `start.line` or `end.line` const declarationLine = state.lines[decl.id.loc.start.line - 1]; let currentAdjustments = state.getAdjustment(decl.id.loc.start.line); let totalAdjustment = currentAdjustments.totalAdjustment; if (decl.id.type === 'ArrayPattern' || decl.id.type === 'ObjectPattern') { // 1. First add the leading `(` (only if we have array or object patterns, i.e `var {a} = ...`) state.lines[decl.id.loc.start.line - 1] = `${declarationLine.substring( 0, decl.id.loc.start.column + totalAdjustment )}(${declarationLine.substring(decl.id.loc.start.column + totalAdjustment)}`; // 1.a Track this adjustment currentAdjustments.adjustedColumns.set( decl.id.loc.start.column, decl.id.loc.start.column + totalAdjustment + '('.length ); currentAdjustments.firstOriginallyAdjustedColumn = currentAdjustments.firstOriginallyAdjustedColumn ?? decl.id.loc.start.column; currentAdjustments.totalAdjustment += '('.length; } // 2. Next add the trailing `)` (if we don't have a variable initialize, then initialize to `undefined`) const trailingBrackets = decl.id.type === 'ArrayPattern' || decl.id.type === 'ObjectPattern' ? ')' : ''; const textToAdd = decl.init ? trailingBrackets : `=undefined${trailingBrackets}`; const endLine = state.lines[decl.loc.end.line - 1]; currentAdjustments = state.getAdjustment(decl.loc.end.line); totalAdjustment = currentAdjustments.totalAdjustment; state.lines[decl.loc.end.line - 1] = `${endLine.substring( 0, decl.loc.end.column + totalAdjustment )}${textToAdd}${endLine.substring(decl.loc.end.column + totalAdjustment)}`; // 2.a Track this adjustment currentAdjustments.adjustedColumns.set( decl.loc.end.column, decl.loc.end.column + totalAdjustment + textToAdd.length ); currentAdjustments.firstOriginallyAdjustedColumn = currentAdjustments.firstOriginallyAdjustedColumn ?? decl.loc.end.column; currentAdjustments.totalAdjustment += textToAdd.length; }); } // eslint-disable-next-line no-inner-declarations function registerVariableDeclarationIdentifiers(node) { switch (node.type) { case 'Identifier': state.variablesToDeclare.push(node.name); break; case 'ObjectPattern': node.properties.forEach((property) => { registerVariableDeclarationIdentifiers(property.value); }); break; case 'ArrayPattern': node.elements.forEach((element) => { registerVariableDeclarationIdentifiers(element); }); break; } } node.declarations.forEach((decl) => { registerVariableDeclarationIdentifiers(decl.id); }); } walk.base.VariableDeclaration(node as any, state, c); } }; // Hijack the node visitors, Remember, code is copied from node repo. // If its good for them, its good for us. const visitors = {}; for (const nodeType of Object.keys(walk.base)) { const callback = visitorsWithoutAncestors[nodeType] || walk.base[nodeType]; visitors[nodeType] = (node, state, c) => { const isNew = node !== state.ancestors[state.ancestors.length - 1]; if (isNew) { state.ancestors.push(node); } callback(node, state, c); if (isNew) { state.ancestors.pop(); } }; } /** * Changes code to support top level awaits. * @param {boolean} [supportBreakingOnExceptionsInDebugger] * `Defaults to false` * This flag enables exception breakpionts when debugging by simply wrapping the code in a try..catch. * Currently a flag so we can turn this on/off. */ export function processTopLevelAwait( expectedImports: string, src: string, supportBreakingOnExceptionsInDebugger?: boolean ) { let wrapPrefix: string; let wrapped: string; if (supportBreakingOnExceptionsInDebugger) { // for some reason not having a try..catch won't allow debugger to break on unhandled exceptions. wrapPrefix = '(async () => { try { '; wrapped = `${expectedImports}${EOL}${wrapPrefix}${EOL}${src}${EOL}} catch (__compilerEx){throw __compilerEx;}})()`; } else { wrapPrefix = '(async () => { '; wrapped = `${expectedImports}${EOL}${wrapPrefix}${EOL}${src}${EOL}})()`; } let root; try { root = parser.parse(wrapped, { ecmaVersion: 'latest', locations: true }); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (e: any) { // If the parse error is before the first "await", then use the execution // error. Otherwise we must emit this parse error, making it look like a // proper syntax error. const awaitPos = src.indexOf('await'); const errPos = e.pos - wrapPrefix.length; if (awaitPos > errPos) throw e; // Convert keyword parse errors on await into their original errors when // possible. if (errPos === awaitPos + 6 && e.message.includes('Expecting Unicode escape sequence')) return null; if (errPos === awaitPos + 7 && e.message.includes('Unexpected token')) return null; const line = e.loc.line; const column = line === 1 ? e.loc.column - wrapPrefix.length : e.loc.column; let message = '\n' + src.split('\n')[line - 1] + '\n' + ' '.repeat(column) + '^\n\n' + e.message.replace(new RegExp(/ \([^)]+\)/), ''); // V8 unexpected token errors include the token string. if (message.endsWith('Unexpected token')) message += " '" + // Wrapper end may cause acorn to report error position after the source (src[e.pos - wrapPrefix.length] ?? src[src.length - 1]) + "'"; // eslint-disable-next-line no-restricted-syntax throw new SyntaxError(message); } let body = root.body[root.body.length - 1].expression.callee.body; let tryStatementBody: undefined | any; if ( supportBreakingOnExceptionsInDebugger && 'body' in body && Array.isArray(body.body) && body.body.length === 1 && body.body[0].type === 'TryStatement' ) { tryStatementBody = body; body = body.body[0].block; } const linesUpdated = new Map< LineNumber, { adjustedColumns: Map<OldColumn, NewColumn>; firstOriginallyAdjustedColumn?: number; totalAdjustment: number } >(); const state: State = { body, tryStatementBody, ancestors: [], lines: wrapped.split(/\r?\n/), hoistedDeclarations: [], variablesToDeclare: [], containsAwait: false, containsReturn: false, getAdjustment }; function getAdjustment(line: number) { if (linesUpdated.has(line)) { return linesUpdated.get(line)!; } const declarationAdjustments = { adjustedColumns: new Map<OldColumn, NewColumn>(), firstOriginallyAdjustedColumn: undefined, totalAdjustment: 0 }; linesUpdated.set(line, declarationAdjustments); return declarationAdjustments; } walk.recursive(body as any, state, visitors); // // Do not transform if // // 1. False alarm: there isn't actually an await expression. // // 2. There is a top-level return, which is not allowed. // if (!state.containsAwait || state.containsReturn) { // return null; // } // Possible theres no code (e.g. if you have an import that is not used, then the body of // the try..catch that we add is empty, meaning the body is now empty) // let lastLineNumber = -1; if (body.body.length) { const last = body.body[body.body.length - 1] as ExpressionStatement; if (last.type === 'ExpressionStatement') { // lastLineNumber = last.loc.start.line; const lastLine = state.lines[last.loc.start.line - 1]; const currentAdjustments = state.getAdjustment(last.loc.start.line); state.lines[last.loc.start.line - 1] = `${lastLine.substring( 0, last.loc.start.column + currentAdjustments.totalAdjustment )}return (${lastLine.substring(last.loc.start.column + currentAdjustments.totalAdjustment)}`; currentAdjustments.totalAdjustment += 'return ('.length; currentAdjustments.firstOriginallyAdjustedColumn = currentAdjustments.firstOriginallyAdjustedColumn ?? last.loc.start.column; // Keep track to udpate source maps; // Ok, now we need to add the `)` const endLine = state.lines[last.loc.end.line - 1]; const indexOfLastSimiColon = endLine.lastIndexOf(';'); // Remember, last character would be `;`, we need to add `)` before that. // Also we're using typescript compiler, hence it would add the necessary `;`. state.lines[last.loc.end.line - 1] = `${endLine.substring(0, indexOfLastSimiColon)})${endLine.substring( indexOfLastSimiColon )}`; } } // Add the variable declarations & hoisted functions/vars. const variables = state.variablesToDeclare.length ? `var ${state.variablesToDeclare.join(',')};` : ''; const hoisted = state.hoistedDeclarations.length ? state.hoistedDeclarations.join(' ') : ''; state.lines[1] = `${variables}${state.lines[1]}${hoisted}`; return { updatedCode: state.lines.join(EOL), linesUpdated }; } type BaseNode<T> = { type: T; start: number; end: number; loc: BodyLocation; range?: [number, number]; }; type TokenLocation = { line: number; column: number }; type BodyLocation = { start: TokenLocation; end: TokenLocation }; // type LocationToFix = FunctionDeclaration | ClassDeclaration | VariableDeclaration; type FunctionDeclaration = BaseNode<'FunctionDeclaration'> & { body: BlockStatement; id: { name: string; loc: BodyLocation }; // loc: BodyLocation; }; export type VariableDeclaration = BaseNode<'VariableDeclaration'> & { kind: 'const' | 'var' | 'let'; id: { name: string; loc: BodyLocation }; // loc: BodyLocation; declarations: VariableDeclarator[]; }; type VariableDeclarator = BaseNode<'VariableDeclarator'> & { id: | (BaseNode<string> & { name: string; loc: BodyLocation; type: 'Identifier' | '<other>' }) | (BaseNode<'ObjectPattern'> & { name: string; properties: { type: 'Property'; key: { name: string }; value: { name: string } }[]; }) | (BaseNode<'ArrayPattern'> & { name: string; elements: { name: string; type: 'Identifier' }[]; }); init?: { loc: BodyLocation }; loc: BodyLocation; }; type OtherNodes = BaseNode<'other'> & { loc: BodyLocation }; type ClassDeclaration = BaseNode<'ClassDeclaration'> & { id: { name: string; loc: BodyLocation }; }; type BodyDeclaration = | ExpressionStatement | VariableDeclaration | ClassDeclaration | FunctionDeclaration | OtherNodes | BlockStatement; type BlockStatement = { body: BodyDeclaration[]; }; type ExpressionStatement = BaseNode<'ExpressionStatement'> & { expression: | (BaseNode<'CallExpression'> & { callee: | (BaseNode<'ArrowFunctionExpression'> & { body: BlockStatement }) | (BaseNode<'CallExpression'> & { body: BlockStatement; callee: { name: string; loc: BodyLocation }; }); }) | BaseNode<'other'>; loc: BodyLocation; };
the_stack
// Deta CLI version: v1.3.0-beta // https://docs.deta.sh/docs/cli/releases#v130-beta // Fig generator for runtime options. Manually coded from // https://docs.deta.sh/docs/cli/commands#deta-new const runtimes: Fig.Generator = { script: "echo node12, node14, python3.7, python3.9", postProcess: (output) => { return output.split(",").map((runtime) => { return { name: runtime, description: "Runtime", }; }); }, }; const completionSpec: Fig.Spec = { name: "deta", description: "Deta CLI for managing Deta Micros", subcommands: [ { name: "login", description: "Trigger the login process for the Deta CLI", options: [ { name: "-h", description: "Show help for login", }, ], }, { name: "version", description: "Print the Deta version", subcommands: [ { name: "upgrade", description: "Upgrade Deta CLI version", options: [ { name: "-h", description: "Show help for upgrade", }, { name: "-v", description: "Upgrade CLI to specific version", args: { name: "Version number", }, }, ], }, ], options: [ { name: "-h", description: "Show help for version", }, ], }, { name: "projects", description: "List Deta projects", options: [ { name: "-h", description: "Show help for projects", }, ], }, { name: "new", description: "Create a new Deta Micro", args: { name: "path", description: "Path to new directory for the micro", isOptional: true, }, options: [ { name: "-h", description: "Show help for new", }, { name: "-n", description: "Create a micro with Node (node14.x) runtime", }, { name: "-p", description: "Create a micro with Python (python 3.9) runtime", }, { name: "--name", description: "Set the name of the new micro", args: { name: "name", description: "Name of the new micro", }, }, { name: "--project", description: "Set the project under which the micro is created", args: { name: "project", description: "Name of the existing project", }, }, { name: "--runtime", description: "Create a micro with a specified runtime", args: { name: "runtime", description: "The selected runtime", generators: runtimes, }, }, ], }, { name: "deploy", description: "Deploy new code to a Deta Micro", args: { name: "path", description: "Path to project directory", template: "folders", isOptional: true, }, options: [ { name: "-h", description: "Show help for deploy", }, ], }, { name: "details", description: "Get detailed information about a specific Deta micro", args: { name: "path", description: "Path to project directory", template: "folders", isOptional: true, }, options: [ { name: "-h", description: "Show help for details", }, ], }, { name: "watch", description: "Auto-deploy locally saved changes in real time to your Deta micro", args: { name: "path", description: "Path to project directory", template: "folders", isOptional: true, }, options: [ { name: "-h", description: "Show help for watch", }, ], }, { name: "auth", description: "Change auth settings for a Deta Micro", subcommands: [ { name: "disable", description: "Disable HTTP Auth for a Deta Micro", options: [ { name: "-h", description: "Show help for auth disable", }, ], }, { name: "enable", description: "Enable HTTP Auth for a Deta Micro", options: [ { name: "-h", description: "Show help for auth enable", }, ], }, { name: "create-api-key", description: "Create an API key for a Deta Micro", options: [ { name: "-h", description: "Show help for auth create-api-key", }, { name: "-d", description: "Set the api-key description", args: { name: "description", description: "The api-key description", }, }, { name: "-n", description: "Set the api-key name", isRequired: true, args: { name: "name", description: "The api-key name", }, }, { name: "-o", description: "Set the api-key output file", args: { name: "outfile", description: "The api-key output file", template: "filepaths", }, }, ], }, { name: "delete-api-key", description: "Delete an API key for a Deta Micro", options: [ { name: "-h", description: "Show help for auth delete-api-key", }, { name: "-n", description: "Set the api-key name", isRequired: true, args: { name: "name", description: "The api-key name", }, }, ], }, ], options: [ { name: "-h", description: "Show help for auth", }, ], }, { name: "pull", description: "Pull the latest deployed code of a Deta Micro to your local machine", options: [ { name: "-h", description: "Show help for pull", }, { name: "-f", description: "Force the overwrite of existing files", }, ], }, { name: "clone", description: "Clone a Deta Micro", args: { name: "path", description: "Path to new directory for the clone", isOptional: true, }, options: [ { name: "-h", description: "Show help for clone", }, { name: "-n", description: "The name of the micro to be cloned", isRequired: true, args: { name: "name", description: "Name of the micro", }, }, { name: "-p", description: "The name of the project with the micro to be cloned", args: { name: "project", description: "Name of the project", }, }, ], }, { name: "update", description: "Update a Deta Micro's name or environment variables", options: [ { name: "-h", description: "Show help for pull", }, { name: "-n", description: "The new name of the micro", args: { name: "name", description: "New name for the micro", }, }, { name: "-r", description: "The new runtime of the micro", args: { name: "runtime", description: "New runtime for the micro", generators: runtimes, }, }, { name: "-e", description: "The new env file of the micro", args: { name: "env", description: "Path to env file", template: "filepaths", }, }, ], }, { name: "visor", description: "Change the Visor settings for a Deta Micro", subcommands: [ { name: "open", description: "Open Micro's visor page in the browser", options: [ { name: "-h", description: "Show help for visor open", }, ], }, { name: "enable", description: "Enable Visor for a Deta Micro", options: [ { name: "-h", description: "Show help for visor enable", }, ], }, { name: "disable", description: "Disable Visor for a Deta Micro", options: [ { name: "-h", description: "Show help for visor disable", }, ], }, ], options: [ { name: "-h", description: "Show help for visor", }, ], }, { name: "run", description: "Run a Deta Micro from the CLI", args: { name: "action", description: "The action to be performed on the micro. See docs for full examples and details", }, options: [ { name: "-h", description: "Show help for run", }, { name: "-l", description: "Show the micro logs", }, ], }, { name: "cron", description: "Change cron settings for a Deta Micro", subcommands: [ { name: "set", description: "Set Deta Micro to run on a schedule", args: { name: "expression", description: "The cron expression to be set", }, options: [ { name: "-h", description: "Show help for cron set", }, ], }, { name: "remove", description: "Remove a schedule from a Deta Micro", args: { name: "expression", description: "The cron expression to be removed", }, options: [ { name: "-h", description: "Show help for cron remove", }, ], }, ], options: [ { name: "-h", description: "Show help for cron", }, ], }, ], options: [ { name: "-h", description: "Show help for deta", }, ], }; export default completionSpec;
the_stack
jest.dontMock('ddp') import { CoreConnection } from '../index' import { PeripheralDeviceAPI as P, PeripheralDeviceAPI } from '../lib/corePeripherals' process.on('unhandledRejection', (reason) => { console.log('Unhandled Promise rejection!', reason) }) function wait (time: number): Promise<void> { return new Promise((resolve) => { setTimeout(() => { resolve() }, time) }) } const coreHost = '127.0.0.1' const corePort = 3000 test('Integration: Test connection and basic Core functionality', async () => { // Note: This is an integration test, that require a Core to connect to let core = new CoreConnection({ deviceId: 'JestTest', deviceToken: 'abcd', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework' }) let onConnectionChanged = jest.fn() let onConnected = jest.fn() let onDisconnected = jest.fn() let onError = jest.fn() core.onConnectionChanged(onConnectionChanged) core.onConnected(onConnected) core.onDisconnected(onDisconnected) core.onError(onError) expect(core.connected).toEqual(false) // Initiate connection to Core: let id = await core.init({ host: coreHost, port: corePort }) expect(core.connected).toEqual(true) expect(id).toEqual(core.deviceId) expect(onConnectionChanged).toHaveBeenCalledTimes(1) expect(onConnectionChanged.mock.calls[0][0]).toEqual(true) expect(onConnected).toHaveBeenCalledTimes(1) expect(onDisconnected).toHaveBeenCalledTimes(0) // Set some statuses: let statusResponse = await core.setStatus({ statusCode: P.StatusCode.WARNING_MAJOR, messages: ['testing testing'] }) expect(statusResponse).toMatchObject({ statusCode: P.StatusCode.WARNING_MAJOR }) statusResponse = await core.setStatus({ statusCode: P.StatusCode.GOOD }) expect(statusResponse).toMatchObject({ statusCode: P.StatusCode.GOOD }) // Observe data: let observer = core.observe('peripheralDevices') observer.added = jest.fn() observer.changed = jest.fn() observer.removed = jest.fn() // Subscribe to data: let coll0 = core.getCollection('peripheralDevices') expect(coll0.findOne({ _id: id })).toBeFalsy() let subId = await core.subscribe('peripheralDevices', { _id: id }) let coll1 = core.getCollection('peripheralDevices') expect(coll1.findOne({ _id: id })).toMatchObject({ _id: id }) expect(observer.added).toHaveBeenCalledTimes(1) // Call a method await expect(core.callMethod('peripheralDevice.testMethod', ['return123'])).resolves.toEqual('return123') // Call a method which will throw error: await expect(core.callMethod('peripheralDevice.testMethod', ['abcd', true])).rejects.toMatchObject({ error: 418, reason: /error/ }) // Call an unknown method await expect(core.callMethod('myunknownMethod123', ['a', 'b'])).rejects.toMatchObject({ error: 404, reason: /error/ }) // Unsubscribe: core.unsubscribe(subId) await wait(200) // wait for unsubscription to go through expect(observer.removed).toHaveBeenCalledTimes(1) // Uninitialize id = await core.unInitialize() expect(id).toEqual(core.deviceId) // Set the status now (should cause an error) await expect(core.setStatus({ statusCode: P.StatusCode.GOOD })).rejects.toMatchObject({ error: 404 }) expect(onConnectionChanged).toHaveBeenCalledTimes(1) // Close connection: await core.destroy() expect(core.connected).toEqual(false) expect(onConnectionChanged).toHaveBeenCalledTimes(2) expect(onConnectionChanged.mock.calls[1][0]).toEqual(false) expect(onConnected).toHaveBeenCalledTimes(1) expect(onDisconnected).toHaveBeenCalledTimes(1) expect(onError).toHaveBeenCalledTimes(0) }) test('Integration: Connection timeout', async () => { // Note: This is an integration test, that require a Core to connect to let core = new CoreConnection({ deviceId: 'JestTest', deviceToken: 'abcd', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework' }) let onConnectionChanged = jest.fn() let onConnected = jest.fn() let onDisconnected = jest.fn() let onFailed = jest.fn() let onError = jest.fn() core.onConnectionChanged(onConnectionChanged) core.onConnected(onConnected) core.onDisconnected(onDisconnected) core.onFailed(onFailed) core.onError(onError) expect(core.connected).toEqual(false) // Initiate connection to Core: let err = null try { await core.init({ host: '127.0.0.999', port: corePort }) } catch (e) { err = e } expect(err).toMatch('Network error') expect(core.connected).toEqual(false) await core.destroy() }) test('Integration: Connection recover from close', async () => { // Note: This is an integration test, that require a Core to connect to let core = new CoreConnection({ deviceId: 'JestTest', deviceToken: 'abcd', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework' }) let onConnectionChanged = jest.fn() let onConnected = jest.fn() let onDisconnected = jest.fn() let onFailed = jest.fn() let onError = jest.fn() core.onConnectionChanged(onConnectionChanged) core.onConnected(onConnected) core.onDisconnected(onDisconnected) core.onFailed(onFailed) core.onError(onError) expect(core.connected).toEqual(false) // Initiate connection to Core: await core.init({ host: coreHost, port: corePort }) expect(core.connected).toEqual(true) // Force-close the socket: core.ddp.ddpClient!.socket.close() await wait(10) expect(core.connected).toEqual(false) await wait(1300) // should have reconnected by now expect(core.connected).toEqual(true) await core.destroy() }) test('Integration: autoSubscription', async () => { // Note: This is an integration test, that require a Core to connect to let core = new CoreConnection({ deviceId: 'JestTest', deviceToken: 'abcd', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework' }) let onConnectionChanged = jest.fn() let onConnected = jest.fn() let onDisconnected = jest.fn() let onFailed = jest.fn() let onError = jest.fn() core.onConnectionChanged(onConnectionChanged) core.onConnected(onConnected) core.onDisconnected(onDisconnected) core.onFailed(onFailed) core.onError(onError) expect(core.connected).toEqual(false) // Initiate connection to Core: await core.init({ host: coreHost, port: corePort }) expect(core.connected).toEqual(true) let observerAdded = jest.fn() let observerChanged = jest.fn() let observerRemoved = jest.fn() let observer = core.observe('peripheralDevices') observer.added = observerAdded observer.changed = observerChanged observer.removed = observerRemoved await core.autoSubscribe('peripheralDevices', { _id: 'JestTest' }) expect(observerAdded).toHaveBeenCalledTimes(1) await core.setStatus({ statusCode: PeripheralDeviceAPI.StatusCode.GOOD, messages: ['Jest A ' + Date.now()] }) await wait(300) expect(observerChanged).toHaveBeenCalledTimes(1) // Force-close the socket: core.ddp.ddpClient!.socket.close() await wait(10) expect(core.connected).toEqual(false) await wait(1300) // should have reconnected by now expect(core.connected).toEqual(true) observerChanged.mockClear() await core.setStatus({ statusCode: PeripheralDeviceAPI.StatusCode.GOOD, messages: ['Jest B' + Date.now()] }) await wait(300) expect(observerChanged).toHaveBeenCalledTimes(1) await core.destroy() }) test('Integration: Connection recover from a close that lasts some time', async () => { // Note: This is an integration test, that require a Core to connect to let core = new CoreConnection({ deviceId: 'JestTest', deviceToken: 'abcd', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework' }) let onConnectionChanged = jest.fn() let onConnected = jest.fn() let onDisconnected = jest.fn() let onFailed = jest.fn() let onError = jest.fn() core.onConnectionChanged(onConnectionChanged) core.onConnected(onConnected) core.onDisconnected(onDisconnected) core.onFailed(onFailed) core.onError(onError) expect(core.connected).toEqual(false) // Initiate connection to Core: await core.init({ host: coreHost, port: corePort, autoReconnect: true, autoReconnectTimer: 100 }) expect(core.connected).toEqual(true) // temporary scramble the ddp host: ;(core.ddp.ddpClient as any).host = '127.0.0.9' // Force-close the socket: core.ddp.ddpClient!.socket.close() await wait(10) expect(core.connected).toEqual(false) await wait(1000) // allow for some reconnections // restore ddp host: ;(core.ddp.ddpClient as any).host = '127.0.0.1' await wait(1000) // should have reconnected by now expect(core.connected).toEqual(true) await core.destroy() }) test('Integration: Parent connections', async () => { // Note: This is an integration test, that require a Core to connect to let coreParent = new CoreConnection({ deviceId: 'JestTest', deviceToken: 'abcd', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework' }) let onError = jest.fn() coreParent.onError(onError) let parentOnConnectionChanged = jest.fn() coreParent.onConnectionChanged(parentOnConnectionChanged) let id = await coreParent.init({ host: coreHost, port: corePort }) expect(coreParent.connected).toEqual(true) // Set child connection: let coreChild = new CoreConnection({ deviceId: 'JestTestChild', deviceToken: 'abcd2', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework child' }) let onChildConnectionChanged = jest.fn() let onChildConnected = jest.fn() let onChildDisconnected = jest.fn() let onChildError = jest.fn() coreChild.onConnectionChanged(onChildConnectionChanged) coreChild.onConnected(onChildConnected) coreChild.onDisconnected(onChildDisconnected) coreChild.onError(onChildError) let idChild = await coreChild.init(coreParent) expect(idChild).toEqual(coreChild.deviceId) expect(coreChild.connected).toEqual(true) expect(onChildConnectionChanged).toHaveBeenCalledTimes(1) expect(onChildConnectionChanged.mock.calls[0][0]).toEqual(true) expect(onChildConnected).toHaveBeenCalledTimes(1) expect(onChildDisconnected).toHaveBeenCalledTimes(0) // Set some statuses: let statusResponse = await coreChild.setStatus({ statusCode: P.StatusCode.WARNING_MAJOR, messages: ['testing testing'] }) expect(statusResponse).toMatchObject({ statusCode: P.StatusCode.WARNING_MAJOR }) statusResponse = await coreChild.setStatus({ statusCode: P.StatusCode.GOOD }) expect(statusResponse).toMatchObject({ statusCode: P.StatusCode.GOOD }) // Uninitialize: id = await coreChild.unInitialize() expect(id).toEqual(coreChild.deviceId) // Set the status now (should cause an error) await expect(coreChild.setStatus({ statusCode: P.StatusCode.GOOD })).rejects.toMatchObject({ error: 404 }) await coreParent.destroy() await coreChild.destroy() expect(onError).toHaveBeenCalledTimes(0) expect(onChildError).toHaveBeenCalledTimes(0) }) test('Integration: Parent destroy', async () => { // Note: This is an integration test, that require a Core to connect to let coreParent = new CoreConnection({ deviceId: 'JestTest', deviceToken: 'abcd', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework' }) let onParentError = jest.fn() coreParent.onError(onParentError) await coreParent.init({ host: coreHost, port: corePort }) // Set child connection: let coreChild = new CoreConnection({ deviceId: 'JestTestChild', deviceToken: 'abcd2', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework child' }) let onChildConnectionChanged = jest.fn() let onChildConnected = jest.fn() let onChildDisconnected = jest.fn() let onChildError = jest.fn() coreChild.onConnectionChanged(onChildConnectionChanged) coreChild.onConnected(onChildConnected) coreChild.onDisconnected(onChildDisconnected) coreChild.onError(onChildError) await coreChild.init(coreParent) expect(coreChild.connected).toEqual(true) // Close parent connection: await coreParent.destroy() expect(coreChild.connected).toEqual(false) expect(onChildConnectionChanged).toHaveBeenCalledTimes(2) expect(onChildConnectionChanged.mock.calls[1][0]).toEqual(false) expect(onChildConnected).toHaveBeenCalledTimes(1) expect(onChildDisconnected).toHaveBeenCalledTimes(1) // Setup stuff again onChildConnectionChanged.mockClear() onChildConnected.mockClear() onChildDisconnected.mockClear() coreChild.onConnectionChanged(onChildConnectionChanged) coreChild.onConnected(onChildConnected) coreChild.onDisconnected(onChildDisconnected) // connect parent again: await coreParent.init({ host: coreHost, port: corePort }) await coreChild.init(coreParent) expect(coreChild.connected).toEqual(true) expect(onChildConnected).toHaveBeenCalledTimes(1) expect(onChildConnectionChanged).toHaveBeenCalledTimes(1) expect(onChildConnectionChanged.mock.calls[0][0]).toEqual(true) expect(onChildDisconnected).toHaveBeenCalledTimes(0) await coreParent.destroy() await coreChild.destroy() expect(onChildError).toHaveBeenCalledTimes(0) expect(onParentError).toHaveBeenCalledTimes(0) }) test('Integration: Child destroy', async () => { // Note: This is an integration test, that require a Core to connect to let coreParent = new CoreConnection({ deviceId: 'JestTest', deviceToken: 'abcd', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework' }) let onParentError = jest.fn() coreParent.onError(onParentError) await coreParent.init({ host: coreHost, port: corePort }) // Set child connection: let coreChild = new CoreConnection({ deviceId: 'JestTestChild', deviceToken: 'abcd2', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework child' }) let onChildConnectionChanged = jest.fn() let onChildConnected = jest.fn() let onChildDisconnected = jest.fn() let onChildError = jest.fn() coreChild.onConnectionChanged(onChildConnectionChanged) coreChild.onConnected(onChildConnected) coreChild.onDisconnected(onChildDisconnected) coreChild.onError(onChildError) await coreChild.init(coreParent) expect(coreChild.connected).toEqual(true) // Close parent connection: await coreChild.destroy() expect(coreChild.connected).toEqual(false) expect(onChildConnectionChanged).toHaveBeenCalledTimes(2) expect(onChildConnectionChanged.mock.calls[1][0]).toEqual(false) expect(onChildConnected).toHaveBeenCalledTimes(1) expect(onChildDisconnected).toHaveBeenCalledTimes(1) await coreParent.destroy() expect(onParentError).toHaveBeenCalledTimes(0) expect(onChildError).toHaveBeenCalledTimes(0) }) test('Integration: Test callMethodLowPrio', async () => { // Note: This is an integration test, that require a Core to connect to let core = new CoreConnection({ deviceId: 'JestTest', deviceToken: 'abcd', deviceType: P.DeviceType.PLAYOUT, deviceCategory: P.DeviceCategory.PLAYOUT, deviceName: 'Jest test framework' }) let onError = jest.fn() core.onError(onError) await core.init({ host: coreHost, port: corePort }) expect(core.connected).toEqual(true) // Call a method await expect(core.callMethod('peripheralDevice.testMethod', ['return123'])).resolves.toEqual('return123') // Call a low-prio method await expect(core.callMethodLowPrio('peripheralDevice.testMethod', ['low123'])).resolves.toEqual('low123') let ps: Promise<any>[] = [] // method should be called before low-prio: let i = 0 ps.push(core.callMethodLowPrio('peripheralDevice.testMethod', ['return123']) .then(() => { return i++ })) ps.push(core.callMethod('peripheralDevice.testMethod', ['low123']) .then(() => { return i++ })) let r = await Promise.all(ps) expect(r[0]).toBeGreaterThan(r[1]) // because callMethod should have run before callMethodLowPrio // Clean up await core.destroy() expect(onError).toHaveBeenCalledTimes(0) })
the_stack
import { Component, NotifyPropertyChanges, INotifyPropertyChanged, ChildProperty, Property, Collection, append, extend, Event, EmitType, BaseEventArgs, EventHandler, closest, addClass, removeClass, detach, remove } from '@syncfusion/ej2-base'; import { ListBase, ListBaseOptions } from '@syncfusion/ej2-lists'; import { Popup } from '@syncfusion/ej2-popups'; import { BreadcrumbModel, BreadcrumbItemModel } from './breadcrumb-model'; type obj = { [key: string]: Object }; const ICONRIGHT: string = 'e-icon-right'; const ITEMTEXTCLASS: string = 'e-breadcrumb-text'; const ICONCLASS: string = 'e-breadcrumb-icon'; const MENUCLASS: string = 'e-breadcrumb-menu'; const ITEMCLASS: string = 'e-breadcrumb-item'; const POPUPCLASS: string = 'e-breadcrumb-popup'; const WRAPMODECLASS: string = 'e-breadcrumb-wrap-mode'; const SCROLLMODECLASS: string = 'e-breadcrumb-scroll-mode'; const TABINDEX: string = 'tabindex'; const DISABLEDCLASS: string = 'e-disabled'; const ARIADISABLED: string = 'aria-disabled' const DOT: string = '.'; /** * Defines the Breadcrumb overflow modes. */ export type BreadcrumbOverflowMode = 'Hidden' | 'Collapsed' | 'Menu' | 'Wrap' | 'Scroll' | 'None'; export class BreadcrumbItem extends ChildProperty<BreadcrumbItem> { /** * Specifies the text content of the Breadcrumb item. * * @default '' */ @Property('') public text: string; /** * Specifies the Url of the Breadcrumb item that will be activated when clicked. * * @default '' */ @Property('') public url: string; /** * Defines a class/multiple classes separated by a space for the item that is used to include an icon. * * @default null */ @Property(null) public iconCss: string; /** * Enable or disable the breadcrumb item, when set to true, the breadcrumb item will be disabled. * * @default false */ @Property(false) public disabled: boolean; } /** * Interface for item click event. */ export interface BreadcrumbClickEventArgs extends BaseEventArgs { /** * Specifies the item's element. */ element: HTMLElement; /** * Specifies the Breadcrumb item. */ item: BreadcrumbItemModel; /** * Specifies the item click event. */ event: Event; } /** * Interface for before item render event. */ export interface BreadcrumbBeforeItemRenderEventArgs extends BaseEventArgs { /** * Specifies the item's element. */ element: HTMLElement; /** * Specifies the Breadcrumb item. */ item: BreadcrumbItemModel; /** * Cancels the Breadcrumb item rendering. */ cancel: boolean; } /** * Breadcrumb is a graphical user interface that helps to identify or highlight the current location within a hierarchical structure of websites. * The aim is to make the user aware of their current position in a hierarchy of website links. * ```html * <nav id='breadcrumb'></nav> * ``` * ```typescript * <script> * var breadcrumbObj = new Breadcrumb({ items: [{ text: 'Home', url: '/' }, { text: 'Index', url: './index.html }]}); * breadcrumbObj.appendTo("#breadcrumb"); * </script> * ``` */ @NotifyPropertyChanges export class Breadcrumb extends Component<HTMLElement> implements INotifyPropertyChanged { private isExpanded: boolean; private startIndex: number; private endIndex: number; private _maxItems: number; private popupObj: Popup; private popupUl: HTMLElement; private delegateClickHanlder: Function; /** * Defines the Url based on which the Breadcrumb items are generated. * * @default '' */ @Property('') public url: string; /** * Defines the list of Breadcrumb items. * * @default [] */ @Collection<BreadcrumbItemModel>([], BreadcrumbItem) public items: BreadcrumbItemModel[]; /** * Specifies the Url of the active Breadcrumb item. * * @default '' */ @Property('') public activeItem: string; /** * Specifies an integer to enable overflow behavior when the Breadcrumb items count exceeds and it is based on the overflowMode property. * * @default -1 * @aspType int */ @Property(-1) public maxItems: number; /** * Specifies the overflow mode of the Breadcrumb item when it exceeds maxItems count. The possible values are, * - Default: Specified maxItems count will be visible and the remaining items will be hidden. While clicking on the previous item, the hidden item will become visible. * - Collapsed: Only the first and last items will be visible, and the remaining items will be hidden in the collapsed icon. When the collapsed icon is clicked, all items become visible. * - Menu: Shows the number of breadcrumb items that can be accommodated within the container space, and creates a sub menu with the remaining items. * - Wrap: Wraps the items on multiple lines when the Breadcrumb’s width exceeds the container space. * - Scroll: Shows an HTML scroll bar when the Breadcrumb’s width exceeds the container space. * - None: Shows all the items on a single line. * * @default 'Menu' */ @Property('Menu') public overflowMode: BreadcrumbOverflowMode; /** * Defines class/multiple classes separated by a space in the Breadcrumb element. * * @default '' */ @Property('') public cssClass: string; /** * Specifies the template for Breadcrumb item. * * @default null */ @Property(null) public itemTemplate: string; /** * Specifies the separator template for Breadcrumb. * * @default '/' */ @Property('/') public separatorTemplate: string; /** * Enable or disable the item's navigation, when set to false, each item navigation will be prevented. * * @default true */ @Property(true) public enableNavigation: boolean; /** * Enable or disable the active item navigation, when set to true, active item will be navigable. * * @default false */ @Property(false) public enableActiveItemNavigation: boolean; /** * Enable or disable the breadcrumb, when set to true, the breadcrumb will be disabled. * * @default false */ @Property(false) public disabled: boolean; /** * Overrides the global culture and localization value for this component. Default global culture is 'en-US'. * * @default '' * @private * @aspIgnore */ @Property('') public locale: string; /** * Triggers while rendering each breadcrumb item. * * @event beforeItemRender */ @Event() public beforeItemRender: EmitType<BreadcrumbBeforeItemRenderEventArgs>; /** * Triggers while clicking the breadcrumb item. * * @event itemClick */ @Event() public itemClick: EmitType<BreadcrumbClickEventArgs>; /** * Triggers once the component rendering is completed. * * @event created */ @Event() public created: EmitType<Event>; /** * Constructor for creating the widget. * * @private * @param {BreadcrumbModel} options - Specifies the Breadcrumb model. * @param {string | HTMLElement} element - Specifies the element. */ public constructor(options?: BreadcrumbModel, element?: string | HTMLElement) { super(options, <string | HTMLElement>element); } /** * @private * @returns {void} */ protected preRender(): void { // pre render code } /** * Initialize the control rendering. * * @private * @returns {void} */ protected render(): void { this.initialize(); this.renderItems(this.items); this.wireEvents(); } private initialize(): void { this._maxItems = this.maxItems; this.element.setAttribute('aria-label', 'breadcrumb'); if (this.cssClass) { addClass([this.element], this.cssClass.split(' ')); } if (this.enableRtl) { this.element.classList.add('e-rtl'); } if (this.disabled) { this.element.classList.add(DISABLEDCLASS); this.element.setAttribute(ARIADISABLED, 'true'); } if (this.overflowMode === 'Wrap') { this.element.classList.add(WRAPMODECLASS); } else if (this.overflowMode === 'Scroll') { this.element.classList.add(SCROLLMODECLASS); } this.initItems(); this.initPvtProps(); } private initPvtProps(): void { if (this.overflowMode === 'Hidden' && this._maxItems > 0) { this.endIndex = this.getEndIndex(); this.startIndex = this.endIndex + 1 - (this._maxItems - 1); } if (this.overflowMode === 'Menu') { if (this._maxItems >= 0) { this.startIndex = this._maxItems > 1 ? 1 : 0; this.endIndex = this.getEndIndex(); this.popupUl = this.createElement('ul', { attrs: { TABINDEX: '0', 'role': 'menu' } }); } else { this.startIndex = this.endIndex = null; } } } private getEndIndex(): number { let endIndex: number; if (this.activeItem) { this.items.forEach((item: BreadcrumbItemModel, idx: number) => { if (item.url === this.activeItem || item.text === this.activeItem) { endIndex = idx; } }); } else { endIndex = this.items.length - 1; } return endIndex; } private initItems(): void { if (!this.items.length) { let baseUri: string; let uri: string[]; const items: BreadcrumbItemModel[] = []; if (this.url) { const url: URL = new URL(this.url, window.location.origin); baseUri = url.origin + '/'; uri = url.href.split(baseUri)[1].split('/'); } else { baseUri = window.location.origin + '/'; uri = window.location.href.split(baseUri)[1].split('/'); } items.push({ iconCss: 'e-icons e-home', url: baseUri }); for (let i: number = 0; i < uri.length; i++) { if (uri[i]) { items.push({ text: uri[i], url: baseUri + uri[i] }); baseUri += uri[i] + '/'; } } this.setProperties({ items: items }, true); } } private renderItems(items: BreadcrumbItemModel[]): void { let item: BreadcrumbItemModel[] | object[]; let isSingleLevel: boolean; const isIconRight: boolean = this.element.classList.contains(ICONRIGHT); const itemsLength: number = items.length; if (itemsLength) { let isActiveItem: boolean; let isLastItem: boolean; let isLastItemInPopup: boolean; let j: number = 0; let wrapDiv: HTMLElement; const len: number = (itemsLength * 2) - 1; let isItemCancelled: boolean = false; const ol: HTMLElement = this.createElement('ol', { className: this.overflowMode === 'Wrap' ? 'e-breadcrumb-wrapped-ol' : '' }); const firstOl: HTMLElement = this.createElement('ol', { className: this.overflowMode === 'Wrap' ? 'e-breadcrumb-first-ol' : '' }); const showIcon: boolean = this.hasField(items, 'iconCss'); const isCollasped: boolean = (this.overflowMode === 'Collapsed' && this._maxItems > 0 && itemsLength > this._maxItems && !this.isExpanded); const isDefaultOverflowMode: boolean = (this.overflowMode === 'Hidden' && this._maxItems > 0); if (this.overflowMode === 'Menu' && this.popupUl) { this.popupUl.innerHTML = ''; } const listBaseOptions: ListBaseOptions = { moduleName: this.getModuleName(), showIcon: showIcon, itemNavigable: true, itemCreated: (args: { curData: BreadcrumbItemModel, item: HTMLElement, fields: obj }): void => { const isLastItem: boolean = (args.curData as { isLastItem: boolean }).isLastItem; if (isLastItem && args.item.children.length && !this.itemTemplate) { delete (args.curData as { isLastItem: boolean }).isLastItem; if (!isLastItemInPopup && !this.enableActiveItemNavigation) { args.item.innerHTML = this.createElement('span', { className: ITEMTEXTCLASS, innerHTML: args.item.children[0].innerHTML }).outerHTML; } } if (args.curData.iconCss && !args.curData.text && !this.itemTemplate) { args.item.classList.add('e-icon-item'); } if (isDefaultOverflowMode) { args.item.setAttribute('item-index', j.toString()); } const eventArgs: BreadcrumbBeforeItemRenderEventArgs = { item: extend({}, (args.curData as { properties: object }).properties ? (args.curData as { properties: object }).properties : args.curData), element: args.item, cancel: false }; this.trigger('beforeItemRender', eventArgs); isItemCancelled = eventArgs.cancel; const containsRightIcon: boolean = (isIconRight || eventArgs.element.classList.contains(ICONRIGHT)); if (containsRightIcon && args.curData.iconCss && !this.itemTemplate) { args.item.querySelector('.e-anchor-wrap').appendChild(args.item.querySelector(DOT + ICONCLASS)); } if (eventArgs.item.disabled) { args.item.setAttribute(ARIADISABLED, 'true'); args.item.classList.add(DISABLEDCLASS); } if ((eventArgs.item.disabled || this.disabled) && args.item.children.length && !this.itemTemplate) { args.item.children[0].setAttribute(TABINDEX, '-1'); } if ((args.curData as { isEmptyUrl: boolean }).isEmptyUrl) { args.item.children[0].removeAttribute('href'); if ((!isLastItem || (isLastItem && this.enableActiveItemNavigation)) && !(eventArgs.item.disabled || this.disabled)) { args.item.children[0].setAttribute(TABINDEX, '0'); EventHandler.add(args.item.children[0], 'keydown', this.keyDownHandler, this); } } if (isLastItem) { args.item.setAttribute('data-active-item', ''); } if (!this.itemTemplate) { this.beforeItemRenderChanges(args.curData, eventArgs.item, args.item, containsRightIcon); } } }; for (let i: number = 0; i < len; (i % 2 && j++), i++) { isActiveItem = (this.activeItem && (this.activeItem === items[j].url || this.activeItem === items[j].text)); if (isCollasped && i > 1 && i < len - 2) { continue; } else if (isDefaultOverflowMode && ((j < this.startIndex || j > this.endIndex) && (i % 2 ? j !== this.startIndex - 1 : true)) && j !== 0) { continue; } if (i % 2) { // separator item wrapDiv = this.createElement('div', { className: 'e-breadcrumb-item-wrapper' }); listBaseOptions.template = this.separatorTemplate ? this.separatorTemplate : '/'; listBaseOptions.itemClass = 'e-breadcrumb-separator'; isSingleLevel = false; item = [{ previousItem: items[j], nextItem: items[j + 1] }]; } else { // list item listBaseOptions.itemClass = ''; if (this.itemTemplate) { listBaseOptions.template = this.itemTemplate; isSingleLevel = false; } else { isSingleLevel = true; } item = [extend({}, (items[j] as { properties: object }).properties ? (items[j] as { properties: object }).properties : items[j])]; if (!(item as BreadcrumbItemModel[])[0].url && !this.itemTemplate) { item = [extend({}, (item as BreadcrumbItemModel[])[0], { isEmptyUrl: true, url: '#' })]; } isLastItem = (isDefaultOverflowMode || this.overflowMode === 'Menu') && (j === this.endIndex); if (((i === len - 1 || isLastItem) && !this.itemTemplate) || isActiveItem) { (item[0] as { isLastItem: boolean }).isLastItem = true; } } let parent: HTMLElement = ol; const lastPopupItemIdx: number = this.startIndex + this.endIndex - this._maxItems; if (this.overflowMode === 'Menu' && ((j >= this.startIndex && (j <= lastPopupItemIdx && (i % 2 ? !(j === lastPopupItemIdx) : true)) && this.endIndex >= this._maxItems && this._maxItems > 0) || this._maxItems === 0)) { if (i % 2) { continue; } else { parent = this.popupUl; if (isLastItem) { isLastItemInPopup = true; } } } else if (this.overflowMode === 'Wrap') { if (i === 0) { parent = firstOl } else { parent = wrapDiv; } } const li: NodeList = ListBase.createList(this.createElement, item as { [key: string]: Object; }[], listBaseOptions, isSingleLevel, this).childNodes; if (!isItemCancelled) { append(li, parent); } else if (isDefaultOverflowMode || isCollasped || this.overflowMode === 'Menu' || this.overflowMode === 'Wrap') { items.splice(j, 1); this.initPvtProps(); return this.reRenderItems(); } else if ((i === len - 1 || isLastItem)) { remove(parent.lastElementChild); } if (this.overflowMode === 'Wrap' && i !== 0 && i % 2 === 0) { ol.appendChild(wrapDiv); } if (isCollasped && i === 1) { const li: Element = this.createElement('li', { className: 'e-icons e-breadcrumb-collapsed', attrs: { TABINDEX: '0' } }); EventHandler.add(li, 'keyup', this.expandHandler, this); ol.appendChild(li); } if (this.overflowMode === 'Menu' && this.startIndex === i && this.endIndex >= this._maxItems && this._maxItems >= 0) { const menu: Element = this.getMenuElement(); EventHandler.add(menu, 'keyup', this.keyDownHandler, this); ol.appendChild(menu); } if (isActiveItem || isLastItem) { break; } if (isItemCancelled) { i++; } } if ((this as unknown as { isReact: boolean }).isReact) { this.renderReactTemplates(); } if (this.overflowMode === 'Wrap') { this.element.appendChild(firstOl); } this.element.appendChild(ol); this.calculateMaxItems(); } } private calculateMaxItems(): void { if (this.overflowMode === 'Hidden' || this.overflowMode === 'Collapsed' || this.overflowMode === 'Menu') { let maxItems: number; const width: number = this.element.offsetWidth; const liElems: HTMLElement[] = [].slice.call(this.element.children[0].children).reverse(); let liWidth: number = this.overflowMode === 'Menu' ? 0 : liElems[liElems.length - 1].offsetWidth + (liElems[liElems.length - 2] ? liElems[liElems.length - 2].offsetWidth : 0); if (this.overflowMode === 'Menu') { const menuEle: HTMLElement = this.getMenuElement(); this.element.appendChild(menuEle); liWidth += menuEle.offsetWidth; remove(menuEle); } for (let i: number = 0; i < liElems.length - 2; i++) { if (liWidth > width) { maxItems = Math.ceil((i - 1) / 2) + ((this.overflowMode === 'Menu' && i <= 2) ? 0 : 1); if (((this.maxItems > maxItems && !(this.maxItems > -1 && maxItems == -1)) || this.maxItems == -1) && this._maxItems != maxItems) { this._maxItems = maxItems; this.initPvtProps(); return this.reRenderItems(); } else { break; } } else { if (this.overflowMode === 'Menu' && i === 2) { liWidth += liElems[liElems.length - 1].offsetWidth + liElems[liElems.length - 2].offsetWidth; if (liWidth > width) { this._maxItems = 1; this.initPvtProps(); return this.reRenderItems(); } } if (!(this.overflowMode === 'Menu' && liElems[i].classList.contains(MENUCLASS))) { liWidth += liElems[i].offsetWidth; if (liWidth > width) { maxItems = Math.ceil((i) / 2) + (this.overflowMode === 'Menu' && i <= 2 ? 0 : 1); this._maxItems = maxItems; this.initPvtProps(); return this.reRenderItems(); } } } } } else if ((this.overflowMode === 'Wrap' || this.overflowMode === 'Scroll') && this._maxItems > 0) { let width: number = 0; const liElems: NodeListOf<HTMLElement> = this.element.querySelectorAll(DOT + ITEMCLASS); if (liElems.length > this._maxItems + this._maxItems - 1) { for (let i: number = this.overflowMode === 'Wrap' ? 1 : 0; i < this._maxItems + this._maxItems - 1; i++) { width += liElems[i].offsetWidth; } width = width + 5 + (parseInt(getComputedStyle(this.element.children[0]).paddingLeft, 10) * 2); if (this.overflowMode === 'Wrap') { (this.element.querySelector('.e-breadcrumb-wrapped-ol') as HTMLElement).style.width = width + 'px'; } else { this.element.style.width = width + 'px'; } } } } private hasField(items: BreadcrumbItemModel[], field: string): boolean { for (let i: number = 0, len: number = items.length; i < len; i++) { if ((<obj>items[i])[field]) { return true; } } return false; } private getMenuElement(): HTMLElement { return this.createElement('li', { className: 'e-icons e-breadcrumb-menu', attrs: { TABINDEX: '0' } }) } private beforeItemRenderChanges(prevItem: BreadcrumbItemModel, currItem: BreadcrumbItemModel, elem: Element, isRightIcon: boolean) : void { const wrapElem: Element = elem.querySelector('.e-anchor-wrap'); if (currItem.text !== prevItem.text) { wrapElem.childNodes.forEach((child: Element) => { if (child.nodeType === Node.TEXT_NODE) { child.textContent = currItem.text; } }); } if (currItem.iconCss !== prevItem.iconCss && wrapElem) { // wrapElem - for checking it is item not a separator const iconElem: Element = elem.querySelector(DOT + ICONCLASS); if (iconElem) { if (currItem.iconCss) { removeClass([iconElem], prevItem.iconCss.split(' ')); addClass([iconElem], currItem.iconCss.split(' ')); } else { remove(iconElem); } } else if (currItem.iconCss) { const iconElem: Element = this.createElement('span', { className: ICONCLASS + ' ' + currItem.iconCss }); if (isRightIcon) { append([iconElem], wrapElem); } else { wrapElem.insertBefore(iconElem, wrapElem.childNodes[0]); } } } if (currItem.url !== prevItem.url && this.enableNavigation) { const anchor: Element = elem.querySelector('a.' + ITEMTEXTCLASS); if (anchor) { if (currItem.url) { anchor.setAttribute('href', currItem.url); } else { anchor.removeAttribute('href'); } } } } private reRenderItems(): void { this.element.innerHTML = ''; this.renderItems(this.items); } private clickHandler(e: MouseEvent): void { const li: Element = closest(e.target as Element, DOT + ITEMCLASS + ':not(.e-breadcrumb-separator)'); if (!this.enableNavigation) { e.preventDefault(); } if (li && (closest(e.target as Element, DOT + ITEMTEXTCLASS) || this.itemTemplate)) { let idx: number; if (this.overflowMode === 'Wrap') { idx = [].slice.call(this.element.querySelectorAll(DOT + ITEMCLASS)).indexOf(li); } else { idx = [].slice.call(li.parentElement.children).indexOf(li); } if (this.overflowMode === 'Menu') { if (closest(e.target as Element, DOT + POPUPCLASS)) { idx += this.startIndex; this.endIndex = idx; if (e.type === 'keydown') { this.documentClickHandler(e); } } else if (this.element.querySelector(DOT + MENUCLASS)) { if (idx > [].slice.call(this.element.children[0].children).indexOf(this.element.querySelector(DOT + MENUCLASS))) { idx += (this.popupUl.childElementCount * 2) - 2; idx = Math.floor(idx / 2); this.endIndex = idx; } else { this.startIndex = this.endIndex = idx; } } else { idx = Math.floor(idx / 2); this.startIndex = this.endIndex = idx; } } else { idx = Math.floor(idx / 2); } if (this.overflowMode === 'Hidden' && this._maxItems > 0 && this.endIndex !== 0) { idx = parseInt(li.getAttribute('item-index'), 10); if (this.startIndex > 1) { this.startIndex -= (this.endIndex - idx); } this.endIndex = idx; } this.trigger('itemClick', { element: li, item: this.items[idx], event: e }); this.activeItem = this.items[idx].url || this.items[idx].text; this.dataBind(); } if ((e.target as Element).classList.contains('e-breadcrumb-collapsed')) { this.isExpanded = true; this.reRenderItems(); } if ((e.target as Element).classList.contains(MENUCLASS)) { this.renderPopup(); } } private renderPopup(): void { const wrapper: HTMLElement = this.createElement('div', { className: POPUPCLASS + ' ' + this.cssClass + (this.enableRtl ? ' e-rtl' : '') }); document.body.appendChild(wrapper); this.popupObj = new Popup(wrapper, { content: this.popupUl, relateTo: this.element.querySelector(DOT + MENUCLASS) as HTMLElement, enableRtl: this.enableRtl, position: { X: 'left', Y: 'bottom' }, collision: { X: 'fit', Y: 'flip' }, open: (): void => { this.popupUl.focus(); } }); this.popupWireEvents(); this.popupObj.show(); } private documentClickHandler(e: Event): void { if (this.overflowMode === 'Menu' && this.popupObj && this.popupObj.element.classList.contains('e-popup-open') && !closest(e.target as Element, DOT + MENUCLASS)) { this.popupObj.hide(); this.popupObj.destroy(); detach(this.popupObj.element); } } private resize(): void { this._maxItems = this.maxItems; this.initPvtProps(); this.reRenderItems(); } private expandHandler(e: KeyboardEvent): void { if (e.key === 'Enter') { this.isExpanded = true; this.reRenderItems(); } } private keyDownHandler(e: KeyboardEvent): void { if (e.key === 'Enter') { this.clickHandler(e as unknown as MouseEvent); } } private popupKeyDownHandler(e: KeyboardEvent): void { if (e.key === 'Escape') { this.documentClickHandler(e); } } /** * Called internally if any of the property value changed. * * @private * @param {BreadcrumbModel} newProp - Specifies the new properties. * @param {BreadcrumbModel} oldProp - Specifies the old properties. * @returns {void} */ public onPropertyChanged(newProp: BreadcrumbModel, oldProp: BreadcrumbModel): void { for (const prop of Object.keys(newProp)) { switch (prop) { case 'items': case 'enableActiveItemNavigation': this.reRenderItems(); break; case 'activeItem': this._maxItems = this.maxItems; this.initPvtProps(); this.reRenderItems(); break; case 'overflowMode': case 'maxItems': this._maxItems = this.maxItems; this.initPvtProps(); this.reRenderItems(); if (oldProp.overflowMode === 'Wrap') { this.element.classList.remove(WRAPMODECLASS); } else if (newProp.overflowMode === 'Wrap') { this.element.classList.add(WRAPMODECLASS); } if (oldProp.overflowMode === 'Scroll') { this.element.classList.remove(SCROLLMODECLASS); } else if (newProp.overflowMode === 'Scroll') { this.element.classList.add(SCROLLMODECLASS); } break; case 'url': this.initItems(); this.reRenderItems(); break; case 'cssClass': if (oldProp.cssClass) { removeClass([this.element], oldProp.cssClass.split(' ')); } if (newProp.cssClass) { addClass([this.element], newProp.cssClass.split(' ')); } if ((oldProp.cssClass && oldProp.cssClass.indexOf(ICONRIGHT) > -1) && !(newProp.cssClass && newProp.cssClass.indexOf(ICONRIGHT) > -1) || !(oldProp.cssClass && oldProp.cssClass.indexOf(ICONRIGHT) > -1) && (newProp.cssClass && newProp.cssClass.indexOf(ICONRIGHT) > -1)) { this.reRenderItems(); } break; case 'enableRtl': this.element.classList.toggle('e-rtl'); break; case 'disabled': this.element.classList.toggle(DISABLEDCLASS); this.element.setAttribute(ARIADISABLED, newProp.disabled + ''); break; } } } private wireEvents(): void { this.delegateClickHanlder = this.documentClickHandler.bind(this); EventHandler.add(document, 'click', this.delegateClickHanlder, this); EventHandler.add(this.element, 'click', this.clickHandler, this); window.addEventListener('resize', this.resize.bind(this)); } private popupWireEvents(): void { EventHandler.add(this.popupObj.element, 'click', this.clickHandler, this); EventHandler.add(this.popupObj.element, 'keydown', this.popupKeyDownHandler, this); } private unWireEvents(): void { EventHandler.remove(document, 'click', this.delegateClickHanlder); EventHandler.remove(this.element, 'click', this.clickHandler); window.removeEventListener('resize', this.resize.bind(this)); if (this.popupObj) { EventHandler.remove(this.popupObj.element, 'click', this.clickHandler); EventHandler.remove(this.popupObj.element, 'keydown', this.popupKeyDownHandler); } } /** * Get the properties to be maintained in the persisted state. * * @returns {string} - Persist data */ protected getPersistData(): string { return this.addOnPersist(['activeItem']); } /** * Get module name. * * @private * @returns {string} - Module Name */ protected getModuleName(): string { return 'breadcrumb'; } /** * Destroys the widget. * * @returns {void} */ public destroy(): void { let classes: string[] = []; let attributes: string[] = ['aria-label']; if (this.cssClass) { classes.concat(this.cssClass.split(' ')); } if (this.enableRtl) { classes.push('e-rtl'); } if (this.disabled) { classes.push(DISABLEDCLASS); attributes.push(ARIADISABLED); } if (this.overflowMode === 'Wrap') { classes.push(WRAPMODECLASS); } else if (this.overflowMode === 'Scroll') { classes.push(SCROLLMODECLASS); } this.unWireEvents(); this.element.innerHTML = ''; removeClass([this.element], classes); attributes.forEach((attribute: string) => { this.element.removeAttribute(attribute); }); super.destroy(); } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormBooking_and_Work_Order { interface tab_fstab_customer_Sections { fstab_customer_section_general: DevKit.Controls.Section; fstab_report_section_travel: 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_general_Sections { fstab_general_section_others: DevKit.Controls.Section; fstab_general_section_summary: DevKit.Controls.Section; } interface tab_fstab_Notes_Sections { fstab_notes_section_general: DevKit.Controls.Section; fstab_notes_section_quicknotes: DevKit.Controls.Section; fstab_notes_section_signature: DevKit.Controls.Section; } interface tab_fstab_service_Sections { fstab_service_section_general: DevKit.Controls.Section; } interface tab_fstab_Timeline_Sections { fstab_timeline_section_new: 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 tab_fstab_general extends DevKit.Controls.ITab { Section: tab_fstab_general_Sections; } interface tab_fstab_Notes extends DevKit.Controls.ITab { Section: tab_fstab_Notes_Sections; } interface tab_fstab_service extends DevKit.Controls.ITab { Section: tab_fstab_service_Sections; } interface tab_fstab_Timeline extends DevKit.Controls.ITab { Section: tab_fstab_Timeline_Sections; } interface Tabs { fstab_customer: tab_fstab_customer; fstab_fieldservice: tab_fstab_fieldservice; fstab_general: tab_fstab_general; fstab_Notes: tab_fstab_Notes; fstab_service: tab_fstab_service; fstab_Timeline: tab_fstab_Timeline; } interface Body { Tab: Tabs; /** Select the status of the booking. */ BookingStatus: DevKit.Controls.Lookup; /** Select whether the booking is solid or liquid. Solid bookings are firm and cannot be changed whereas liquid bookings can be changed. */ BookingType: DevKit.Controls.OptionSet; /** Enter the duration of the booking. */ Duration: DevKit.Controls.Integer; /** Enter the end date and time of the booking. */ EndTime: DevKit.Controls.DateTime; /** Shows the time that work started. */ msdyn_ActualArrivalTime: DevKit.Controls.DateTime; /** Shows the time that work started. */ msdyn_ActualArrivalTime_1: DevKit.Controls.DateTime; /** Shows the total travel duration. Calculated based on the difference between the Bookable Resource Booking's start time and actual arrival time. */ msdyn_ActualTravelDuration: DevKit.Controls.Integer; /** Shows the total travel duration. Calculated based on the difference between the Bookable Resource Booking's start time and actual arrival time. */ msdyn_ActualTravelDuration_1: DevKit.Controls.Integer; /** Agreement Booking Date from where this Booking was generated */ msdyn_AgreementBookingDate: DevKit.Controls.Lookup; /** Allow the time of this booking to be displayed on the schedule assistant as available. */ msdyn_AllowOverlapping: DevKit.Controls.Boolean; /** Shows the method used to create this booking. */ msdyn_BookingMethod: DevKit.Controls.OptionSet; /** Estimated Arrival Time */ msdyn_EstimatedArrivalTime: DevKit.Controls.DateTime; /** Estimated Travel Duration */ msdyn_EstimatedTravelDuration: DevKit.Controls.Integer; /** In this field you can enter the total miles the resource drove to the job site */ msdyn_MilesTraveled: DevKit.Controls.Double; /** Internal Use. This field is used to capture the time when the Booking was updated on mobile offline. */ msdyn_OfflineTimestamp: DevKit.Controls.DateTime; /** Internal For Quick note pcf control actions */ msdyn_quickNoteAction: DevKit.Controls.OptionSet; /** Unique identifier for Resource associated with Resource Booking */ msdyn_ResourceGroup: DevKit.Controls.Lookup; /** This field is used for capturing signature on Mobile (using the Pen Control) */ msdyn_Signature: DevKit.Controls.String; msdyn_TimeGroupDetailSelected: DevKit.Controls.Lookup; /** Unique identifier for Work Order associated with Resource Booking. */ msdyn_WorkOrder: DevKit.Controls.Lookup; /** Unique identifier for Work Order associated with Resource Booking. */ msdyn_WorkOrder_1: DevKit.Controls.Lookup; /** Unique identifier for Work Order associated with Resource Booking. */ msdyn_WorkOrder_2: DevKit.Controls.Lookup; /** Unique identifier for Work Order associated with Resource Booking. */ msdyn_WorkOrder_3: DevKit.Controls.Lookup; /** Type a name for the booking. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Shows the resource that is booked. */ Resource: DevKit.Controls.Lookup; /** Enter the start date and time of the booking. */ StartTime: DevKit.Controls.DateTime; } interface Navigation { nav_msdyn_bookableresourcebooking_msdyn_bookingjournal_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_bookingtimestamp_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_purchaseorder_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_purchaseorderproduct_AssociateToBooking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_purchaseorderreceiptproduct_AssociateToBooking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_rtv_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_timeentry_BookableResourceBooking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_workorderproduct_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_workorderservice_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_workorderservicetask_Booking: DevKit.Controls.NavigationItem, navActivities: DevKit.Controls.NavigationItem, navAsyncOperations: DevKit.Controls.NavigationItem, navAudit: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface Grid { msdyn_quicknotescontrol: DevKit.Controls.Grid; } } class FormBooking_and_Work_Order extends DevKit.IForm { /** * DynamicsCrm.DevKit form Booking_and_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 Booking_and_Work_Order */ Body: DevKit.FormBooking_and_Work_Order.Body; /** The Navigation of form Booking_and_Work_Order */ Navigation: DevKit.FormBooking_and_Work_Order.Navigation; /** The Grid of form Booking_and_Work_Order */ Grid: DevKit.FormBooking_and_Work_Order.Grid; } namespace FormBookableResourceBooking_Information { interface tab_FieldService_Sections { FieldService_section_2: DevKit.Controls.Section; FieldService_section_3: DevKit.Controls.Section; FieldService_section_4: DevKit.Controls.Section; FieldService_section_5: DevKit.Controls.Section; } interface tab_tab_2_Sections { tab_2_section_1: DevKit.Controls.Section; tab_2_section_2: DevKit.Controls.Section; tab_2_section_4: DevKit.Controls.Section; tab_2_section_5: DevKit.Controls.Section; } interface tab_tab_timeline_Sections { } interface tab_FieldService extends DevKit.Controls.ITab { Section: tab_FieldService_Sections; } interface tab_tab_2 extends DevKit.Controls.ITab { Section: tab_tab_2_Sections; } interface tab_tab_timeline extends DevKit.Controls.ITab { Section: tab_tab_timeline_Sections; } interface Tabs { FieldService: tab_FieldService; tab_2: tab_tab_2; tab_timeline: tab_tab_timeline; } interface Body { Tab: Tabs; /** Select the status of the booking. */ BookingStatus: DevKit.Controls.Lookup; /** Select whether the booking is solid or liquid. Solid bookings are firm and cannot be changed whereas liquid bookings can be changed. */ BookingType: DevKit.Controls.OptionSet; /** Enter the duration of the booking. */ Duration: DevKit.Controls.Integer; /** Enter the end date and time of the booking. */ EndTime: DevKit.Controls.DateTime; /** Defines whether this booking accepts changes propagated as cascading changes */ msdyn_AcceptCascadeCrewChanges: DevKit.Controls.Boolean; /** Shows the time that work started. */ msdyn_ActualArrivalTime: DevKit.Controls.DateTime; /** Shows the total travel duration. Calculated based on the difference between the Bookable Resource Booking's start time and actual arrival time. */ msdyn_ActualTravelDuration: DevKit.Controls.Integer; /** Agreement Booking Date from where this Booking was generated */ msdyn_AgreementBookingDate: DevKit.Controls.Lookup; /** Allow the time of this booking to be displayed on the schedule assistant as available. */ msdyn_AllowOverlapping: DevKit.Controls.Boolean; /** Shows the method used to create this booking. */ msdyn_BookingMethod: DevKit.Controls.OptionSet; /** Defines whether changing any of the following fields (Start Time, End Time, Status) should cascade the changes to other bookings on this requirement that have the same start and end time. */ msdyn_CascadeCrewChanges: DevKit.Controls.Boolean; /** This field is populated by the Field Service solution to define to which crew a booking is connected. */ msdyn_Crew: DevKit.Controls.Lookup; /** Crew Member Type */ msdyn_CrewMemberType: DevKit.Controls.OptionSet; /** Capacity that needs to take from resource capacity */ msdyn_effort: DevKit.Controls.Decimal; /** Estimated Arrival Time */ msdyn_EstimatedArrivalTime: DevKit.Controls.DateTime; /** Estimated Travel Duration */ msdyn_EstimatedTravelDuration: DevKit.Controls.Integer; msdyn_Latitude: DevKit.Controls.Double; msdyn_Longitude: DevKit.Controls.Double; /** In this field you can enter the total miles the resource drove to the job site */ msdyn_MilesTraveled: DevKit.Controls.Double; /** Internal Use. This field is used to capture the time when the Booking was updated on mobile offline. */ msdyn_OfflineTimestamp: DevKit.Controls.DateTime; /** Prevents time stamp creation if the time stamp was already created on a mobile device. */ msdyn_PreventTimestampCreation: DevKit.Controls.Boolean; /** Internal For Quick note pcf control actions */ msdyn_quickNoteAction: DevKit.Controls.OptionSet; /** Unique identifier for Resource associated with Resource Booking */ msdyn_ResourceGroup: DevKit.Controls.Lookup; /** Resource Requirement */ msdyn_ResourceRequirement: DevKit.Controls.Lookup; msdyn_TimeGroupDetailSelected: DevKit.Controls.Lookup; /** Shows the total billable duration. If you leave this field blank the system automatically determines the billable duration by calculating the resource journal details. */ msdyn_TotalBillableDuration: DevKit.Controls.Integer; /** Shows the total break duration. If you leave this field blank the system automatically determines the break duration by calculating the resource journal details. */ msdyn_TotalBreakDuration: DevKit.Controls.Integer; /** Shows the total cost for this booking. */ msdyn_TotalCost: DevKit.Controls.Money; /** Shows the total duration that this booking was in progress. */ msdyn_TotalDurationInProgress: DevKit.Controls.Integer; msdyn_WorkLocation: DevKit.Controls.OptionSet; /** Unique identifier for Work Order associated with Resource Booking. */ msdyn_WorkOrder: DevKit.Controls.Lookup; /** Type a name for the booking. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Shows the resource that is booked. */ Resource: DevKit.Controls.Lookup; /** Enter the start date and time of the booking. */ StartTime: DevKit.Controls.DateTime; } interface Navigation { nav_msdyn_bookableresourcebooking_msdyn_bookingjournal_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_bookingtimestamp_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_purchaseorder_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_purchaseorderproduct_AssociateToBooking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_purchaseorderreceiptproduct_AssociateToBooking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_rtv_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_workorderproduct_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_workorderservice_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_workorderservicetask_Booking: DevKit.Controls.NavigationItem } interface Grid { msdyn_quicknotescontrol: DevKit.Controls.Grid; TIMESTAMPS: DevKit.Controls.Grid; } } class FormBookableResourceBooking_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form BookableResourceBooking_Information * @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 BookableResourceBooking_Information */ Body: DevKit.FormBookableResourceBooking_Information.Body; /** The Navigation of form BookableResourceBooking_Information */ Navigation: DevKit.FormBookableResourceBooking_Information.Navigation; /** The Grid of form BookableResourceBooking_Information */ Grid: DevKit.FormBookableResourceBooking_Information.Grid; } namespace FormResource_Booking_Mobile_Deprecated { interface Header extends DevKit.Controls.IHeader { /** Select the status of the booking. */ BookingStatus: DevKit.Controls.Lookup; /** Unique identifier for Work Order associated with Resource Booking. */ msdyn_WorkOrder: DevKit.Controls.Lookup; /** Enter the start date and time of the booking. */ StartTime: DevKit.Controls.DateTime; } interface tab_FieldService_Sections { FieldService_column_5_section_1: DevKit.Controls.Section; FieldService_column_6_section_1: DevKit.Controls.Section; FieldService_section_1: DevKit.Controls.Section; FieldService_section_2: DevKit.Controls.Section; FieldService_section_4: DevKit.Controls.Section; FieldService_section_5: DevKit.Controls.Section; FieldService_section_6: DevKit.Controls.Section; } interface tab_fstab_general_Sections { fstab_general_section_general: DevKit.Controls.Section; fstab_general_section_misc: DevKit.Controls.Section; fstab_general_section_schedule: DevKit.Controls.Section; fstab_general_section_travel: DevKit.Controls.Section; fstab_note_section: DevKit.Controls.Section; tab_actions: DevKit.Controls.Section; } interface tab_fstab_signature_Sections { fstab_signature_section_signature: DevKit.Controls.Section; } interface tab_fstab_timeline_Sections { fstab_note_section_2: DevKit.Controls.Section; } interface tab_FieldService extends DevKit.Controls.ITab { Section: tab_FieldService_Sections; } interface tab_fstab_general extends DevKit.Controls.ITab { Section: tab_fstab_general_Sections; } interface tab_fstab_signature extends DevKit.Controls.ITab { Section: tab_fstab_signature_Sections; } interface tab_fstab_timeline extends DevKit.Controls.ITab { Section: tab_fstab_timeline_Sections; } interface Tabs { FieldService: tab_FieldService; fstab_general: tab_fstab_general; fstab_signature: tab_fstab_signature; fstab_timeline: tab_fstab_timeline; } interface Body { Tab: Tabs; /** Select the status of the booking. */ BookingStatus: DevKit.Controls.Lookup; /** Select whether the booking is solid or liquid. Solid bookings are firm and cannot be changed whereas liquid bookings can be changed. */ BookingType: DevKit.Controls.OptionSet; /** Enter the duration of the booking. */ Duration: DevKit.Controls.Integer; /** Enter the end date and time of the booking. */ EndTime: DevKit.Controls.DateTime; /** Shows the time that work started. */ msdyn_ActualArrivalTime: DevKit.Controls.DateTime; /** Shows the total travel duration. Calculated based on the difference between the Bookable Resource Booking's start time and actual arrival time. */ msdyn_ActualTravelDuration: DevKit.Controls.Integer; /** Agreement Booking Date from where this Booking was generated */ msdyn_AgreementBookingDate: DevKit.Controls.Lookup; /** Allow the time of this booking to be displayed on the schedule assistant as available. */ msdyn_AllowOverlapping: DevKit.Controls.Boolean; /** Shows the method used to create this booking. */ msdyn_BookingMethod: DevKit.Controls.OptionSet; /** Estimated Arrival Time */ msdyn_EstimatedArrivalTime: DevKit.Controls.DateTime; /** Estimated Travel Duration */ msdyn_EstimatedTravelDuration: DevKit.Controls.Integer; msdyn_Latitude: DevKit.Controls.Double; msdyn_Longitude: DevKit.Controls.Double; /** In this field you can enter the total miles the resource drove to the job site */ msdyn_MilesTraveled: DevKit.Controls.Double; /** Internal Use. This field is used to capture the time when the Booking was updated on mobile offline. */ msdyn_OfflineTimestamp: DevKit.Controls.DateTime; /** Internal For Quick note pcf control actions */ msdyn_quickNoteAction: DevKit.Controls.OptionSet; /** Unique identifier for Resource associated with Resource Booking */ msdyn_ResourceGroup: DevKit.Controls.Lookup; /** This field is used for capturing signature on Mobile (using the Pen Control) */ msdyn_Signature: DevKit.Controls.String; msdyn_TimeGroupDetailSelected: DevKit.Controls.Lookup; /** Shows the total billable duration. If you leave this field blank the system automatically determines the billable duration by calculating the resource journal details. */ msdyn_TotalBillableDuration: DevKit.Controls.Integer; /** Shows the total break duration. If you leave this field blank the system automatically determines the break duration by calculating the resource journal details. */ msdyn_TotalBreakDuration: DevKit.Controls.Integer; /** Shows the total cost for this booking. */ msdyn_TotalCost: DevKit.Controls.Money; /** Shows the total duration that this booking was in progress. */ msdyn_TotalDurationInProgress: DevKit.Controls.Integer; /** Type a name for the booking. */ Name: DevKit.Controls.String; notescontrol: DevKit.Controls.Note; /** Shows the resource that is booked. */ Resource: DevKit.Controls.Lookup; /** Enter the start date and time of the booking. */ StartTime: DevKit.Controls.DateTime; /** Exchange rate for the currency associated with the BookableResourceBooking with respect to the base currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_bookableresourcebooking_msdyn_bookingjournal_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_bookingtimestamp_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_purchaseorder_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_purchaseorderproduct_AssociateToBooking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_purchaseorderreceiptproduct_AssociateToBooking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_rtv_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_workorderproduct_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_workorderservice_Booking: DevKit.Controls.NavigationItem, nav_msdyn_bookableresourcebooking_msdyn_workorderservicetask_Booking: DevKit.Controls.NavigationItem, navAsyncOperations: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } interface quickForm_WorkOrderQuickView_Body { msdyn_Address1: DevKit.Controls.QuickView; msdyn_City: DevKit.Controls.QuickView; msdyn_Country: DevKit.Controls.QuickView; msdyn_CustomerAsset: DevKit.Controls.QuickView; msdyn_PostalCode: DevKit.Controls.QuickView; msdyn_PrimaryIncidentDescription: DevKit.Controls.QuickView; msdyn_PrimaryIncidentType: DevKit.Controls.QuickView; msdyn_ServiceAccount: DevKit.Controls.QuickView; msdyn_StateOrProvince: DevKit.Controls.QuickView; msdyn_TotalAmount: DevKit.Controls.QuickView; msdyn_TotalSalesTax: DevKit.Controls.QuickView; } interface quickForm_WorkOrderQuickView extends DevKit.Controls.IQuickView { Body: quickForm_WorkOrderQuickView_Body; } interface QuickForm { WorkOrderQuickView: quickForm_WorkOrderQuickView; } interface Grid { PRODUCTS: DevKit.Controls.Grid; SERVICES: DevKit.Controls.Grid; SERVICE_TASKS: DevKit.Controls.Grid; msdyn_quicknotescontrol: DevKit.Controls.Grid; ServiceTasks: DevKit.Controls.Grid; } } class FormResource_Booking_Mobile_Deprecated extends DevKit.IForm { /** * DynamicsCrm.DevKit form Resource_Booking_Mobile_Deprecated * @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 Resource_Booking_Mobile_Deprecated */ Body: DevKit.FormResource_Booking_Mobile_Deprecated.Body; /** The Header section of form Resource_Booking_Mobile_Deprecated */ Header: DevKit.FormResource_Booking_Mobile_Deprecated.Header; /** The Navigation of form Resource_Booking_Mobile_Deprecated */ Navigation: DevKit.FormResource_Booking_Mobile_Deprecated.Navigation; /** The QuickForm of form Resource_Booking_Mobile_Deprecated */ QuickForm: DevKit.FormResource_Booking_Mobile_Deprecated.QuickForm; /** The Grid of form Resource_Booking_Mobile_Deprecated */ Grid: DevKit.FormResource_Booking_Mobile_Deprecated.Grid; } class BookableResourceBookingApi { /** * DynamicsCrm.DevKit BookableResourceBookingApi * @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 resource booking. */ BookableResourceBookingId: DevKit.WebApi.GuidValue; /** Select the status of the booking. */ BookingStatus: DevKit.WebApi.LookupValue; /** Select whether the booking is solid or liquid. Solid bookings are firm and cannot be changed whereas liquid bookings can be changed. */ BookingType: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Enter the duration of the booking. */ Duration: DevKit.WebApi.IntegerValue; /** Enter the end date and time of the booking. */ EndTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Exchange rate for the currency associated with the bookableresourcebooking with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the reference to the booking header record that represents the summary of bookings. */ Header: DevKit.WebApi.LookupValue; /** 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; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Defines whether this booking accepts changes propagated as cascading changes */ msdyn_AcceptCascadeCrewChanges: DevKit.WebApi.BooleanValue; /** Shows the time that work started. */ msdyn_ActualArrivalTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the total travel duration. Calculated based on the difference between the Bookable Resource Booking's start time and actual arrival time. */ msdyn_ActualTravelDuration: DevKit.WebApi.IntegerValue; /** Agreement Booking Date from where this Booking was generated */ msdyn_AgreementBookingDate: DevKit.WebApi.LookupValue; /** Allow the time of this booking to be displayed on the schedule assistant as available. */ msdyn_AllowOverlapping: DevKit.WebApi.BooleanValue; /** Unique identifier for Appointment associated with Bookable Resource Booking. */ msdyn_AppointmentBookingId: DevKit.WebApi.LookupValue; /** The Base travel duration indicates the travel time without traffic */ msdyn_BaseTravelDuration: DevKit.WebApi.IntegerValue; /** Shows the method used to create this booking. */ msdyn_BookingMethod: DevKit.WebApi.OptionSetValue; /** A unique identifier for the booking setup metadata that is associated with a bookable resource booking. */ msdyn_BookingSetupMetadataId: DevKit.WebApi.LookupValue; /** Defines whether changing any of the following fields (Start Time, End Time, Status) should cascade the changes to other bookings on this requirement that have the same start and end time. */ msdyn_CascadeCrewChanges: DevKit.WebApi.BooleanValue; /** This field is populated by the Field Service solution to define to which crew a booking is connected. */ msdyn_Crew: DevKit.WebApi.LookupValue; /** Crew Member Type */ msdyn_CrewMemberType: DevKit.WebApi.OptionSetValue; /** Capacity that needs to take from resource capacity */ msdyn_effort: DevKit.WebApi.DecimalValue; /** Estimated Arrival Time */ msdyn_EstimatedArrivalTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Estimated Travel Duration */ msdyn_EstimatedTravelDuration: DevKit.WebApi.IntegerValue; /** For internal use only. */ msdyn_InternalFlags: DevKit.WebApi.StringValue; msdyn_Latitude: DevKit.WebApi.DoubleValue; msdyn_Longitude: DevKit.WebApi.DoubleValue; /** In this field you can enter the total miles the resource drove to the job site */ msdyn_MilesTraveled: DevKit.WebApi.DoubleValue; /** Internal Use. This field is used to capture the time when the Booking was updated on mobile offline. */ msdyn_OfflineTimestamp_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Prevents time stamp creation if the time stamp was already created on a mobile device. */ msdyn_PreventTimestampCreation: DevKit.WebApi.BooleanValue; /** Project of booking detail record */ msdyn_projectid: DevKit.WebApi.LookupValue; /** Project team member of booking detail record */ msdyn_projectteamid: DevKit.WebApi.LookupValue; /** Internal For Quick note pcf control actions */ msdyn_quickNoteAction: DevKit.WebApi.OptionSetValue; /** Requirement Group */ msdyn_requirementgroupid: DevKit.WebApi.LookupValue; /** Resource Category */ msdyn_resourcecategoryid: DevKit.WebApi.LookupValue; /** Unique identifier for Resource associated with Resource Booking */ msdyn_ResourceGroup: DevKit.WebApi.LookupValue; /** Resource Requirement */ msdyn_ResourceRequirement: DevKit.WebApi.LookupValue; /** Unique identifier for Service Appointment associated with Resource Booking. */ msdyn_serviceappointment: DevKit.WebApi.LookupValue; /** This field is used for capturing signature on Mobile (using the Pen Control) */ msdyn_Signature: DevKit.WebApi.StringValue; /** Shows the automatically generated text of the time slot on the schedule board. */ msdyn_SlotText: DevKit.WebApi.StringValue; msdyn_TimeGroupDetailSelected: DevKit.WebApi.LookupValue; /** Shows the total billable duration. If you leave this field blank the system automatically determines the billable duration by calculating the resource journal details. */ msdyn_TotalBillableDuration: DevKit.WebApi.IntegerValue; /** Shows the total break duration. If you leave this field blank the system automatically determines the break duration by calculating the resource journal details. */ msdyn_TotalBreakDuration: DevKit.WebApi.IntegerValue; /** Shows the total cost for this booking. */ msdyn_TotalCost: DevKit.WebApi.MoneyValue; /** Value of the Total Cost in base currency. */ msdyn_totalcost_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total duration that this booking was in progress. */ msdyn_TotalDurationInProgress: DevKit.WebApi.IntegerValue; /** Travel Time Calculation */ msdyn_TravelTimeCalculationType: DevKit.WebApi.OptionSetValue; msdyn_TravelTimeRescheduling: DevKit.WebApi.BooleanValue; /** For internal use only. */ msdyn_URSInternalFlags: DevKit.WebApi.StringValue; msdyn_WorkLocation: DevKit.WebApi.OptionSetValue; /** Unique identifier for Work Order associated with Resource Booking. */ msdyn_WorkOrder: DevKit.WebApi.LookupValue; /** Type a name for the booking. */ Name: DevKit.WebApi.StringValue; /** 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; /** Shows the resource that is booked. */ Resource: DevKit.WebApi.LookupValue; /** Contains the id of the stage where the entity is located. */ StageId: DevKit.WebApi.GuidValue; /** Enter the start date and time of the booking. */ StartTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Status of the Bookable Resource Booking */ StateCode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Bookable Resource Booking */ StatusCode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Exchange rate for the currency associated with the BookableResourceBooking with respect to the base currency. */ 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; /** 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 BookableResourceBooking { enum BookingType { /** 2 */ Liquid, /** 1 */ Solid } enum msdyn_BookingMethod { /** 690970003 */ Manual, /** 690970002 */ Mobile, /** 192350000 */ Resource_Scheduling_Optimization, /** 690970004 */ Schedule_Assistant, /** 690970001 */ Schedule_Board, /** 690970005 */ System_Agreement_Schedule } enum msdyn_CrewMemberType { /** 192350000 */ Leader, /** 192350001 */ Member, /** 192350002 */ None } enum msdyn_quickNoteAction { /** 100000004 */ audio, /** 100000005 */ file, /** 100000000 */ none, /** 100000002 */ photo, /** 100000001 */ text, /** 100000003 */ video } enum msdyn_TravelTimeCalculationType { /** 192350003 */ Approximate, /** 192350001 */ Bing_Maps_with_historical_traffic, /** 192350000 */ Bing_Maps_without_historical_traffic, /** 192350002 */ Custom_Map_Provider } 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':['Booking and Work Order','Information','Resource Booking - Mobile (Deprecated)'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Logger, logger, DebugSession, LoggingDebugSession, InitializedEvent, TerminatedEvent, StoppedEvent, BreakpointEvent, OutputEvent, Event, ContinuedEvent, Thread, StackFrame, Scope, Source, Handles, Breakpoint, Variable, LoadedSourceEvent } from 'vscode-debugadapter'; import {DebugProtocol} from 'vscode-debugprotocol'; import {readFileSync} from 'fs'; import {basename, dirname, join} from 'path'; import {spawn, ChildProcess} from 'child_process'; const { Subject } = require('await-notify'); import { PerlDebuggerConnection, RequestResponse } from './adapter'; import { variableType, ParsedVariable, ParsedVariableScope, resolveVariable } from './variableParser'; /** * This interface should always match the schema found in the perl-debug extension manifest. */ export interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments { /** Perl binary */ exec: string; /** Binary executable arguments */ execArgs: string[], /** Workspace path */ root: string, /** An absolute path to the program to debug. */ program: string; /** Automatically stop target after launch. If not specified, target does not stop. */ stopOnEntry?: boolean; /** List of includes */ inc?: string[]; /** List of program arguments */ args?: string[]; /** enable logging the Debug Adapter Protocol */ trace?: boolean; /** env variables when executing debugger */ env?: {}; /** port for debugger to listen for remote debuggers */ port?, /** Where to launch the debug target */ console?: string, /** Log raw I/O with debugger in output channel */ debugRaw?: boolean, /** How to handle forked children or multiple connections */ sessions?: string, } export class PerlDebugSession extends LoggingDebugSession { private static THREAD_ID = 1; private _breakpointId = 1000; private _breakPoints = new Map<string, DebugProtocol.Breakpoint[]>(); private _functionBreakPoints: Map<string, DebugProtocol.Breakpoint> = new Map<string, DebugProtocol.Breakpoint>(); private _loadedSources = new Map<string, Source>(); private _variableHandles = new Handles<string>(); public dcSupportsRunInTerminal: boolean = false; private adapter: PerlDebuggerConnection; public constructor() { super('perl_debugger.log'); this.adapter = new PerlDebuggerConnection(); this.setDebuggerLinesStartAt1(false); this.setDebuggerColumnsStartAt1(false); } private rootPath: string = ''; private _configurationDone = new Subject(); /* protected convertClientPathToDebugger(clientPath: string): string { return clientPath.replace(this.rootPath, ''); } protected convertDebuggerPathToClient(debuggerPath: string): string { return join(this.rootPath, debuggerPath); }*/ protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void { this.dcSupportsRunInTerminal = !!args.supportsRunInTerminalRequest; this.adapter.on('perl-debug.output', (text) => { this.sendEvent(new OutputEvent(`${text}\n`)); }); this.adapter.on('perl-debug.exception', (res) => { // xxx: for now I need more info, code to go away... const [ error ] = res.errors; this.sendEvent( new OutputEvent(`${error.message}`, 'stderr') ); }); this.adapter.on('perl-debug.termination', (x) => { this.sendEvent(new TerminatedEvent()); }); this.adapter.on('perl-debug.stopped', (x) => { // FIXME(bh): `breakpoint` is not always correct here. this.sendEvent(new StoppedEvent("breakpoint", PerlDebugSession.THREAD_ID)); }); this.adapter.on('perl-debug.close', (x) => { this.sendEvent(new TerminatedEvent()); }); this.adapter.on('perl-debug.debug', (...x) => { // FIXME: needs to check launch options this.sendEvent(new Event('perl-debug.debug', x)); }); this.adapter.on('perl-debug.new-source', () => { // FIXME(bh): There is probably a better way to re-use the code // in that function that does not require setting up a malformed // object here, but this seems good enough for the moment. this.loadedSourcesRequestAsync( {} as DebugProtocol.LoadedSourcesResponse, {} ); }); this.adapter.on( 'perl-debug.attachable.listening', data => { this.sendEvent( new Event( 'perl-debug.attachable.listening', data ) ); } ); this.adapter.initializeRequest() .then(() => { // This debug adapter implements the configurationDoneRequest. response.body.supportsConfigurationDoneRequest = true; // make VS Code to use 'evaluate' when hovering over source response.body.supportsEvaluateForHovers = true; // make VS Code to show a 'step back' button response.body.supportsStepBack = false; response.body.supportsFunctionBreakpoints = true; response.body.supportsLoadedSourcesRequest = true; response.body.supportsTerminateRequest = true; response.body.supportsSetVariable = true; this.sendResponse(response); }); } /** * Called at the end of the configuration sequence. * Indicates that all breakpoints etc. have been sent to the DA and that the 'launch' can start. */ protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void { super.configurationDoneRequest(response, args); // notify the launchRequest that configuration has finished this._configurationDone.notify(); } private stepAfterFork( sessions: string, launchResponse: RequestResponse ) { const stoppedInForkWrapper = /^Devel::vscode::_fork/.test(launchResponse.data[0] || ""); const pidsInDebuggerPrompt = /^\[pid=/.test(launchResponse.db); if (stoppedInForkWrapper && sessions === 'break') { // step out of the wrapper this.adapter.request('s'); } if (sessions === 'watch') { this.adapter.request('c'); this.sendEvent( new ContinuedEvent(PerlDebugSession.THREAD_ID) ); } else if (sessions === 'break') { this.sendEvent( new StoppedEvent("postfork", PerlDebugSession.THREAD_ID) ); } } protected async launchRequest( response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments ) { this.rootPath = args.root; logger.setup(args.trace ? Logger.LogLevel.Verbose : Logger.LogLevel.Stop, false); this.adapter.removeAllListeners('perl-debug.streamcatcher.data'); this.adapter.removeAllListeners('perl-debug.streamcatcher.write'); if (args.debugRaw) { this.adapter.on('perl-debug.streamcatcher.data', (...x) => { this.sendEvent(new Event('perl-debug.streamcatcher.data', x)); }); this.adapter.on('perl-debug.streamcatcher.write', (...x) => { this.sendEvent(new Event('perl-debug.streamcatcher.write', x)); }); } // TODO(bh): If the user manually launches two debug sessions in // parallel, this would clear output from one of the sessions // when starting the other one. That is not ideal. if (args.console !== '_attach') { this.sendEvent(new Event('perl-debug.streamcatcher.clear')); } const launchResponse = await this.adapter.launchRequest( args, // Needs a reference to the session for `runInTerminal` this ); // NOTE(bh): This extension used to send the `InitializedEvent` // at the beginning of the `initializeRequest`. That was taken // as a signal that we can accept configurations right away, but // we actually need to talk to the debugger to set breakpoints // without buffering them. Fixed in part thanks to the help in // https://github.com/Microsoft/vscode/issues/69317 this.sendEvent(new InitializedEvent()); // With the event sent vscode should now send us breakpoint and // other configuration requests and signals us that it done doing // so with a `configurationDoneRequest`, so we wait here for it. await this._configurationDone.wait(2000); if (args.console === '_attach') { this.stepAfterFork(args.sessions, launchResponse); } else if (args.stopOnEntry) { this.sendResponse(response); // we stop on the first line this.sendEvent(new StoppedEvent("entry", PerlDebugSession.THREAD_ID)); } else { // we just start to run until we hit a breakpoint or an exception this.continueRequest( <DebugProtocol.ContinueResponse>response, { threadId: PerlDebugSession.THREAD_ID } ); } } protected threadsRequest(response: DebugProtocol.ThreadsResponse): void { // NOTE(bh): vscode actually shows the thread name in the user // interface during multi-session debugging, at least until // https://github.com/Microsoft/vscode/issues/69752 is addressed, // so this tries to make a pretty name for it. // NOTE(bh): "The use of interpreter-based threads in perl is // officially discouraged." -- `perldoc threads`. This extension // does not support them in any way, so we only ever report one // thread per adapter instance. response.body = { threads: [ new Thread( PerlDebugSession.THREAD_ID, this.adapter.getThreadName() ) ] }; this.sendResponse(response); } /** * TODO * * if possible: * * * step out * * step back * * reverse continue * * data breakpoints (https://github.com/raix/vscode-perl-debug/issues/4) */ /** * Reverse continue */ protected reverseContinueRequest(response: DebugProtocol.ReverseContinueResponse, args: DebugProtocol.ReverseContinueArguments) : void { this.sendEvent(new OutputEvent(`ERR>Reverse continue not implemented\n\n`)); response.success = false; this.sendResponse(response); this.sendEvent(new StoppedEvent("entry", PerlDebugSession.THREAD_ID)); } /** * Step back */ protected stepBackRequest(response: DebugProtocol.StepBackResponse, args: DebugProtocol.StepBackArguments): void { this.sendEvent(new OutputEvent(`ERR>Step back not implemented\n`)); response.success = false; this.sendResponse(response); this.sendEvent(new StoppedEvent("entry", PerlDebugSession.THREAD_ID)); } private async checkSignaling(): Promise<boolean> { if (!this.adapter.canSignalDebugger) { return false; } // When we get here, it looks as though we run on the same host // and our user also has a process with a process identifier that // matches the one we got from the debugger. Check if we can make // the debugger send us a SIGINT. If that works, we assume that // the other direction works aswell. In the unlikely worst case, // the signal goes to the wrong process on a different machine. const result = Promise.race<boolean>([ new Promise<boolean>(resolve => { process.once('SIGINT', () => resolve(true)) }), new Promise<boolean>((resolve, reject) => { setTimeout(() => resolve(false), 200) }) ]); await this.adapter.getExpressionValue( `CORE::kill('INT', ${process.pid})` ); return result; } protected async disconnectRequest( response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments ): Promise<void> { this.adapter.terminateDebugger() await this.adapter.destroy(); this.sendResponse(response); } protected async terminateRequest( response: DebugProtocol.TerminateResponse, args: DebugProtocol.TerminateArguments ): Promise<void> { if (this.adapter.terminateDebugger()) { // FIXME(bh): Unsure whether to do this here. await this.adapter.destroy(); this.sendResponse(response); } else { response.success = false; response.body = { error: { message: 'Cannot send SIGTERM to debugger on remote system' } }; this.sendResponse(response); } } protected pauseRequest(response: DebugProtocol.PauseResponse, args: DebugProtocol.PauseArguments): void { if (!this.adapter.canSignalDebugger) { response.success = false; response.body = { error: { message: 'Cannot send SIGINT to debugger on remote system' } }; this.sendResponse(response); } else { // Send SIGINT to the `perl -d` process on the local system. process.kill(this.adapter.debuggerPid, 'SIGINT'); this.sendResponse(response); } } private isValidFunctionName(name: string): boolean { return /^[':A-Za-z_][':\w]*$/.test(name); } private async setFunctionBreakPointAsync( bp: DebugProtocol.FunctionBreakpoint ): Promise<DebugProtocol.Breakpoint> { if (!this.isValidFunctionName(bp.name)) { // Report an unverified breakpoint when there is an attempt to // set a function breakpoint on something that cannot be a Perl // function; we cannot pass illegal names like `12345` to the // debugger as it might misinterpret it as something other than // a function breakpoint request. return new Breakpoint(false); } const res = await this.adapter.request(`b ${bp.name}`); if (/Subroutine \S+ not found/.test(res.data[0])) { // Unverified (and ignored by the debugger), but see below. } this.sendEvent(new OutputEvent( `Adding function breakpoint on ${bp.name}\n` )); // NOTE(bh): This is a simple attempt to get file and line // information about where the sub is defined, at least to // some extent, by going through `%DB::sub`, assuming it has // already been loaded and has not been defined in unusal // ways. Not sure if vscode actually uses the values though. const pathPos = await this.adapter.getExpressionValue( `$DB::sub{'${this.adapter.escapeForSingleQuotes(bp.name)}'}` ); const [ bpWhole, bpFile, bpFirst, bpLast ] = pathPos ? pathPos.match( /(.*):(\d+)-(\d+)$/ ) : [undefined, undefined, undefined, undefined]; return new Breakpoint( !!pathPos, parseInt(bpFirst), undefined, new Source( bpFile, bpFile, ) ); } private async setFunctionBreakPointsRequestAsync(response: DebugProtocol.SetFunctionBreakpointsResponse, args: DebugProtocol.SetFunctionBreakpointsArguments): Promise<DebugProtocol.SetFunctionBreakpointsResponse> { // FIXME(bh): It is not clear yet how to set breakpoints on subs // that are not yet loaded at program start time. Global watch // expressions can be used like so: // // % perl -d -e0 // // Loading DB routines from perl5db.pl version 1.53 // Editor support available. // // Enter h or 'h h' for help, or 'man perldebug' for more help. // // main::(-e:1): 0 // DB<1> w *Data::Dumper::Dumper{CODE} // DB<2> use Data::Dumper // // DB<3> r // Watchpoint 0: *Data::Dumper::Dumper{CODE} changed: // old value: '' // new value: 'CODE(0x55f9e2629688)' // // But possibly with considerable performance impact as any // watch expression would put the debugger in trace mode? Might // make sense to offer that behind a `launch.json` option. for (const [name, bp] of this._functionBreakPoints.entries()) { // Remove breakpoint await this.adapter.request(`B ${name}`); } this._functionBreakPoints.clear(); for (const bp of args.breakpoints) { this._functionBreakPoints.set( bp.name, await this.setFunctionBreakPointAsync(bp) ); } response.body = { breakpoints: [...this._functionBreakPoints.values()] }; return response; } protected setFunctionBreakPointsRequest(response: DebugProtocol.SetFunctionBreakpointsResponse, args: DebugProtocol.SetFunctionBreakpointsArguments): void { this.setFunctionBreakPointsRequestAsync(response, args) .then(res => { this.sendResponse(response); }) .catch(err => { const [ error = err ] = err.errors || []; this.sendEvent(new OutputEvent(`ERR>setFunctionBreakPointsRequest error: ${error.message}\n`)); response.success = false; this.sendResponse(response); }); } /** * Implemented */ /** * Set variable */ protected setVariableRequest(response: DebugProtocol.SetVariableResponse, args: DebugProtocol.SetVariableArguments): void { // Get type of variable contents const name = this.getVariableName(args.name, args.variablesReference) .then((variableName) => { // We use perl's eval() here for maximum flexibility so that the user can actually change the type of the value in the VS Code // GUI on-the-fly. E.g. by simply changing a scalar value into an array ref by typing [1,2,3] as the new value of the scalar. // E.g. if the user has an array @a = (1,2,3) and edits the 2nd element (2) by typing [4,5,6] in the GUI, the scalar value of 2 // will be replaced with the expected array ref, so the updated array will look like @a = (1,[4,5,6],3) after the edit. // This allows the user to arbitrarily change the structure of composite types (like arrays and hashes) on-the-fly during debugging // using the VS Code GUI. In fact, it also allows you to do arithmetic during editing a value so you can just simply type "11 + 22" // as the new value and it becomes 33. And you can use any valid perl expression for the new value e.g. $x + $y will set the value // to the sum of vars $x and $y (they obviously have to be defined in the perl code and visible in the given scope). // // Note that we also support perl string interpolation just like perl does. // This means that what the new value will be depends on whether or how the specified value is quoted by the user in the GUI. // // Assume we have two perl vars $x and $y, with values 1 and 2 respectively, then quoting will work as a perl programmer expects it // to work: // // 1. Unquoted expression: $x + $y evaluates to the value 3 because $x = 1 and $y = 2. (3 = 1 + 2) // // 2. Quoted expression: // // 1. Single-quoted: '$x + $y' evaluates to the string '$x + $y'. No variable interpolation // // 2. double-quoted: "$x + $y" evaluates to the string '1 + 2'. Variable interpolation // // // Note that the following assignment operations assume that the user types in meaningful perl expressions. // // Otherwise GIGO rules apply. That is, if the user specifies a garbage expression, then the result will be a garbage value or a failed assignment. // If the user-specified string is not a valid perl expression then it will be assigned as an interpolated perl string (unless it's single quoted, // in which case it's not interpolated). This is not a bug but a feature (and hence it won't be "fixed"). The malformed expression will be assigned // as a string to the variable so that the user can easily see that they made a mistake (because they will get a string instead of e.g. the expected // array). But for normal everyday well-formed user input this will not happen so it will not be an issue. // // That is, the following implementation provides perl programmers with an intuitive set of assignment operations but it assumes that the // user actually knows what perl expressions actually look like (so that they don't type garbage expressions in). // // Note that some of the heuristic assignment rules below deliberately use extended semantics compared to perl to make value assignments uniform // for both composite (arrays, hashes, objects) and scalar variables so that you don't have to care about whether you have to specify an array or // an array ref when e.g. creating an array. This is not a bug but a feature. So that you can just simply use the same array (1,2,3,4) and assign // this in the VS Code GUI to any type of variable and you will get an array in the appropriate form (array or array ref). In other words, these // assignment rules automatically convert between arrays and array refs as needed depending on context, hence allowing intuitive uniform assingments // to variables. E.g. in the VS Code GUI you can assign the array (1,2,3,4) to an array @a, an element in the array $a[i], to a hash %h, to a key // in the hash $h{k} or a scalar $s and you will get an array in the given position // // @a = (1,2,3,4) // $a[i] = [1,2,3,4] // %h = (1,2,3,4) // $h{k} = [1,2,3,4] // $s = [1,2,3,4] // // Note that some of these arrays are actually array refs but you don't have to care about this difference. The appropriate form (ref or non-ref) // will be used automatically. // // So you can just simply assign an array value of (1,2,3,4) to any variable without having to care about whether you have to use an array ref or // not in the given context. But this also means that these intuitive assignments are NOT (necessarily) perl assignment instructions. Because perl // doesn't do this automatic conversion between refs and nonrefs. So in perl the above assignments would be // // @a = (1,2,3,4) // $a[i] = (1,2,3,4) // %h = (1,2,3,4) // $h{k} = (1,2,3,4) // $s = (1,2,3,4) // // and although the assignments to @a and %h would work the same way as above, but perl would assign the last element (4) to all the scalar variables // $a[i], $h{k} and $s (so $a[i] = 4, $h{k} = 4, $s = 4) because of the scalar context, which is obviously not what the user's intention was when they // specified (1,2,3,4) in the GUI. // // So the intuitive heuristic assignment rules below do what the user would intuitively expect to happen and not necessarily what perl would do:) // // // The following array (@a), hash (%h) and scalar ($s) assigment operations are supported: // --------------------------------------------------------------------------------------- // // The "User Input" column shows what the user types into the VS Code GUI edit box when editing a variable (@a, %h, $s). // The "Assignment" column shows what perl assignment will be done as a result. // // E.g. typing @x into the edit box while editing the value of @a will copy the elements of @x over into @a as in @a = @x. // // // User Input Assignment // // @a: // @x @a = @x // %h @a = %h // $s @a = ($s) // {1,2} @a = (1,2) // ({1,2}) @a = ({1,2}) // 1,2,3 @a = (1,2,3) // (1,2,3) @a = (1,2,3) // [1,2,3] @a = (1,2,3) // ([1,2,3]) @a = ([1,2,3]) // // %h: // %x %h = %x // @a %h = @a // {1,2} %h = (1,2) // 1,2,3,4 %h = (1,2,3,4) (hence (1 => 2, 3 => 4)) // (1,2,3,4) %h = (1,2,3,4) // [1,2,3,4] %h = (1,2,3,4) // // $s: // $x $s = $x // @a $s = [@a] // %h $s = {@{[%h]}} (a hashref to a copy of %h) // {1,2} $s = {1,2} // 1,2,3 $s = "1,2,3" // (1,2,3) $s = [1,2,3] // [1,2,3] $s = [1,2,3] // ([1,2,3]) $s = [[1,2,3]] // undef $s = undef // // String ops with the usual quoting rules and variable interpolation are also supported. // // Plus some simpler perl expressions. Invalid expressions are treated as double-quoted strings and will be interpolated accordingly. // Some examples: assuming $x = 1 and $y = 2 // // 11 + 22 $s = 11 + 22 (hence $s = 33) // $x + $y $s = 1 + 2 (hence $s = 3) // '$x + $y' $s = '$x + $y' // "$x + $y" $s = "1 + 2" // // $x,$y,3 $s = "1,2,3" // ($x,$y,3) $s = [1,2,3] // [$x,$y,3] $s = [1,2,3] // // Invalid expressions are treated as double-quoted strings and interpolated accordingly e.g. // // 11 + $s = "11 +" // $x + $s = "1 +" // // Quoted invalid expressions are strings and hence are interpolated according to their quotation marks e.g. // // '$x +' $s = '$x +' // "$x +" $s = "1 +" // // Special case for x'y. Old-style class reference lookalikes are interpreted as strings and not as x::y because it's extremely unlikely // that actually old-style class references are used by the user in the expression. This way strings with single-quotes will work // seamlessly (e.g. "There's" remains "There's" intead of becoming "There::s":) // // x'y $s = "x'y" // // The above assignment ops provide perl programmers with an intuitive set of assignment operations for everyday use cases. // Note that initially the user-specified value will appear in the GUI as specified by the user, that is, as the original string because // VS Code doesn't update the GUI immediately. But once the user does a single-step in the debugger the evaluated expression value // will be displayed in the GUI as the GUI updates. let value = args.value.replace(/^\s*/,'').replace(/\s*$/,''); // remove leading and trailing whitespace if any if (!/^'.*'$/.test(value) && value != 'undef' && !/^"\s+"$/.test(value)) { // Single-quoted strings, undef, double-quoted whitespace strings if (value == '' || value == "''" || value == '""') { value = "''"; } // and empty strings are passed through directly else if (/^[ '"]+$/.test(value)) { // Quote trolling empty strings and pass them through:) // There is no real-life need to specify a value string like this one so the user is obviously trying to troll this parser.:) // Or they might just have a very "special" pathological use case.:) // This string might be a malformed quotation mark fest so we replace the outermost quotation mark pair (if any) if (/^'.*'$/.test(value)) { value = value.replace(/^'(.*)'$/,'$1'); } else if (/^".*"$/.test(value)) { value = value.replace(/^"(.*)"$/,'$1'); } // And then we quote the string properly so that it's a properly delimited string and hence it can be assigned to a variable value = "'" + value.replace(/'/g,"\\'") + "'"; } else if (/^\S*\w'\w\S*$/.test(value)) { value = '"' + value + '"'; } // Pass old-style class ref single words of the form a'b'c through else { // because eval() converts them to a::b::c, which we don't want // This is a non-empty value string that's not 'undef' let use_eval = true; let eval_type_prefix = ''; // not needed for scalar types. Only needed for arrays and hashes let eval_type_suffix = ''; if (/^@/.test(variableName) || /^%/.test(variableName)) { if (/^@/.test(value) || /^%/.test(value)) { use_eval = false; } // because it can be directly assigned e.g. @a = @x, %h = %x else { if (/^\{.*\}$/.test(value)) { value = value.replace(/^./,'[').replace(/.$/,']'); } // {expr} -> [expr] else if (!/^\[.*\]$/.test(value) && !/^\(.*\)$/.test(value)) { // if not array (expr) or [expr] value = '[' + value + ']'; // value -> [value] } eval_type_prefix = '@'; // we use arrays internally during evaluation. Even for hashes } } if (use_eval) { if (/^\(.*\)$/.test(value) || /^\{.*\}$/.test(value)) { // value = {expr} or value = (expr) if (/^\{/.test(value)) { eval_type_prefix = '{@'; // to generate a hash ref from the array (ref) after evaluation eval_type_suffix = '}'; } value = value.replace(/^./,'[').replace(/.$/,']'); // (expr)|{expr} -> [expr] } else if (/^@/.test(value)) { value = '[' + value + ']'; } // @a -> [@a] else if (/^%/.test(value)) { value = '[' + value + ']'; // %h -> [%h] eval_type_prefix = '{@'; // to generate a hash ref from the array (ref) after evaluation eval_type_suffix = '}'; } else if (!/^\[.*\]$/.test(value) && !/^{.*}$/.test(value) && /,/.test(value)) { // This might be a list e.g. 1, 2, 3. If it is then we treat it as a simple string and double-quote it let v = value.replace(/(".*?),(.*?")/g,'$1 $2').replace(/('.*?),(.*?')/g,'$1 $2'); // mask commas inside strings // Double-quote it if it looks like a list if (/,/.test(v)) { value = '"' + value.replace(/"/g,'\\"') + '"'; } // 1, 2, 3 -> "1, 2, 3" } // Escape the single-quotes in the value (if any) TWICE for the nested single-quoting in the eval() below value = value.replace(/'/g,"\\\\\\'"); // ' -> \\\' // If it's a valid perl expression then we use the value of the expression otherwise we use the value directly as a string. // This way users can just simply type strings in without having to quote the string in the GUI. So they can just type // expressions or strings in and it will just work in both cases value = "eval('no warnings; " + "my $v = \\'" + value + "\\'; " + // single-quoting to prevent string interpolation at this point "my $r; eval { $r = eval($v) }; " + // check if it's a valid expression and get its value if it is "if (not defined $r) { " + // and if it's not then treat it as a double-quoted string and interpolate "my $qv = $v !~ /^\".*\"$/ ? \\'\"\\'.$v.\\'\"\\' : $v; " + "eval { $r = eval(\"$qv\"); }; " + "} " + "defined($r) ? $r : $v')"; // if all else fails then we just return the original value string as the result if (eval_type_prefix) { // The eval type prefix and suffix are used for type conversion to convert the array ref eval result value = eval_type_prefix + '{' + value + '}' + eval_type_suffix; // to the target type } } } } return this.adapter.request(`${variableName}=${value}`) .then(() => { response.body = { value: args.value, type: variableType(args.value), }; this.sendResponse(response); }); }) .catch((err) => { const [ error = err ] = err.errors || []; this.sendEvent(new OutputEvent(`ERR>setVariableRequest error: ${error.message}\n`)); response.success = false; this.sendResponse(response); }); } /** * Step out */ protected stepOutRequest(response: DebugProtocol.StepOutResponse, args: DebugProtocol.StepOutArguments): void { this.adapter.request('r'); this.sendResponse(response); } /** * Step in */ protected stepInRequest(response: DebugProtocol.StepInResponse, args: DebugProtocol.StepInArguments): void { this.adapter.request('s'); this.sendResponse(response); } /** * Restart */ private async restartRequestAsync(response: DebugProtocol.RestartResponse, args: DebugProtocol.RestartArguments): Promise<DebugProtocol.RestartResponse> { const res = await this.adapter.request('R') if (res.finished) { this.sendEvent(new TerminatedEvent()); } else { this.sendEvent(new StoppedEvent("entry", PerlDebugSession.THREAD_ID)); } return response; } protected restartRequest(response: DebugProtocol.RestartResponse, args: DebugProtocol.RestartArguments): void { this.restartRequestAsync(response, args) .then(res => this.sendResponse(res)) .catch(err => { response.success = false; this.sendResponse(response); }); } /** * Breakpoints */ private async setBreakPointsRequestAsync(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): Promise<DebugProtocol.SetBreakpointsResponse> { const path = args.source.path; const debugPath = await this.adapter.relativePath(path); const editorExisting = this._breakPoints.get(path); const editorBPs: number[] = args.lines.map(ln => ln); const dbp = await this.adapter.getBreakPoints(); const debuggerPBs: number[] = (await this.adapter.getBreakPoints())[debugPath] || []; const createBP: number[] = []; const removeBP: number[] = []; const breakpoints = new Array<Breakpoint>(); // Clean up debugger removing unset bps for (let i = 0; i < debuggerPBs.length; i++) { const ln = debuggerPBs[i]; if (editorBPs.indexOf(ln) < 0) { await this.adapter.clearBreakPoint(ln, debugPath); } } // Add missing bps to the debugger for (let i = 0; i < editorBPs.length; i++) { const ln = editorBPs[i]; if (debuggerPBs.indexOf(ln) < 0) { try { const res = await this.adapter.setBreakPoint(ln, debugPath); const bp = <DebugProtocol.Breakpoint> new Breakpoint(true, ln); bp.id = this._breakpointId++; breakpoints.push(bp); } catch(err) { const bp = <DebugProtocol.Breakpoint> new Breakpoint(false, ln); bp.id = this._breakpointId++; breakpoints.push(bp); } } else { // This is good const bp = <DebugProtocol.Breakpoint> new Breakpoint(true, ln); bp.id = this._breakpointId++; breakpoints.push(bp); } } this._breakPoints.set(path, breakpoints); // send back the actual breakpoint positions response.body = { breakpoints: breakpoints }; return response; } protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void { this.setBreakPointsRequestAsync(response, args) .then(res => this.sendResponse(res)) .catch(err => { response.success = false; this.sendResponse(response) }); } /** * Next */ protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void { this.adapter.request('n'); this.sendResponse(response); } /** * Continue */ protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void { // NOTE(bh): The code for execution control requests like this // one used to delay sending a response and events until there // has been a response from the debugger. That does not make // sense though since we explicitly pass control the debugger, // and it might not return at all until the debuggee terminates. // Instead, responses are sent immediately and events are sent // based on the actual state of the debugger. this.adapter.request('c'); this.sendResponse(response); } /** * Scope request */ protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void { const frameReference = args.frameId; const scopes = new Array<Scope>(); scopes.push(new Scope("Local", this._variableHandles.create("local_" + frameReference), false)); scopes.push(new Scope("Closure", this._variableHandles.create("closure_" + frameReference), false)); scopes.push(new Scope("Global", this._variableHandles.create("global_" + frameReference), true)); response.body = { scopes: scopes }; this.sendResponse(response); } private getVariableName(name: string, variablesReference: number): Promise<string> { let id = this._variableHandles.get(variablesReference); return this.adapter.variableList({ global_0: 0, local_0: 1, closure_0: 2, }) .then(variables => { return resolveVariable(name, id, variables); }); } /** * Variable scope */ protected variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): void { const id = this._variableHandles.get(args.variablesReference); this.adapter.variableList({ global_0: 0, local_0: 1, closure_0: 2, }) .then(variables => { const result = []; if (id != null && variables[id]) { const len = variables[id].length; const result = variables[id].map(variable => { // Convert the parsed variablesReference into Variable complient references if (variable.variablesReference === '0') { variable.variablesReference = 0; } else { variable.variablesReference = this._variableHandles.create(`${variable.variablesReference}`); } return variable; }); response.body = { variables: <Variable[]>result }; this.sendResponse(response); } else { this.sendResponse(response); } }) .catch(() => { response.success = false; this.sendResponse(response); }); } /** * Evaluate hover */ private evaluateHover(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments) { if (/^[\$|\@]/.test(args.expression)) { const expression = args.expression.replace(/\.(\'\w+\'|\w+)/g, (...a) => `->{${a[1]}}`); this.adapter.getExpressionValue(expression) .then(result => { if (/^HASH/.test(result)) { response.body = { result: result, variablesReference: this._variableHandles.create(result), type: 'string' }; } else { response.body = { result: result, variablesReference: 0 }; } this.sendResponse(response); }) .catch(() => { response.body = { result: undefined, variablesReference: 0 }; this.sendResponse(response); }); } else { this.sendResponse(response); } } /** * Evaluate command line */ private evaluateCommandLine(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments) { this.adapter.request(args.expression) .then((res) => { if (res.data.length > 1) { res.data.forEach((line) => { this.sendEvent(new OutputEvent(`> ${line}\n`)); }); response.body = { result: `Result:`, variablesReference: 0, }; } else { response.body = { result: `${res.data[0]}`, variablesReference: 0 }; } this.sendResponse(response); }); }; /** * Fetch expression value */ async fetchExpressionRequest(clientExpression): Promise<any> { const isVariable = /^([\$|@|%])([a-zA-Z0-9_\'\.]+)$/.test(clientExpression); const expression = isVariable ? clientExpression.replace(/\.(\'\w+\'|\w+)/g, (...a) => `->{${a[1]}}`) : clientExpression; let value = await this.adapter.getExpressionValue(expression); if (/^Can\'t use an undefined value as a HASH reference/.test(value)) { value = undefined; } const reference = isVariable ? await this.adapter.getVariableReference(expression) : null; if (typeof value !== 'undefined' && /^HASH|ARRAY/.test(reference)) { return { value: reference, reference: reference, }; } return { value: value, reference: null, }; } /** * Evaluate watch * Note: We don't actually levarage the debugger watch capabilities yet */ protected evaluateWatch(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void { // Clear watch if last request wasn't setting a watch? this.fetchExpressionRequest(args.expression) .then(result => { // this.sendEvent(new OutputEvent(`${args.expression}=${result.value} ${typeof result.value} ${result.reference}$')\n`)); if (typeof result.value !== 'undefined') { response.body = { result: result.value, variablesReference: result.reference === null ? 0 : this._variableHandles.create(result.reference), }; } this.sendResponse(response); }) .catch(() => {}); } /** * Evaluate */ protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void { if (args.context === 'repl') { this.evaluateCommandLine(response, args); } else if (args.context === 'hover') { this.evaluateHover(response, args); } else if (args.context === 'watch') { this.evaluateWatch(response, args); } else { this.sendEvent(new OutputEvent(`evaluate(context: '${args.context}', '${args.expression}')`)); response.body = { result: `evaluate(context: '${args.context}', '${args.expression}')`, variablesReference: 0 }; this.sendResponse(response); } } /** * Stacktrace */ private async stackTraceRequestAsync(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): Promise<DebugProtocol.StackTraceResponse> { // TODO(bh): Maybe re-set the function breakpoints from here, if // there are any newly loaded sources there most probably are new // functions, and we might be trying to break on one of them... const stacktrace = await this.adapter.getStackTrace(); const frames = new Array<StackFrame>(); // In case this is a trace run on end, we want to return the file with the exception in the @ position let endFrame = null; stacktrace.forEach((trace, i) => { const frame = new StackFrame(i, `${trace.caller}`, new Source(basename(trace.filename), this.convertDebuggerPathToClient(trace.filename)), trace.ln, 0); frames.push(frame); if (trace.caller === 'DB::END()') { endFrame = frame; } }); if (endFrame) { frames.unshift(endFrame); } response.body = { stackFrames: frames, totalFrames: frames.length }; return response; } protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void { this.stackTraceRequestAsync(response, args) .then(res => this.sendResponse(res)) .catch(err => { const [ error = err ] = err.errors || []; this.sendEvent(new OutputEvent(`--->Trace error...${error.message}\n`)); response.success = false; response.body = { stackFrames: [], totalFrames: 0 }; this.sendResponse(response); }); } private async loadedSourcesRequestAsync(response: DebugProtocol.LoadedSourcesResponse, args: DebugProtocol.LoadedSourcesArguments): Promise<DebugProtocol.LoadedSourcesResponse> { const loadedFiles = await this.adapter.getLoadedFiles(); const newFiles = loadedFiles.filter( x => !this._loadedSources.has(x) ); for (const file of newFiles) { const newSource = new Source( file, file, // no sourceReference when debugging locally, so vscode will // open the local file rather than retrieving a read-only // version of the code through the debugger (that lacks code // past `__END__` markers, among possibly other limitations). this.adapter.canSignalDebugger ? 0 : this._loadedSources.size ); this.sendEvent(new LoadedSourceEvent("new", newSource)); this._loadedSources.set(file, newSource); } response.body = { sources: [...this._loadedSources.values()] }; return response; } protected loadedSourcesRequest(response: DebugProtocol.LoadedSourcesResponse, args: DebugProtocol.LoadedSourcesArguments) { this.loadedSourcesRequestAsync(response, args) .then(res => this.sendResponse(res)) .catch(err => { const [ error = err ] = err.errors || []; this.sendEvent(new OutputEvent(`--->Loaded sources request error...${error.message}\n`)); response.success = false; response.body = { sources: [ ] }; this.sendResponse(response); }); } private async sourceRequestAsync(response: DebugProtocol.SourceResponse, args: DebugProtocol.SourceArguments): Promise<DebugProtocol.SourceResponse> { // NOTE(bh): When sources reported by `loadedSources` have some // non-zero `sourceReference` specified, Visual Studio Code will // ask us for the source code, otherwise it interprets the `path` // as a local file. Our `loadedSources` takes the paths from the // Perl debugger, and `sourceReference` is just a counter value. // Accordingly there is no point for us to distinguish the cases. if (args.source && args.source.sourceReference) { // retrieve by source reference } else { // retrieve by path } response.body = { content: await this.adapter.getSourceCode( args.source.path ) }; return response; } protected sourceRequest(response: DebugProtocol.SourceResponse, args: DebugProtocol.SourceArguments) { this.sourceRequestAsync(response, args) .then(res => this.sendResponse(res)) .catch(err => { const [ error = err ] = err.errors || []; this.sendEvent(new OutputEvent(`--->Source request error...${error.message}\n`)); response.success = false; response.body = { content: `# error`, mimeType: `text/vnd.vscode-perl-debug.error`, }; this.sendResponse(response); }); } // Custom requests protected customRequestx(command: string, response: DebugProtocol.Response, args: any) { if (command === '...') { // this....(response, args); } response.success = false; } }
the_stack
import { combineLatest as observableCombineLatest, Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { RemoteData } from '../data/remote-data'; import { PaginatedList } from '../data/paginated-list.model'; import { FindListOptions } from '../data/request.models'; import { hasValue, hasValueOperator, isNotEmptyOperator } from '../../shared/empty.util'; import { getFirstSucceededRemoteDataPayload } from '../shared/operators'; import { createSelector, select, Store } from '@ngrx/store'; import { AppState } from '../../app.reducer'; import { MetadataRegistryState } from '../../admin/admin-registries/metadata-registry/metadata-registry.reducers'; import { MetadataRegistryCancelFieldAction, MetadataRegistryCancelSchemaAction, MetadataRegistryDeselectAllFieldAction, MetadataRegistryDeselectAllSchemaAction, MetadataRegistryDeselectFieldAction, MetadataRegistryDeselectSchemaAction, MetadataRegistryEditFieldAction, MetadataRegistryEditSchemaAction, MetadataRegistrySelectFieldAction, MetadataRegistrySelectSchemaAction } from '../../admin/admin-registries/metadata-registry/metadata-registry.actions'; import { map, mergeMap, tap } from 'rxjs/operators'; import { NotificationsService } from '../../shared/notifications/notifications.service'; import { TranslateService } from '@ngx-translate/core'; import { MetadataSchema } from '../metadata/metadata-schema.model'; import { MetadataField } from '../metadata/metadata-field.model'; import { MetadataSchemaDataService } from '../data/metadata-schema-data.service'; import { MetadataFieldDataService } from '../data/metadata-field-data.service'; import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; import { RequestParam } from '../cache/models/request-param.model'; import { NoContent } from '../shared/NoContent.model'; const metadataRegistryStateSelector = (state: AppState) => state.metadataRegistry; const editMetadataSchemaSelector = createSelector(metadataRegistryStateSelector, (metadataState: MetadataRegistryState) => metadataState.editSchema); const selectedMetadataSchemasSelector = createSelector(metadataRegistryStateSelector, (metadataState: MetadataRegistryState) => metadataState.selectedSchemas); const editMetadataFieldSelector = createSelector(metadataRegistryStateSelector, (metadataState: MetadataRegistryState) => metadataState.editField); const selectedMetadataFieldsSelector = createSelector(metadataRegistryStateSelector, (metadataState: MetadataRegistryState) => metadataState.selectedFields); /** * Service for registry related CRUD actions such as metadata schema, metadata field and bitstream format */ @Injectable() export class RegistryService { constructor(private store: Store<AppState>, private notificationsService: NotificationsService, private translateService: TranslateService, private metadataSchemaService: MetadataSchemaDataService, private metadataFieldService: MetadataFieldDataService) { } /** * Retrieves all metadata schemas * @param options The options used to retrieve the schemas * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved */ public getMetadataSchemas(options: FindListOptions = {}, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<MetadataSchema>[]): Observable<RemoteData<PaginatedList<MetadataSchema>>> { return this.metadataSchemaService.findAll(options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } /** * Retrieves a metadata schema by its prefix * @param prefix The prefux of the schema to find * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved */ public getMetadataSchemaByPrefix(prefix: string, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<MetadataSchema>[]): Observable<RemoteData<MetadataSchema>> { // Temporary options to get ALL metadataschemas until there's a rest api endpoint for fetching a specific schema const options: FindListOptions = Object.assign(new FindListOptions(), { elementsPerPage: 10000 }); return this.getMetadataSchemas(options).pipe( getFirstSucceededRemoteDataPayload(), map((schemas: PaginatedList<MetadataSchema>) => schemas.page), isNotEmptyOperator(), map((schemas: MetadataSchema[]) => schemas.filter((schema) => schema.prefix === prefix)[0]), mergeMap((schema: MetadataSchema) => this.metadataSchemaService.findById(`${schema.id}`, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow)) ); } /** * retrieves all metadata fields that belong to a certain metadata schema * @param schema The schema to filter by * @param options The options info used to retrieve the fields * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved */ public getMetadataFieldsBySchema(schema: MetadataSchema, options: FindListOptions = {}, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<MetadataField>[]): Observable<RemoteData<PaginatedList<MetadataField>>> { return this.metadataFieldService.findBySchema(schema, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } public editMetadataSchema(schema: MetadataSchema) { this.store.dispatch(new MetadataRegistryEditSchemaAction(schema)); } /** * Method to cancel editing a metadata schema, dispatches a cancel schema action */ public cancelEditMetadataSchema() { this.store.dispatch(new MetadataRegistryCancelSchemaAction()); } /** * Method to retrieve the metadata schema that are currently being edited */ public getActiveMetadataSchema(): Observable<MetadataSchema> { return this.store.pipe(select(editMetadataSchemaSelector)); } /** * Method to select a metadata schema, dispatches a select schema action * @param schema The schema that's being selected */ public selectMetadataSchema(schema: MetadataSchema) { this.store.dispatch(new MetadataRegistrySelectSchemaAction(schema)); } /** * Method to deselect a metadata schema, dispatches a deselect schema action * @param schema The schema that's it being deselected */ public deselectMetadataSchema(schema: MetadataSchema) { this.store.dispatch(new MetadataRegistryDeselectSchemaAction(schema)); } /** * Method to deselect all currently selected metadata schema, dispatches a deselect all schema action */ public deselectAllMetadataSchema() { this.store.dispatch(new MetadataRegistryDeselectAllSchemaAction()); } /** * Method to retrieve the metadata schemas that are currently selected */ public getSelectedMetadataSchemas(): Observable<MetadataSchema[]> { return this.store.pipe(select(selectedMetadataSchemasSelector)); } /** * Method to start editing a metadata field, dispatches an edit field action * @param field The field that's being edited */ public editMetadataField(field: MetadataField) { this.store.dispatch(new MetadataRegistryEditFieldAction(field)); } /** * Method to cancel editing a metadata field, dispatches a cancel field action */ public cancelEditMetadataField() { this.store.dispatch(new MetadataRegistryCancelFieldAction()); } /** * Method to retrieve the metadata field that are currently being edited */ public getActiveMetadataField(): Observable<MetadataField> { return this.store.pipe(select(editMetadataFieldSelector)); } /** * Method to select a metadata field, dispatches a select field action * @param field The field that's being selected */ public selectMetadataField(field: MetadataField) { this.store.dispatch(new MetadataRegistrySelectFieldAction(field)); } /** * Method to deselect a metadata field, dispatches a deselect field action * @param field The field that's it being deselected */ public deselectMetadataField(field: MetadataField) { this.store.dispatch(new MetadataRegistryDeselectFieldAction(field)); } /** * Method to deselect all currently selected metadata fields, dispatches a deselect all field action */ public deselectAllMetadataField() { this.store.dispatch(new MetadataRegistryDeselectAllFieldAction()); } /** * Method to retrieve the metadata fields that are currently selected */ public getSelectedMetadataFields(): Observable<MetadataField[]> { return this.store.pipe(select(selectedMetadataFieldsSelector)); } /** * Create or Update a MetadataSchema * If the MetadataSchema contains an id, it is assumed the schema already exists and is updated instead * Since creating or updating is nearly identical, the only real difference is the request (and slight difference in endpoint): * - On creation, a CreateRequest is used * - On update, a PutRequest is used * @param schema The MetadataSchema to create or update */ public createOrUpdateMetadataSchema(schema: MetadataSchema): Observable<MetadataSchema> { const isUpdate = hasValue(schema.id); return this.metadataSchemaService.createOrUpdateMetadataSchema(schema).pipe( getFirstSucceededRemoteDataPayload(), hasValueOperator(), tap(() => { this.showNotifications(true, isUpdate, false, { prefix: schema.prefix }); }) ); } /** * Method to delete a metadata schema * @param id The id of the metadata schema to delete */ public deleteMetadataSchema(id: number): Observable<RemoteData<NoContent>> { return this.metadataSchemaService.delete(`${id}`); } /** * Method that clears a cached metadata schema request and returns its REST url */ public clearMetadataSchemaRequests(): Observable<string> { return this.metadataSchemaService.clearRequests(); } /** * Create a MetadataField * * @param field The MetadataField to create * @param schema The MetadataSchema to create the field in */ public createMetadataField(field: MetadataField, schema: MetadataSchema): Observable<MetadataField> { if (!field.qualifier) { field.qualifier = null; } return this.metadataFieldService.create(field, new RequestParam('schemaId', schema.id)).pipe( getFirstSucceededRemoteDataPayload(), hasValueOperator(), tap(() => { this.showNotifications(true, false, true, { field: field.toString() }); }) ); } /** * Update a MetadataField * * @param field The MetadataField to update */ public updateMetadataField(field: MetadataField): Observable<MetadataField> { if (!field.qualifier) { field.qualifier = null; } return this.metadataFieldService.put(field).pipe( getFirstSucceededRemoteDataPayload(), hasValueOperator(), tap(() => { this.showNotifications(true, true, true, { field: field.toString() }); }) ); } /** * Method to delete a metadata field * @param id The id of the metadata field to delete */ public deleteMetadataField(id: number): Observable<RemoteData<NoContent>> { return this.metadataFieldService.delete(`${id}`); } /** * Method that clears a cached metadata field request and returns its REST url */ public clearMetadataFieldRequests(): void { this.metadataFieldService.clearRequests(); } private showNotifications(success: boolean, edited: boolean, isField: boolean, options: any) { const prefix = 'admin.registries.schema.notification'; const suffix = success ? 'success' : 'failure'; const editedString = edited ? 'edited' : 'created'; const messages = observableCombineLatest( this.translateService.get(success ? `${prefix}.${suffix}` : `${prefix}.${suffix}`), this.translateService.get(`${prefix}${isField ? '.field' : ''}.${editedString}`, options) ); messages.subscribe(([head, content]) => { if (success) { this.notificationsService.success(head, content); } else { this.notificationsService.error(head, content); } }); } /** * Retrieve a filtered paginated list of metadata fields * @param query {string} The query to use for the metadata field name, can be part of * the fully qualified field, should start with the start of * the schema, element or qualifier (e.g. “dc.ti”, * “contributor”, “auth”, “contributor.ot”) * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's * no valid cached version. Defaults to true * @param reRequestOnStale Whether or not the request should automatically be re- * requested after the response becomes stale * @param linksToFollow List of {@link FollowLinkConfig} that indicate which * {@link HALLink}s should be automatically resolved * @returns an observable that emits a remote data object with a page of metadata fields that match the query */ queryMetadataFields(query: string, options: FindListOptions = {}, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<MetadataField>[]): Observable<RemoteData<PaginatedList<MetadataField>>> { return this.metadataFieldService.searchByFieldNameParams(null, null, null, query, null, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); } }
the_stack
import type { Type } from "@sdkgen/parser"; import { ArrayType, Base64PrimitiveType, BigIntPrimitiveType, BoolPrimitiveType, BytesPrimitiveType, CnpjPrimitiveType, CpfPrimitiveType, DatePrimitiveType, DateTimePrimitiveType, EmailPrimitiveType, EnumType, FloatPrimitiveType, HexPrimitiveType, HtmlPrimitiveType, IntPrimitiveType, JsonPrimitiveType, MoneyPrimitiveType, OptionalType, StringPrimitiveType, StructType, TypeReference, UIntPrimitiveType, UrlPrimitiveType, UuidPrimitiveType, VoidPrimitiveType, XmlPrimitiveType, } from "@sdkgen/parser"; const reservedWords = [ "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "using", "static", "virtual", "void", "volatile", "while", ]; const typesWithNativeNullable: Function[] = [ StringPrimitiveType, HtmlPrimitiveType, CpfPrimitiveType, CnpjPrimitiveType, BytesPrimitiveType, EmailPrimitiveType, UrlPrimitiveType, UuidPrimitiveType, HexPrimitiveType, Base64PrimitiveType, XmlPrimitiveType, StructType, ArrayType, ]; const needsTempVarForNullable: Function[] = [ BigIntPrimitiveType, DatePrimitiveType, DateTimePrimitiveType, FloatPrimitiveType, IntPrimitiveType, MoneyPrimitiveType, UIntPrimitiveType, ]; export function ident(name: string): string { return reservedWords.includes(name) ? `@${name}` : name; } export function capitalize(name: string): string { return name[0].toUpperCase() + name.slice(1); } export function generateTypeName(type: Type): string { switch (type.constructor) { case StringPrimitiveType: return "string"; case IntPrimitiveType: return "int"; case UIntPrimitiveType: return "uint"; case FloatPrimitiveType: return "double"; case BigIntPrimitiveType: return "BigInteger"; case DatePrimitiveType: case DateTimePrimitiveType: return "DateTime"; case BoolPrimitiveType: return "bool"; case BytesPrimitiveType: return "byte[]"; case MoneyPrimitiveType: return "decimal"; case CpfPrimitiveType: case CnpjPrimitiveType: case EmailPrimitiveType: case HtmlPrimitiveType: case UrlPrimitiveType: case UuidPrimitiveType: case HexPrimitiveType: case Base64PrimitiveType: case XmlPrimitiveType: return "string"; case VoidPrimitiveType: return "void"; case JsonPrimitiveType: return "JsonElement"; case OptionalType: return `${generateTypeName((type as OptionalType).base)}?`; case ArrayType: return `List<${generateTypeName((type as ArrayType).base)}>`; case StructType: return type.name; case EnumType: return type.name; case TypeReference: return generateTypeName((type as TypeReference).type); default: throw new Error(`BUG: generateTypeName with ${type.constructor.name}`); } } export function decodeType(type: Type, jsonElementVar: string, path: string, targetVar: string, suffix = 1, maybeNull = true): string { switch (type.constructor) { case IntPrimitiveType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.Number || !${jsonElementVar}.TryGetInt32(out ${targetVar})) { throw new FatalException($"'{${path}}' must be an integer"); } ` .replace(/\n {16}/gu, "\n") .trim(); } case UIntPrimitiveType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.Number || !${jsonElementVar}.TryGetUInt32(out ${targetVar})) { throw new FatalException($"'{${path}}' must be an unsigned integer."); } ` .replace(/\n {16}/gu, "\n") .trim(); } case MoneyPrimitiveType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.Number || !${jsonElementVar}.TryGetDecimal(out ${targetVar}) || ${targetVar} % 1 != 0) { throw new FatalException($"'{${path}}' must be an integer amount of cents."); } ${targetVar} /= 100; ` .replace(/\n {16}/gu, "\n") .trim(); } case FloatPrimitiveType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.Number || !${jsonElementVar}.TryGetDouble(out ${targetVar})) { throw new FatalException($"'{${path}}' must be a floating-point number."); } ` .replace(/\n {16}/gu, "\n") .trim(); } case BigIntPrimitiveType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String || !BigInteger.TryParse(${jsonElementVar}.GetString(), out ${targetVar})) { throw new FatalException($"'{${path}}' must be an arbitrarily large integer in a string."); } ` .replace(/\n {16}/gu, "\n") .trim(); } case StringPrimitiveType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a string."); } ${targetVar} = ${jsonElementVar}.GetString(); ` .replace(/\n {16}/gu, "\n") .trim(); } case HtmlPrimitiveType: { // TODO: validate HTML return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a valid HTML string."); } ${targetVar} = ${jsonElementVar}.GetString(); ` .replace(/\n {16}/gu, "\n") .trim(); } case CpfPrimitiveType: { // TODO: validate CPF return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a valid CPF string."); } ${targetVar} = ${jsonElementVar}.GetString(); ` .replace(/\n {16}/gu, "\n") .trim(); } case CnpjPrimitiveType: { // TODO: validate CNPJ return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a valid CNPJ string."); } ${targetVar} = ${jsonElementVar}.GetString(); ` .replace(/\n {16}/gu, "\n") .trim(); } case EmailPrimitiveType: { // TODO: validate Email return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a valid email."); } ${targetVar} = ${jsonElementVar}.GetString(); ` .replace(/\n {16}/gu, "\n") .trim(); } case UrlPrimitiveType: { // TODO: validate URL return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a valid URL string."); } ${targetVar} = ${jsonElementVar}.GetString(); ` .replace(/\n {16}/gu, "\n") .trim(); } case UuidPrimitiveType: { // TODO: validate UUID return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a valid UUID."); } ${targetVar} = ${jsonElementVar}.GetString(); ` .replace(/\n {16}/gu, "\n") .trim(); } case HexPrimitiveType: { // TODO: validate Hex return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a valid hex string."); } ${targetVar} = ${jsonElementVar}.GetString(); ` .replace(/\n {16}/gu, "\n") .trim(); } case Base64PrimitiveType: { // TODO: validate Base64 return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a base64 string."); } ${targetVar} = ${jsonElementVar}.GetString(); ` .replace(/\n {16}/gu, "\n") .trim(); } case XmlPrimitiveType: { // TODO: validate XML return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a XML string."); } ${targetVar} = ${jsonElementVar}.GetString(); ` .replace(/\n {16}/gu, "\n") .trim(); } case BoolPrimitiveType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.True && ${jsonElementVar}.ValueKind != JsonValueKind.False) { throw new FatalException($"'{${path}}' must be either true or false."); } ${targetVar} = ${jsonElementVar}.GetBoolean(); ` .replace(/\n {16}/gu, "\n") .trim(); } case BytesPrimitiveType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String) { throw new FatalException($"'{${path}}' must be a string."); } try { ${targetVar} = Convert.FromBase64String(${jsonElementVar}.GetString()); } catch (FormatException) { throw new FatalException($"'{${path}}' must be a base64 string."); } ` .replace(/\n {16}/gu, "\n") .trim(); } case TypeReference: return decodeType((type as TypeReference).type, jsonElementVar, path, targetVar, suffix); case OptionalType: if (needsTempVarForNullable.includes((type as OptionalType).base.constructor)) { const tempVar = `${targetVar.replace(/[^0-9a-zA-Z]/gu, "")}Tmp`; return ` if (${jsonElementVar}.ValueKind == JsonValueKind.Null || ${jsonElementVar}.ValueKind == JsonValueKind.Undefined) { ${targetVar} = null; } else { ${generateTypeName((type as OptionalType).base)} ${tempVar}; ${decodeType((type as OptionalType).base, jsonElementVar, path, tempVar, suffix, false).replace( /\n/gu, "\n ", )} ${targetVar} = ${tempVar}; } ` .replace(/\n {20}/gu, "\n") .trim(); } return ` if (${jsonElementVar}.ValueKind == JsonValueKind.Null || ${jsonElementVar}.ValueKind == JsonValueKind.Undefined) { ${targetVar} = null; } else { ${decodeType((type as OptionalType).base, jsonElementVar, path, targetVar, suffix, false).replace( /\n/gu, "\n ", )} } ` .replace(/\n {20}/gu, "\n") .trim(); case EnumType: case StructType: return `${targetVar} = Decode${type.name}(${jsonElementVar}, ${path});`; case JsonPrimitiveType: if (maybeNull) { return ` if (${jsonElementVar}.ValueKind == JsonValueKind.Null || ${jsonElementVar}.ValueKind == JsonValueKind.Undefined) { throw new FatalException($"'{${path}}' can't be null."); } ${targetVar} = ${jsonElementVar}; ` .replace(/\n {16}/gu, "\n") .trim(); } return `${targetVar} = ${jsonElementVar};`; case DateTimePrimitiveType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String || !(DateTime.TryParseExact(${jsonElementVar}.GetString(), "yyyy-MM-ddTHH:mm:ss.FFFFFFF", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out ${targetVar}) || DateTime.TryParseExact(${jsonElementVar}.GetString(), "yyyy-MM-ddTHH:mm:ss.FFFFFFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out ${targetVar}))) { throw new FatalException($"'{${path}}' must be a datetime."); } ` .replace(/\n {16}/gu, "\n") .trim(); } case DatePrimitiveType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.String || !(DateTime.TryParseExact(${jsonElementVar}.GetString(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out ${targetVar}))) { throw new FatalException($"'{${path}}' must be a date."); } ` .replace(/\n {16}/gu, "\n") .trim(); } case ArrayType: { return ` if (${jsonElementVar}.ValueKind != JsonValueKind.Array) { throw new FatalException($"'{${path}}' must be a date."); } ${targetVar} = new ${generateTypeName(type)}(); for (var i${suffix} = 0; i${suffix} < ${jsonElementVar}.GetArrayLength(); ++i${suffix}) { ${generateTypeName((type as ArrayType).base)} element${suffix}; ${decodeType( (type as ArrayType).base, `${jsonElementVar}[i${suffix}]`, `$"{${path}}[{i${suffix}}]"`, `element${suffix}`, suffix + 1, ).replace(/\n/gu, "\n ")} ${targetVar}.Add(element${suffix}); } ` .replace(/\n {16}/gu, "\n") .trim(); } default: throw new Error(`BUG: decodeType with ${type.constructor.name}`); } } export function encodeType(type: Type, valueVar: string, path: string, suffix = 1): string { switch (type.constructor) { case StringPrimitiveType: { return `resultWriter_.WriteStringValue(${valueVar});`; } case FloatPrimitiveType: case UIntPrimitiveType: case IntPrimitiveType: { return `resultWriter_.WriteNumberValue(${valueVar});`; } case MoneyPrimitiveType: { return `resultWriter_.WriteNumberValue(Math.Round(${valueVar} * 100));`; } case BigIntPrimitiveType: { return `resultWriter_.WriteStringValue(${valueVar}.ToString());`; } case BoolPrimitiveType: { return `resultWriter_.WriteBooleanValue(${valueVar});`; } case BytesPrimitiveType: { return `resultWriter_.WriteStringValue(Convert.ToBase64String(${valueVar}));`; } case DateTimePrimitiveType: { return `resultWriter_.WriteStringValue(${valueVar}.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFF'Z'"));`; } case DatePrimitiveType: { return `resultWriter_.WriteStringValue(${valueVar}.ToString("yyyy-MM-dd"));`; } // TODO: format those case CpfPrimitiveType: case CnpjPrimitiveType: case EmailPrimitiveType: case HtmlPrimitiveType: case UrlPrimitiveType: case UuidPrimitiveType: case Base64PrimitiveType: case HexPrimitiveType: case XmlPrimitiveType: { return `resultWriter_.WriteStringValue(${valueVar});`; } case OptionalType: { let realBaseType = (type as OptionalType).base; while (realBaseType instanceof TypeReference) { realBaseType = realBaseType.type; } return ` if (${valueVar} == null) { resultWriter_.WriteNullValue(); } else { ${encodeType( realBaseType, typesWithNativeNullable.includes(realBaseType.constructor) ? valueVar : `${valueVar}.Value`, path, suffix, ).replace(/\n/gu, "\n ")} }` .replace(/\n {16}/gu, "\n") .trim(); } case TypeReference: return encodeType((type as TypeReference).type, valueVar, path, suffix); case EnumType: case StructType: return `Encode${type.name}(${valueVar}, resultWriter_, ${path});`; case JsonPrimitiveType: return `${valueVar}.WriteTo(resultWriter_);`; case ArrayType: { return ` resultWriter_.WriteStartArray(); for (var i${suffix} = 0; i${suffix} < ${valueVar}.Count; ++i${suffix}) { ${encodeType((type as ArrayType).base, `${valueVar}[i${suffix}]`, `$"{${path}}[{i${suffix}}]"`, suffix + 1).replace( /\n/gu, "\n ", )} } resultWriter_.WriteEndArray(); ` .replace(/\n {16}/gu, "\n") .trim(); } default: throw new Error(`BUG: encodeType with ${type.constructor.name}`); } } export function generateStruct(struct: StructType): string { return ` public class ${struct.name} {${struct.fields .map( field => ` public ${generateTypeName(field.type)} ${capitalize(field.name)};`, ) .join("")} public ${struct.name}(${struct.fields.map(field => `${generateTypeName(field.type)} ${ident(field.name)}`).join(", ")}) {${struct.fields .map( field => ` ${capitalize(field.name)} = ${ident(field.name)};`, ) .join("")} } } ${struct.name} Decode${struct.name}(JsonElement json_, string path_) { if (json_.ValueKind != JsonValueKind.Object) { throw new FatalException($"'{path_}' must be an object."); }\n${struct.fields .map( field => ` JsonElement ${field.name}Json_; if (!json_.TryGetProperty(${JSON.stringify(field.name)}, out ${field.name}Json_)) { ${ field.type instanceof OptionalType ? `${field.name}Json_ = new JsonElement();` : `throw new FatalException($"'{path_}.${field.name}' must be set to a value of type ${field.type.name}.");` } } ${generateTypeName(field.type)} ${ident(field.name)}; ${decodeType(field.type, `${field.name}Json_`, `$"{path_}.${field.name}"`, ident(field.name)).replace(/\n/gu, "\n ")}`, ) .join("\n")} return new ${struct.name}(${struct.fields.map(field => ident(field.name)).join(", ")}); } void Encode${struct.name}(${struct.name} obj_, Utf8JsonWriter resultWriter_, string path_) { resultWriter_.WriteStartObject(); ${struct.fields .map( field => `resultWriter_.WritePropertyName(${JSON.stringify(field.name)}); ${encodeType(field.type, `obj_.${capitalize(field.name)}`, `$"{path_}.${field.name}"`).replace(/\n/gu, "\n ")}`, ) .join("\n ")} resultWriter_.WriteEndObject(); } `; } export function generateEnum(type: EnumType): string { return ` public enum ${type.name} {${type.values .map( ({ value }) => ` ${capitalize(value)}`, ) .join(",\n ")} } ${type.name} Decode${type.name}(JsonElement json_, string path_) { if (json_.ValueKind != JsonValueKind.String) { throw new FatalException($"'{path_}' must be a string."); } var value = json_.GetString();${type.values .map( ({ value }) => ` if (value == "${value}") { return ${type.name}.${capitalize(value)}; }`, ) .join("")} throw new FatalException($"'{path_}' must be one of: (${type.values.map(({ value }) => `'${value}'`).join(", ")})."); } void Encode${type.name}(${type.name} obj_, Utf8JsonWriter resultWriter_, string path_) {${type.values .map( ({ value }) => ` if (obj_ == ${type.name}.${capitalize(value)}) { resultWriter_.WriteStringValue("${value}"); }`, ) .join("")} } `; }
the_stack
import React from 'react' import {render} from '../utils/testing' import {render as HTMLRender, fireEvent} from '@testing-library/react' import {toHaveNoViolations} from 'jest-axe' import 'babel-polyfill' import Autocomplete, {AutocompleteInputProps} from '../Autocomplete' import {SSRProvider} from '../index' import theme from '../theme' import BaseStyles from '../BaseStyles' import {ThemeProvider} from '../ThemeProvider' import userEvent from '@testing-library/user-event' import {AutocompleteMenuInternalProps} from '../Autocomplete/AutocompleteMenu' import {ItemProps} from '../ActionList' import {MandateProps} from '../utils/types' expect.extend(toHaveNoViolations) const mockItems = [ {text: 'zero', id: 0}, {text: 'one', id: 1}, {text: 'two', id: 2}, {text: 'three', id: 3}, {text: 'four', id: 4}, {text: 'five', id: 5}, {text: 'six', id: 6}, {text: 'seven', id: 7}, {text: 'twenty', id: 20}, {text: 'twentyone', id: 21} ] // eslint-disable-next-line @typescript-eslint/no-explicit-any type AutocompleteItemProps<T = Record<string, any>> = MandateProps<ItemProps, 'id'> & {metadata?: T} const AUTOCOMPLETE_LABEL = 'Autocomplete field' const LabelledAutocomplete = <T extends AutocompleteItemProps>({ inputProps = {}, menuProps }: { inputProps?: AutocompleteInputProps menuProps: AutocompleteMenuInternalProps<T> }) => { const {['aria-labelledby']: ariaLabelledBy = 'autocompleteLabel', ...menuPropsRest} = menuProps const {id = 'autocompleteInput', ...inputPropsRest} = inputProps return ( <ThemeProvider theme={theme}> <SSRProvider> <BaseStyles> {/* eslint-disable-next-line jsx-a11y/label-has-for */} <label htmlFor={id} id={ariaLabelledBy}> Autocomplete field </label> <Autocomplete id="autocompleteId"> <Autocomplete.Input id={id} {...inputPropsRest} /> <Autocomplete.Overlay> <Autocomplete.Menu aria-labelledby={ariaLabelledBy} {...menuPropsRest} /> </Autocomplete.Overlay> </Autocomplete> </BaseStyles> </SSRProvider> </ThemeProvider> ) } describe('Autocomplete', () => { describe('snapshots', () => { it('renders a single select input', () => { expect( render( <SSRProvider> <Autocomplete id="autocompleteId"> <Autocomplete.Input /> <Autocomplete.Menu aria-labelledby="labelId" items={mockItems} selectedItemIds={[]} /> </Autocomplete> </SSRProvider> ) ).toMatchSnapshot() }) it('renders a multiselect input', () => { expect( render( <SSRProvider> <Autocomplete id="autocompleteId"> <Autocomplete.Input /> <Autocomplete.Menu aria-labelledby="labelId" items={mockItems} selectedItemIds={[]} selectionVariant="multiple" /> </Autocomplete> </SSRProvider> ) ).toMatchSnapshot() }) it('renders a multiselect input with selected menu items', () => { expect( render( <SSRProvider> <Autocomplete id="autocompleteId"> <Autocomplete.Input /> <Autocomplete.Menu aria-labelledby="labelId" items={mockItems} selectedItemIds={[0, 1, 2]} selectionVariant="multiple" /> </Autocomplete> </SSRProvider> ) ).toMatchSnapshot() }) it('renders a menu that contains an item to add to the menu', () => { const handleAddItemMock = jest.fn() expect( render( <SSRProvider> <Autocomplete id="autocompleteId"> <Autocomplete.Input /> <Autocomplete.Menu aria-labelledby="labelId" items={mockItems} selectionVariant="multiple" selectedItemIds={[]} addNewItem={{ text: 'Add new item', handleAddItem: handleAddItemMock }} /> </Autocomplete> </SSRProvider> ) ).toMatchSnapshot() }) it('renders a custom empty state message', () => { expect( render( <SSRProvider> <Autocomplete id="autocompleteId"> <Autocomplete.Input /> <Autocomplete.Menu aria-labelledby="labelId" items={[]} selectedItemIds={[]} emptyStateText="No results" /> </Autocomplete> </SSRProvider> ) ).toMatchSnapshot() }) it('renders a loading state', () => { expect( render( <SSRProvider> <Autocomplete id="autocompleteId"> <Autocomplete.Input /> <Autocomplete.Menu aria-labelledby="labelId" loading items={[]} selectedItemIds={[]} /> </Autocomplete> </SSRProvider> ) ).toMatchSnapshot() }) it('renders with a custom text input component', () => { expect( render( <SSRProvider> <Autocomplete id="autocompleteId"> <Autocomplete.Input as={() => <input type="text" id="customInput" />} /> <Autocomplete.Menu aria-labelledby="labelId" items={mockItems} selectedItemIds={[]} /> </Autocomplete> </SSRProvider> ) ).toMatchSnapshot() }) it('renders with an input value', () => { expect( render( <SSRProvider> <Autocomplete id="autocompleteId"> <Autocomplete.Input value="test" /> <Autocomplete.Menu aria-labelledby="labelId" items={mockItems} selectedItemIds={[]} /> </Autocomplete> </SSRProvider> ) ).toMatchSnapshot() }) }) describe('Autocomplete.Input', () => { it('calls onChange', () => { const onChangeMock = jest.fn() const {container} = HTMLRender( <LabelledAutocomplete inputProps={{onChange: onChangeMock}} menuProps={{items: mockItems, selectedItemIds: []}} /> ) const inputNode = container.querySelector('#autocompleteInput') expect(onChangeMock).not.toHaveBeenCalled() inputNode && userEvent.type(inputNode, 'z') expect(onChangeMock).toHaveBeenCalled() }) it('calls onFocus', () => { const onFocusMock = jest.fn() const {container} = HTMLRender( <LabelledAutocomplete inputProps={{onFocus: onFocusMock}} menuProps={{items: mockItems, selectedItemIds: []}} /> ) const inputNode = container.querySelector('#autocompleteInput') expect(onFocusMock).not.toHaveBeenCalled() inputNode && fireEvent.focus(inputNode) expect(onFocusMock).toHaveBeenCalled() }) it('calls onKeyDown', () => { const onKeyDownMock = jest.fn() const {getByLabelText} = HTMLRender( <LabelledAutocomplete inputProps={{onKeyDown: onKeyDownMock}} menuProps={{items: [], selectedItemIds: []}} /> ) const inputNode = getByLabelText(AUTOCOMPLETE_LABEL) expect(onKeyDownMock).not.toHaveBeenCalled() fireEvent.keyDown(inputNode, {key: 'Shift'}) expect(onKeyDownMock).toHaveBeenCalled() }) it('calls onKeyUp', () => { const onKeyUpMock = jest.fn() const {getByLabelText} = HTMLRender( <LabelledAutocomplete inputProps={{onKeyUp: onKeyUpMock}} menuProps={{items: [], selectedItemIds: []}} /> ) const inputNode = getByLabelText(AUTOCOMPLETE_LABEL) expect(onKeyUpMock).not.toHaveBeenCalled() fireEvent.keyUp(inputNode, {key: 'Shift'}) expect(onKeyUpMock).toHaveBeenCalled() }) it('calls onKeyPress', () => { const onKeyPressMock = jest.fn() const {getByLabelText} = HTMLRender( <LabelledAutocomplete inputProps={{onKeyPress: onKeyPressMock}} menuProps={{items: [], selectedItemIds: []}} /> ) const inputNode = getByLabelText(AUTOCOMPLETE_LABEL) expect(onKeyPressMock).not.toHaveBeenCalled() userEvent.type(inputNode, '{enter}') expect(onKeyPressMock).toHaveBeenCalled() }) it('opens the menu when the input is focused', () => { const {getByLabelText} = HTMLRender(<LabelledAutocomplete menuProps={{items: [], selectedItemIds: []}} />) const inputNode = getByLabelText(AUTOCOMPLETE_LABEL) expect(inputNode.getAttribute('aria-expanded')).not.toBe('true') fireEvent.focus(inputNode) expect(inputNode.getAttribute('aria-expanded')).toBe('true') }) it('closes the menu when the input is blurred', () => { const {getByLabelText} = HTMLRender(<LabelledAutocomplete menuProps={{items: [], selectedItemIds: []}} />) const inputNode = getByLabelText(AUTOCOMPLETE_LABEL) expect(inputNode.getAttribute('aria-expanded')).not.toBe('true') fireEvent.focus(inputNode) expect(inputNode.getAttribute('aria-expanded')).toBe('true') // eslint-disable-next-line github/no-blur fireEvent.blur(inputNode) // wait a tick for blur to finish setTimeout(() => { expect(inputNode.getAttribute('aria-expanded')).not.toBe('true') }, 0) }) it('sets the input value to the suggested item text and highlights the untyped part of the word', () => { const {container, getByDisplayValue} = HTMLRender( <LabelledAutocomplete menuProps={{items: mockItems, selectedItemIds: []}} /> ) const inputNode = container.querySelector('#autocompleteInput') inputNode && userEvent.type(inputNode, 'ze') expect(getByDisplayValue('zero')).toBeDefined() }) it('does not show or highlight suggestion text after the user hits Backspace until they hit another key', () => { const {container, getByDisplayValue} = HTMLRender( <LabelledAutocomplete menuProps={{items: mockItems, selectedItemIds: []}} /> ) const inputNode = container.querySelector('#autocompleteInput') expect((inputNode as HTMLInputElement).selectionStart).toBe(0) inputNode && userEvent.type(inputNode, 'ze') expect(getByDisplayValue('zero')).toBeDefined() expect((inputNode as HTMLInputElement).selectionStart).toBe(2) expect((inputNode as HTMLInputElement).selectionEnd).toBe(4) inputNode && userEvent.type(inputNode, '{backspace}') expect((inputNode as HTMLInputElement).selectionStart).toBe(2) expect(getByDisplayValue('ze')).toBeDefined() inputNode && userEvent.type(inputNode, 'r') expect((inputNode as HTMLInputElement).selectionStart).toBe(3) expect((inputNode as HTMLInputElement).selectionEnd).toBe(4) expect(getByDisplayValue('zero')).toBeDefined() }) it('clears the input value when when the user hits Escape', () => { const {container} = HTMLRender(<LabelledAutocomplete menuProps={{items: mockItems, selectedItemIds: []}} />) const inputNode = container.querySelector('#autocompleteInput') expect(inputNode?.getAttribute('aria-expanded')).not.toBe('true') inputNode && userEvent.type(inputNode, 'ze') expect(inputNode?.getAttribute('aria-expanded')).toBe('true') inputNode && userEvent.type(inputNode, '{esc}') expect(inputNode?.getAttribute('aria-expanded')).not.toBe('true') }) }) describe('Autocomplete.Menu', () => { it('calls a custom filter function', () => { const filterFnMock = jest.fn() const {container} = HTMLRender( <LabelledAutocomplete menuProps={{items: mockItems, selectedItemIds: [], filterFn: filterFnMock}} /> ) const inputNode = container.querySelector('#autocompleteInput') inputNode && userEvent.type(inputNode, 'ze') expect(filterFnMock).toHaveBeenCalled() }) it('calls a custom sort function when the menu closes', () => { const sortOnCloseFnMock = jest.fn() const {container} = HTMLRender( <LabelledAutocomplete menuProps={{items: mockItems, selectedItemIds: [], sortOnCloseFn: sortOnCloseFnMock}} /> ) const inputNode = container.querySelector('#autocompleteInput') // `sortOnCloseFnMock` will be called in a `.sort()` on render to check if the // current sort order matches the result of `sortOnCloseFnMock` expect(sortOnCloseFnMock).toHaveBeenCalledTimes(mockItems.length - 1) if (inputNode) { userEvent.type(inputNode, 'ze') // eslint-disable-next-line github/no-blur fireEvent.blur(inputNode) } // wait a tick for blur to finish setTimeout(() => { expect(sortOnCloseFnMock).toHaveBeenCalledTimes(mockItems.length) }, 0) }) it("calls onOpenChange with the menu's open state", () => { const onOpenChangeMock = jest.fn() const {container} = HTMLRender( <LabelledAutocomplete menuProps={{items: mockItems, selectedItemIds: [], onOpenChange: onOpenChangeMock}} /> ) const inputNode = container.querySelector('#autocompleteInput') inputNode && userEvent.type(inputNode, 'ze') expect(onOpenChangeMock).toHaveBeenCalled() }) it('calls onSelectedChange with the data for the selected items', () => { const onSelectedChangeMock = jest.fn() const {container} = HTMLRender( <LabelledAutocomplete menuProps={{items: mockItems, selectedItemIds: [], onSelectedChange: onSelectedChangeMock}} /> ) const inputNode = container.querySelector('#autocompleteInput') expect(onSelectedChangeMock).not.toHaveBeenCalled() if (inputNode) { fireEvent.focus(inputNode) userEvent.type(inputNode, '{enter}') } // wait a tick for the keyboard event to be dispatched to the menu item setTimeout(() => { expect(onSelectedChangeMock).toHaveBeenCalledWith([mockItems[0]]) }, 0) }) it('does not close the menu when clicking an item in the menu if selectionVariant=multiple', () => { const {getByText, container} = HTMLRender( <LabelledAutocomplete menuProps={{items: mockItems, selectedItemIds: [], selectionVariant: 'multiple'}} /> ) const inputNode = container.querySelector('#autocompleteInput') const itemToClickNode = getByText(mockItems[1].text) expect(inputNode?.getAttribute('aria-expanded')).not.toBe('true') inputNode && fireEvent.focus(inputNode) expect(inputNode?.getAttribute('aria-expanded')).toBe('true') fireEvent.click(itemToClickNode) inputNode && userEvent.type(inputNode, '{enter}') expect(inputNode?.getAttribute('aria-expanded')).toBe('true') }) it('closes the menu when clicking an item in the menu if selectionVariant=single', () => { const {getByText, container} = HTMLRender( <LabelledAutocomplete menuProps={{items: mockItems, selectedItemIds: [], selectionVariant: 'single'}} /> ) const inputNode = container.querySelector('#autocompleteInput') const itemToClickNode = getByText(mockItems[1].text) expect(inputNode?.getAttribute('aria-expanded')).not.toBe('true') inputNode && fireEvent.focus(inputNode) expect(inputNode?.getAttribute('aria-expanded')).toBe('true') fireEvent.click(itemToClickNode) expect(inputNode?.getAttribute('aria-expanded')).not.toBe('true') }) it('calls handleAddItem with new item data when passing addNewItem', () => { const handleAddItemMock = jest.fn() const {getByText} = HTMLRender( <LabelledAutocomplete menuProps={{ items: mockItems, selectedItemIds: [], selectionVariant: 'multiple', addNewItem: { text: 'Add new item', handleAddItem: handleAddItemMock } }} /> ) const addNewItemNode = getByText('Add new item') expect(handleAddItemMock).not.toHaveBeenCalled() fireEvent.click(addNewItemNode) expect(handleAddItemMock).toHaveBeenCalled() }) }) })
the_stack
// clang-format off import {DomIf, flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {AutofillManagerImpl, PasswordsSectionElement, PaymentsManagerImpl, SettingsAutofillSectionElement, SettingsPaymentsSectionElement} from 'chrome://settings/lazy_load.js'; import {CrSettingsPrefs, MultiStoreExceptionEntry, MultiStorePasswordUiEntry, OpenWindowProxyImpl, PasswordManagerImpl, SettingsAutofillPageElement, SettingsPluralStringProxyImpl, SettingsPrefsElement} from 'chrome://settings/settings.js'; import {assertDeepEquals, assertEquals, assertNotEquals} from 'chrome://webui-test/chai_assert.js'; import {TestPluralStringProxy} from 'chrome://webui-test/test_plural_string_proxy.js'; import {FakeSettingsPrivate} from './fake_settings_private.js'; import {AutofillManagerExpectations, createAddressEntry, createCreditCardEntry, createExceptionEntry, createPasswordEntry, PaymentsManagerExpectations, TestAutofillManager, TestPaymentsManager} from './passwords_and_autofill_fake_data.js'; import {makeCompromisedCredential} from './passwords_and_autofill_fake_data.js'; import {TestOpenWindowProxy} from './test_open_window_proxy.js'; import {PasswordManagerExpectations,TestPasswordManagerProxy} from './test_password_manager_proxy.js'; // clang-format on suite('PasswordsAndForms', function() { /** * Creates a new passwords and forms element. */ function createAutofillElement(prefsElement: SettingsPrefsElement): SettingsAutofillPageElement { const element = document.createElement('settings-autofill-page'); element.prefs = prefsElement.prefs; document.body.appendChild(element); element.shadowRoot!.querySelector<DomIf>( 'dom-if[route-path="/passwords"]')!.if = true; element.shadowRoot!.querySelector<DomIf>( 'dom-if[route-path="/payments"]')!.if = true; element.shadowRoot!.querySelector<DomIf>( 'dom-if[route-path="/addresses"]')!.if = true; flush(); return element; } /** * @param autofill Whether autofill is enabled or not. * @param passwords Whether passwords are enabled or not. */ function createPrefs( autofill: boolean, passwords: boolean): Promise<SettingsPrefsElement> { return new Promise(function(resolve) { CrSettingsPrefs.deferInitialization = true; const prefs = document.createElement('settings-prefs'); prefs.initialize(new FakeSettingsPrivate([ { key: 'autofill.enabled', type: chrome.settingsPrivate.PrefType.BOOLEAN, value: autofill, }, { key: 'autofill.profile_enabled', type: chrome.settingsPrivate.PrefType.BOOLEAN, value: true, }, { key: 'autofill.credit_card_enabled', type: chrome.settingsPrivate.PrefType.BOOLEAN, value: true, }, { key: 'credentials_enable_service', type: chrome.settingsPrivate.PrefType.BOOLEAN, value: passwords, }, { key: 'credentials_enable_autosignin', type: chrome.settingsPrivate.PrefType.BOOLEAN, value: true, }, { key: 'payments.can_make_payment_enabled', type: chrome.settingsPrivate.PrefType.BOOLEAN, value: true, } ]) as unknown as typeof chrome.settingsPrivate); CrSettingsPrefs.initialized.then(function() { resolve(prefs); }); }); } /** * Cleans up prefs so tests can continue to run. * @param prefs The prefs element. */ function destroyPrefs(prefs: SettingsPrefsElement) { CrSettingsPrefs.resetForTesting(); CrSettingsPrefs.deferInitialization = false; prefs.resetForTesting(); } /** * Creates PasswordManagerExpectations with the values expected after first * creating the element. */ function basePasswordExpectations(): PasswordManagerExpectations { const expected = new PasswordManagerExpectations(); expected.requested.passwords = 1; expected.requested.exceptions = 1; expected.requested.accountStorageOptInState = 1; expected.listening.passwords = 1; expected.listening.exceptions = 1; expected.listening.accountStorageOptInState = 1; return expected; } /** * Creates AutofillManagerExpectations with the values expected after first * creating the element. */ function baseAutofillExpectations(): AutofillManagerExpectations { const expected = new AutofillManagerExpectations(); expected.requestedAddresses = 1; expected.listeningAddresses = 1; return expected; } /** * Creates PaymentsManagerExpectations with the values expected after first * creating the element. */ function basePaymentsExpectations(): PaymentsManagerExpectations { const expected = new PaymentsManagerExpectations(); expected.requestedCreditCards = 1; expected.listeningCreditCards = 1; return expected; } let passwordManager: TestPasswordManagerProxy; let autofillManager: TestAutofillManager; let paymentsManager: TestPaymentsManager; setup(async function() { document.body.innerHTML = ''; // Override the PasswordManagerImpl for testing. passwordManager = new TestPasswordManagerProxy(); PasswordManagerImpl.setInstance(passwordManager); // Override the AutofillManagerImpl for testing. autofillManager = new TestAutofillManager(); AutofillManagerImpl.setInstance(autofillManager); // Override the PaymentsManagerImpl for testing. paymentsManager = new TestPaymentsManager(); PaymentsManagerImpl.setInstance(paymentsManager); }); test('baseLoadAndRemove', function() { return createPrefs(true, true).then(function(prefs) { const element = createAutofillElement(prefs); const passwordsExpectations = basePasswordExpectations(); passwordManager.assertExpectations(passwordsExpectations); const autofillExpectations = baseAutofillExpectations(); autofillManager.assertExpectations(autofillExpectations); const paymentsExpectations = basePaymentsExpectations(); paymentsManager.assertExpectations(paymentsExpectations); element.remove(); flush(); passwordsExpectations.listening.passwords = 0; passwordsExpectations.listening.exceptions = 0; passwordsExpectations.listening.accountStorageOptInState = 0; passwordManager.assertExpectations(passwordsExpectations); autofillExpectations.listeningAddresses = 0; autofillManager.assertExpectations(autofillExpectations); paymentsExpectations.listeningCreditCards = 0; paymentsManager.assertExpectations(paymentsExpectations); destroyPrefs(prefs); }); }); test('loadPasswordsAsync', function() { return createPrefs(true, true).then(function(prefs) { const element = createAutofillElement(prefs); const list = [ createPasswordEntry({url: 'one.com', username: 'user1', id: 0}), createPasswordEntry({url: 'two.com', username: 'user1', id: 1}) ]; passwordManager.lastCallback.addSavedPasswordListChangedListener!(list); flush(); assertDeepEquals( list.map(entry => new MultiStorePasswordUiEntry(entry)), element.shadowRoot! .querySelector<PasswordsSectionElement>( '#passwordSection')!.savedPasswords); // The callback is coming from the manager, so the element shouldn't // have additional calls to the manager after the base expectations. passwordManager.assertExpectations(basePasswordExpectations()); autofillManager.assertExpectations(baseAutofillExpectations()); paymentsManager.assertExpectations(basePaymentsExpectations()); destroyPrefs(prefs); }); }); test('loadExceptionsAsync', function() { return createPrefs(true, true).then(function(prefs) { const element = createAutofillElement(prefs); const list = [ createExceptionEntry({url: 'one.com', id: 0}), createExceptionEntry({url: 'two.com', id: 1}) ]; passwordManager.lastCallback.addExceptionListChangedListener!(list); flush(); assertDeepEquals( list.map(entry => new MultiStoreExceptionEntry(entry)), element.shadowRoot! .querySelector<PasswordsSectionElement>( '#passwordSection')!.passwordExceptions); // The callback is coming from the manager, so the element shouldn't // have additional calls to the manager after the base expectations. passwordManager.assertExpectations(basePasswordExpectations()); autofillManager.assertExpectations(baseAutofillExpectations()); paymentsManager.assertExpectations(basePaymentsExpectations()); destroyPrefs(prefs); }); }); test('loadAddressesAsync', function() { return createPrefs(true, true).then(function(prefs) { const element = createAutofillElement(prefs); const addressList = [createAddressEntry(), createAddressEntry()]; const cardList = [createCreditCardEntry(), createCreditCardEntry()]; autofillManager.lastCallback.setPersonalDataManagerListener! (addressList, cardList); flush(); assertEquals( addressList, element.shadowRoot! .querySelector<SettingsAutofillSectionElement>( '#autofillSection')!.addresses); // The callback is coming from the manager, so the element shouldn't // have additional calls to the manager after the base expectations. passwordManager.assertExpectations(basePasswordExpectations()); autofillManager.assertExpectations(baseAutofillExpectations()); paymentsManager.assertExpectations(basePaymentsExpectations()); destroyPrefs(prefs); }); }); test('loadCreditCardsAsync', function() { return createPrefs(true, true).then(function(prefs) { const element = createAutofillElement(prefs); const addressList = [createAddressEntry(), createAddressEntry()]; const cardList = [createCreditCardEntry(), createCreditCardEntry()]; paymentsManager.lastCallback.setPersonalDataManagerListener! (addressList, cardList); flush(); assertEquals( cardList, element.shadowRoot! .querySelector<SettingsPaymentsSectionElement>( '#paymentsSection')!.creditCards); // The callback is coming from the manager, so the element shouldn't // have additional calls to the manager after the base expectations. passwordManager.assertExpectations(basePasswordExpectations()); autofillManager.assertExpectations(baseAutofillExpectations()); paymentsManager.assertExpectations(basePaymentsExpectations()); destroyPrefs(prefs); }); }); }); function createAutofillPageSection() { // Create a passwords-section to use for testing. const autofillPage = document.createElement('settings-autofill-page'); autofillPage.prefs = { profile: { password_manager_leak_detection: {}, }, }; document.body.innerHTML = ''; document.body.appendChild(autofillPage); flush(); return autofillPage; } suite('PasswordsUITest', function() { let autofillPage: SettingsAutofillPageElement; let openWindowProxy: TestOpenWindowProxy; let passwordManager: TestPasswordManagerProxy; let pluralString: TestPluralStringProxy; setup(function() { openWindowProxy = new TestOpenWindowProxy(); OpenWindowProxyImpl.setInstance(openWindowProxy); // Override the PasswordManagerImpl for testing. passwordManager = new TestPasswordManagerProxy(); PasswordManagerImpl.setInstance(passwordManager); pluralString = new TestPluralStringProxy(); SettingsPluralStringProxyImpl.setInstance(pluralString); autofillPage = createAutofillPageSection(); }); teardown(function() { autofillPage.remove(); }); test('Compromised Credential', async function() { // Check if sublabel is empty assertEquals( '', autofillPage.shadowRoot! .querySelector<HTMLElement>( '#passwordManagerSubLabel')!.innerText.trim()); // Simulate one compromised password const leakedPasswords = [ makeCompromisedCredential( 'google.com', 'jdoerrie', chrome.passwordsPrivate.CompromiseType.LEAKED), ]; passwordManager.data.leakedCredentials = leakedPasswords; // create autofill page with leaked credentials autofillPage = createAutofillPageSection(); await passwordManager.whenCalled('getCompromisedCredentials'); await pluralString.whenCalled('getPluralString'); // With compromised credentials sublabel should have text assertNotEquals( '', autofillPage.shadowRoot! .querySelector<HTMLElement>( '#passwordManagerSubLabel')!.innerText.trim()); }); });
the_stack
import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { CellType, DefaultSortingStrategy, GridSelectionMode, IButtonGroupEventArgs, IChangeSwitchEventArgs, IGridKeydownEventArgs, IgxButtonGroupComponent, IgxDialogComponent, IgxGridComponent, IgxSliderComponent, IRowSelectionEventArgs, SortingDirection } from '<%=igxPackage%>'; import { CategoryChartType, IgxCategoryChartComponent } from 'igniteui-angular-charts'; import { timer } from 'rxjs'; import { debounce } from 'rxjs/operators'; import { LocalDataService } from './localData.service'; import { Contract, REGIONS } from './localData/financialData'; @Component({ providers: [LocalDataService], selector: 'app-<%=filePrefix%>', templateUrl: './<%=filePrefix%>.component.html', styleUrls: ['./<%=filePrefix%>.component.scss'] }) export class <%=ClassName%>Component implements OnInit, AfterViewInit, OnDestroy { @ViewChild('grid1', { static: true }) public grid1!: IgxGridComponent; @ViewChild('buttonGroup1', { static: true }) public buttonGroup1!: IgxButtonGroupComponent; @ViewChild('buttonGroup2', { static: true }) public buttonGroup2!: IgxButtonGroupComponent; @ViewChild('slider1', { static: true }) public volumeSlider!: IgxSliderComponent; @ViewChild('slider2', { static: true }) public intervalSlider!: IgxSliderComponent; @ViewChild('chart1', { static: true }) public chart1!: IgxCategoryChartComponent; @ViewChild('dialog', { static: true }) public dialog!: IgxDialogComponent; public showToolbar: boolean = false; public properties: string[] = []; public selectionMode: GridSelectionMode = 'multiple'; public chartType = CategoryChartType; public theme: boolean = false; public volume: number = 1000; public frequency: number = 500; public data: any[] = []; public chartData: any[] = []; public multiCellSelection: { data: any[] } = { data: [] }; public controls = [ { disabled: false, icon: 'update', label: 'LIVE PRICES', selected: false }, { disabled: false, icon: 'update', label: 'LIVE ALL PRICES', selected: false }, { disabled: true, icon: 'stop', label: 'Stop', selected: false }, { disabled: false, icon: 'insert_chart_outlined', label: 'Chart', selected: false } ]; public contracts = Contract; public regions = REGIONS; private subscription: any; private selectedButton: number = -1; private timer: any; private volumeChanged: any; constructor( private localService: LocalDataService, private elRef: ElementRef, private cdr: ChangeDetectorRef) { this.subscription = this.localService.getData(this.volume); this.localService.records.subscribe(x => { this.data = x; }); } public ngOnInit(): void { this.grid1.groupingExpressions = [{ dir: SortingDirection.Desc, fieldName: 'Category', ignoreCase: false, strategy: DefaultSortingStrategy.instance() }, { dir: SortingDirection.Desc, fieldName: 'Type', ignoreCase: false, strategy: DefaultSortingStrategy.instance() }, { dir: SortingDirection.Desc, fieldName: 'Settlement', ignoreCase: false, strategy: DefaultSortingStrategy.instance() } ]; this.volumeChanged = this.volumeSlider.valueChange.pipe(debounce(() => timer(200))); this.volumeChanged.subscribe( (x: any) => { this.localService.getData(this.volume); }, (err: string) => console.log('Error: ' + err)); } public ngAfterViewInit(): void { this.grid1.hideGroupedColumns = true; this.grid1.reflow(); this.selectFirstGroupAndFillChart(); this.cdr.detectChanges(); } public selectFirstGroupAndFillChart(): void { this.properties = ['Price', 'Country']; this.setChartConfig('Countries', 'Prices (USD)', 'Data Chart with prices by Category and Country'); if (this.grid1.groupsRecords[0].groups && this.grid1.groupsRecords[0]?.groups[0]?.groups) { const recordsToBeSelected = this.grid1.selectionService.getRowIDs(this.grid1.groupsRecords[0].groups[0].groups[0].records); recordsToBeSelected.forEach(item => { this.grid1.selectionService.selectRowById(item, false, true); }); } } public setChartConfig(xAsis: string, yAxis: string, title: string): void { // update label interval and angle based on data this.setLabelIntervalAndAngle(); this.chart1.xAxisTitle = xAsis; this.chart1.yAxisTitle = yAxis; this.chart1.chartTitle = title; } public onButtonAction(evt: IButtonGroupEventArgs): void { switch (evt.index) { case 0: { this.disableOtherButtons(evt.index, true); const currData = this.grid1.data; this.timer = setInterval(() => this.ticker(currData), this.frequency); break; } case 1: { this.disableOtherButtons(evt.index, true); const currData = this.grid1.data; this.timer = setInterval(() => this.tickerAllPrices(currData), this.frequency); break; } case 2: { this.disableOtherButtons(evt.index, false); this.stopFeed(); break; } case 3: { this.disableOtherButtons(evt.index, true); this.dialog.open(); break; } default: { break; } } } public onCloseHandler(): void { this.buttonGroup1.selectButton(2); if (this.grid1.navigation.activeNode) { if (this.grid1.navigation.activeNode.row === -1) { this.grid1.theadRow.nativeElement.focus(); } else { this.grid1.tbody.nativeElement.focus(); } } } public closeDialog(evt: KeyboardEvent): void { if (this.dialog.isOpen && evt.shiftKey === true && evt.ctrlKey === true && evt.key.toLowerCase() === 'd') { evt.preventDefault(); this.dialog.close(); } } public onChange(event: IChangeSwitchEventArgs): void { if (this.grid1.groupingExpressions.length > 0) { this.grid1.groupingExpressions = []; } else { this.grid1.groupingExpressions = [{ dir: SortingDirection.Desc, fieldName: 'Category', ignoreCase: false, strategy: DefaultSortingStrategy.instance() }, { dir: SortingDirection.Desc, fieldName: 'Type', ignoreCase: false, strategy: DefaultSortingStrategy.instance() }, { dir: SortingDirection.Desc, fieldName: 'Contract', ignoreCase: false, strategy: DefaultSortingStrategy.instance() } ]; } } public rowSelectionChanging(args: IRowSelectionEventArgs): void { this.grid1.clearCellSelection(); this.chartData = []; args.newSelection.forEach(row => { if (this.grid1.data) { this.chartData.push(this.grid1.data[row]); this.chart1.notifyInsertItem(this.chartData, this.chartData.length - 1, this.grid1.data[row]); } }); this.setLabelIntervalAndAngle(); this.setChartConfig('Countries', 'Prices (USD)', 'Data Chart with prices by Category and Country'); } public openSingleRowChart(cell: CellType): void { this.chartData = []; setTimeout(() => { this.chartData = this.data.filter(item => item.Region === cell.row.data.Region && item.Category === cell.row.data.Category); this.chart1.notifyInsertItem(this.chartData, this.chartData.length - 1, {}); this.setLabelIntervalAndAngle(); this.chart1.chartTitle = 'Data Chart with prices of ' + this.chartData[0].Category + ' in ' + this.chartData[0].Region + ' Region'; this.dialog.open(); }, 200); } public stopFeed(): void { if (this.timer) { clearInterval(this.timer); } if (this.subscription) { this.subscription.unsubscribe(); } } public formatNumber(value: number): string { return value.toFixed(2); } public percentage(value: number): string { return value.toFixed(2) + '%'; } public formatCurrency(value: number): string { return '$' + value.toFixed(3); } /** * the below code is needed when accessing the sample through the navigation * it will style all the space below the sample component element, but not the navigation menu */ public onThemeChanged(event: IChangeSwitchEventArgs): void { const parentEl = this.parentComponentEl(); if (event.checked && parentEl.classList.contains('main')) { parentEl.classList.add('fin-dark-theme'); } else { parentEl.classList.remove('fin-dark-theme'); } } public ngOnDestroy(): void { this.stopFeed(); this.volumeChanged.unsubscribe(); } public toggleToolbar(): void { this.showToolbar = !this.showToolbar; } private negative = (rowData: any): boolean => { return rowData['Change(%)'] < 0; } private positive = (rowData: any): boolean => { return rowData['Change(%)'] > 0; } private changeNegative = (rowData: any): boolean => { return rowData['Change(%)'] < 0 && rowData['Change(%)'] > -1; } private changePositive = (rowData: any): boolean => { return rowData['Change(%)'] > 0 && rowData['Change(%)'] < 1; } private strongPositive = (rowData: any): boolean => { return rowData['Change(%)'] >= 1; } private strongNegative = (rowData: any, key: string): boolean => { return rowData['Change(%)'] <= -1; } // tslint:disable:member-ordering public trends = { changeNeg: this.changeNegative, changePos: this.changePositive, negative: this.negative, positive: this.positive, strongNegative: this.strongNegative, strongPositive: this.strongPositive }; public trendsChange = { changeNeg2: this.changeNegative, changePos2: this.changePositive, strongNegative2: this.strongNegative, strongPositive2: this.strongPositive }; public setLabelIntervalAndAngle(): void { const intervalSet = this.chartData.length; if (intervalSet < 10) { this.chart1.xAxisLabelAngle = 0; this.chart1.xAxisInterval = 1; } else if (intervalSet < 15) { this.chart1.xAxisLabelAngle = 30; this.chart1.xAxisInterval = 1; } else if (intervalSet < 40) { this.chart1.xAxisLabelAngle = 90; this.chart1.xAxisInterval = 1; } else if (intervalSet < 100) { this.chart1.xAxisLabelAngle = 90; this.chart1.xAxisInterval = 3; } else if (intervalSet < 200) { this.chart1.xAxisLabelAngle = 90; this.chart1.xAxisInterval = 5; } else if (intervalSet < 400) { this.chart1.xAxisLabelAngle = 90; this.chart1.xAxisInterval = 7; } else if (intervalSet > 400) { this.chart1.xAxisLabelAngle = 90; this.chart1.xAxisInterval = 10; } this.chart1.yAxisAbbreviateLargeNumbers = true; } public gridKeydown(evt: KeyboardEvent): void { if (this.grid1.selectedRows.length > 0 && evt.shiftKey === true && evt.ctrlKey === true && evt.key.toLowerCase() === 'd') { evt.preventDefault(); this.dialog.open(); } } public customKeydown(args: IGridKeydownEventArgs): void { const target: CellType = args.target as CellType; const evt: KeyboardEvent = args.event as KeyboardEvent; const type = args.targetType; if (type === 'dataCell' && target.column.field === 'Chart' && evt.key.toLowerCase() === 'enter') { this.grid1.selectRows([target.row.key], true); this.openSingleRowChart(target); } } // tslint:enable:member-ordering private disableOtherButtons(ind: number, disableButtons: boolean): void { if (this.subscription) { this.subscription.unsubscribe(); } this.volumeSlider.disabled = disableButtons; this.intervalSlider.disabled = disableButtons; this.selectedButton = ind; this.buttonGroup1.buttons.forEach((button, index) => { if (index === 2) { button.disabled = !disableButtons; } else { this.buttonGroup1.buttons[0].disabled = disableButtons; this.buttonGroup1.buttons[1].disabled = disableButtons; } }); } /** * returns the main div container of the Index Component, * if path is /samples/sample-url, or the appRoot, if path is /sample-url */ private parentComponentEl(): HTMLElement { return this.elRef.nativeElement.parentElement.parentElement; } private ticker(data: any): void { this.grid1.data = this.updateRandomPrices(data); } private tickerAllPrices(data: any): void { this.grid1.data = this.updateAllPrices(data); } /** * Updates values in every record */ private updateAllPrices(data: any[]): any[] { const newData = []; for (const dataRow of data) { newData.push(this.randomizeObjectData(dataRow)); } return newData; } /** * Updates values in random number of records */ private updateRandomPrices(data: any[]): any { const newData = data.slice(); for (let i = Math.round(Math.random() * 10), y = 0; i < data.length; i += Math.round(Math.random() * 10)) { newData[i] = this.randomizeObjectData(data[i]); y++; } return newData; } /** * Generates ne values for Change, Price and ChangeP columns */ private randomizeObjectData(dataObj: any) { const changeP = 'Change(%)'; const res = this.generateNewPrice(dataObj.Price); dataObj.Change = res.Price - dataObj.Price; dataObj.Price = res.Price; dataObj[changeP] = res.ChangePercent; return { ...dataObj }; } private generateNewPrice(oldPrice: number): any { let rnd = Math.random(); rnd = Math.round(rnd * 100) / 100; const volatility = 2; let newPrice = 0; let changePercent = 2 * volatility * rnd; if (changePercent > volatility) { changePercent -= (2 * volatility); } const changeAmount = oldPrice * (changePercent / 100); newPrice = oldPrice + changeAmount; newPrice = Math.round(newPrice * 100) / 100; const result = { Price: 0, ChangePercent: 0 }; changePercent = Math.round(changePercent * 100) / 100; result.Price = newPrice; result.ChangePercent = changePercent; return result; } get grouped(): boolean { return this.grid1.groupingExpressions.length > 0; } get buttonSelected(): number { return this.selectedButton || this.selectedButton === 0 ? this.selectedButton : -1; } }
the_stack
import { EditorState, RichUtils, SelectionState, ContentState, BlockMap, ContentBlock, } from 'draft-js'; import pluckGoodies from './pluck_goodies'; import { getBlocksWithItsDescendants, hasChildren, adjustHasChildren, } from './tree_utils'; import { moveCurrentBlockUp, moveCurrentBlockDown } from './move'; import { collapseBlock, expandBlock } from './collapse_expand_block'; // import { makeCorrectionsToNodeAndItsDescendants } from './make_corrections_to_node_and_its_descendants'; import { ROOT_KEY, MAX_DEPTH } from '../constants'; import { onTab } from './tab'; export const CHANGE = 'CHANGE'; export const SET_ROOT_EDITOR_STATE = 'SET_ROOT_EDITOR_STATE'; export const SET_EDITOR_STATE = 'SET_EDITOR_STATE'; export const SET_STATE = 'SET_STATE'; export const INSERT_SOFT_NEWLINE = 'INSERT_SOFT_NEWLINE'; export const ZOOM = 'ZOOM'; export const COLLAPSE_ITEM = 'COLLAPSE_ITEM'; export const EXPAND_ITEM = 'EXPAND_ITEM'; export const EXPAND_ALL = 'EXPAND_ALL'; export const COLLAPSE_ALL = 'COLLAPSE_ALL'; export const MOVE_UP = 'MOVE_UP'; export const MOVE_DOWN = 'MOVE_DOWN'; export const TOGGLE_COMPLETION = 'TOGGLE_COMPLETION'; export const DELETE_CURRENT_ITEM = 'DELETE_CURRENT_ITEM '; export const INDENT = 'INDENT'; export const DEDENT = 'DEDENT'; export const BOOKMARK = 'BOOKMARK'; export interface DeepnotesEditorState { // This is for future, when editorState will only have blocks which are under the zoomed in item node. The rootEditorState will always have all the blocks. rootEditorState: EditorState; editorState: EditorState; zoomedInItemId: string; } interface ChangeAction { type: typeof CHANGE; editorState: EditorState; } interface InsertSoftNewlineAction { type: typeof INSERT_SOFT_NEWLINE; } interface SetRootEditorStateAction { type: typeof SET_ROOT_EDITOR_STATE; editorState: EditorState; } interface SetEditorStateAction { type: typeof SET_EDITOR_STATE; editorState: EditorState; } interface SetStateAction { type: typeof SET_STATE; prop: string; val: any; } interface MoveUpAction { type: typeof MOVE_UP; } interface MoveDownAction { type: typeof MOVE_DOWN; } interface CollapseItemAction { type: typeof COLLAPSE_ITEM; blockKey: string; } interface ExpandItemAction { type: typeof EXPAND_ITEM; blockKey: string; } interface ExpandAllAction { type: typeof EXPAND_ALL; } interface CollapseAllAction { type: typeof COLLAPSE_ALL; } interface ZoomAction { type: typeof ZOOM; blockKey: string; } interface ToggleCompletionAction { type: typeof TOGGLE_COMPLETION; } interface DeleteCurrentItemAction { type: typeof DELETE_CURRENT_ITEM; } interface IndentItemAction { type: typeof INDENT; } interface DedentItemAction { type: typeof DEDENT; } interface BookmarkAction { type: typeof BOOKMARK; } export type EditorActions = | BookmarkAction | IndentItemAction | DedentItemAction | ExpandAllAction | CollapseAllAction | DeleteCurrentItemAction | ToggleCompletionAction | ZoomAction | SetStateAction | ChangeAction | InsertSoftNewlineAction | SetRootEditorStateAction | SetEditorStateAction | MoveUpAction | MoveDownAction | CollapseItemAction | ExpandItemAction; function updateSelectionForZoom( editorState: EditorState, zoomedInItemId: string ) { const { selectionState, blockMap } = pluckGoodies(editorState); let newSelectionState = selectionState; const blockWithItsChildren = getBlocksWithItsDescendants( blockMap, zoomedInItemId ); // if the zoomed in item has children, let's focus the first child if (blockWithItsChildren.count() > 1) { // check if one of the children has focus const childWithFocus = blockWithItsChildren.find( block => !!(block && block.getKey() === selectionState.getAnchorKey()) ); // if one of the children has focus, just maintain that focus // else, focus the first child if (!childWithFocus) { const firstChild = blockWithItsChildren.rest().first(); newSelectionState = SelectionState.createEmpty(firstChild.getKey()); } } else { // if the zoomed in item also has the focus, we should retain it's cursor // position. Else create new focus on the zoomedin item with cursor at // start of line. if (selectionState.getAnchorKey() !== zoomedInItemId) { newSelectionState = SelectionState.createEmpty(zoomedInItemId); } } return EditorState.forceSelection(editorState, newSelectionState); } // This function create a new editorState with blocks only in the sub tree rooted at the zoomedInItemId // function withBlocksForZoomedInItem( // editorState: EditorState, // zoomedInItemId: string, // ) { // const { blockMap } = pluckGoodies(editorState); // const blocks = makeCorrectionsToNodeAndItsDescendants( // blockMap, // blockMap.get(zoomedInItemId), // ); // return EditorState.createWithContent( // ContentState.createFromBlockArray(blocks), // ); // } function zoomReducer(state: DeepnotesEditorState, itemId: string) { const { editorState, zoomedInItemId } = state; const { blockMap } = pluckGoodies(editorState); // if there no zoomed in item, that means there's nothing to zoom out into // If the zoomed in fellow is same is item to zoom into, the zoom reducer // is probably called because the search text changed // can't be because now we removed searchText from query string if (zoomedInItemId === itemId) { console.log('We are at the root. Nothing to zoom out into.'); return state; } let zoomedBlock; // if we are provided itemId to zoom out to if (itemId) { zoomedBlock = blockMap.get(itemId); } const newZoomedInItemId = zoomedBlock ? zoomedBlock.getKey() : ROOT_KEY; // if the zoom is done to the root level, there will be no particular block // to zoom into. And zoomedBlock would be empty in that case. And we // don't need to maintain a separate wholeEditorState return { ...state, // we forceupdate the editor state to itself so that the editor refreshes // If we don't do that, we set the new zoomedInItemId but the editor does // not render again with that information // TODO: Instead of forceupdate, we can update the selection on editorState // We anyways should do it on zoomins. Updating selection, even if it leads // to same selection state, would automatically get draftjs to rerender. editorState: updateSelectionForZoom(state.editorState, newZoomedInItemId), zoomedInItemId: newZoomedInItemId, }; } function toggleCompleteReducer(state: DeepnotesEditorState) { const { blockMap, anchorBlock, contentState, selectionState } = pluckGoodies( state.editorState ); // Don't do anything if the item is empty if (anchorBlock.getText().trim() === '') { return state; } const blocksWithItsDescendants = getBlocksWithItsDescendants( blockMap, anchorBlock.getKey() ); const newBlockMap = blockMap.merge( blocksWithItsDescendants.map(b => b ? b.setIn( ['data', 'completed'], !anchorBlock.getIn(['data', 'completed']) ) : b ) as BlockMap ); const newContentState = contentState.merge({ blockMap: newBlockMap, selectionBefore: selectionState, selectionAfter: selectionState, }) as ContentState; return { ...state, editorState: EditorState.push( state.editorState, newContentState, 'toggle-completion' as any ), }; } function deleteItemWithChildren(state: DeepnotesEditorState) { const { editorState } = state; const { contentState, blockMap, focusKey, focusBlock } = pluckGoodies( editorState ); if (!focusKey) { return state; } const blocksToDelete = getBlocksWithItsDescendants(blockMap, focusKey); const parentId = blockMap.get(focusKey).getIn(['data', 'parentId']); let newBlockMap = blockMap .toSeq() .filter((_: any, k?: string) => !!(k && !blocksToDelete.has(k))) .toOrderedMap(); // don't allow deleting if there is only one item in the list if ( !newBlockMap || newBlockMap.count() === 0 || // at root level, the block map will still have one item, the root item (newBlockMap.count() === 1 && newBlockMap.has(ROOT_KEY)) ) { return state; } const pSibling = contentState.getBlockBefore(focusBlock.getKey()); let newSelection; if (pSibling) { newSelection = new SelectionState({ anchorKey: pSibling.getKey(), anchorOffset: pSibling.getText().length - 1, focusKey: pSibling.getKey(), focusOffset: pSibling.getText().length - 1, }); } else { // what if it's the only item in the list? newSelection = SelectionState.createEmpty( newBlockMap .toSeq() .first() .getKey() ); } // reset the hasChildren state of the parent block newBlockMap = adjustHasChildren(newBlockMap, parentId); return { ...state, editorState: EditorState.push( editorState, contentState.merge({ blockMap: newBlockMap, selectionBefore: newSelection, selectionAfter: newSelection, }) as ContentState, 'delete-item' as any ), }; } function expandCollapseAll(state: DeepnotesEditorState, collapse: boolean) { const { editorState, zoomedInItemId } = state; const { blockMap, contentState } = pluckGoodies(editorState); let blocksWithItsDescendants = getBlocksWithItsDescendants( blockMap, zoomedInItemId ); blocksWithItsDescendants = blocksWithItsDescendants.rest().map(b => { if (!b) { return b; } else { if (hasChildren(blockMap, b.getKey())) { return b.setIn(['data', 'collapsed'], collapse); } else { return b; } } }) as BlockMap; const newBlockMap = blockMap.merge(blocksWithItsDescendants); const newEditorState = EditorState.push( editorState, contentState.set('blockMap', newBlockMap) as ContentState, 'collapse-all' as any ); return { ...state, editorState: newEditorState, }; } function toggleBookmark(editorState: EditorState, zoomedInItemId: string) { const { blockMap, contentState } = pluckGoodies(editorState); const zoomedInBlock = blockMap.get(zoomedInItemId); const newBlockMap = blockMap.set( zoomedInItemId, zoomedInBlock.setIn( ['data', 'bookmarked'], !zoomedInBlock.getIn(['data', 'bookmarked']) ) as ContentBlock ) as BlockMap; return EditorState.push( editorState, contentState.set('blockMap', newBlockMap) as ContentState, 'bookmark' as any ); } export function rootReducer( state: DeepnotesEditorState, action: EditorActions ) { switch (action.type) { case CHANGE: return { ...state, editorState: action.editorState, }; case INSERT_SOFT_NEWLINE: return { ...state, editorState: RichUtils.insertSoftNewline(state.editorState), }; case SET_ROOT_EDITOR_STATE: return { ...state, rootEditorState: action.editorState, }; case SET_EDITOR_STATE: return { ...state, editorState: action.editorState, }; case SET_STATE: return { ...state, [action.prop]: action.val, }; case MOVE_UP: return { ...state, editorState: moveCurrentBlockUp( state.editorState, state.zoomedInItemId ), }; case MOVE_DOWN: return { ...state, editorState: moveCurrentBlockDown( state.editorState, state.zoomedInItemId ), }; case COLLAPSE_ITEM: return { ...state, editorState: collapseBlock(state.editorState, action.blockKey), }; case EXPAND_ITEM: return { ...state, editorState: expandBlock(state.editorState, action.blockKey), }; case EXPAND_ALL: return expandCollapseAll(state, false); case COLLAPSE_ALL: return expandCollapseAll(state, true); case TOGGLE_COMPLETION: return toggleCompleteReducer(state); case DELETE_CURRENT_ITEM: return deleteItemWithChildren(state); case ZOOM: // TODO: we should always pluck out the id of the thing to zoom to // and then send it to this reducer return zoomReducer(state, action.blockKey); case INDENT: return { ...state, editorState: onTab(state.editorState, MAX_DEPTH, state.zoomedInItemId), }; case DEDENT: return { ...state, editorState: onTab( state.editorState, MAX_DEPTH, state.zoomedInItemId, true ), }; case BOOKMARK: return { ...state, editorState: toggleBookmark(state.editorState, state.zoomedInItemId), }; default: return state; } }
the_stack
import * as Gdk from 'gdk'; import * as Gio from 'gio'; import * as GLib from 'glib'; import * as GObject from 'gobject'; import * as Gtk from 'gtk'; import { assert, assertNotNull } from 'src/utils/assert'; import { registerGObjectClass } from 'src/utils/gjs'; const Me = imports.misc.extensionUtils.getCurrentExtension(); const schemaSource = Gio.SettingsSchemaSource.new_from_directory( Me.dir.get_child('schemas').get_path(), Gio.SettingsSchemaSource.get_default(), false ); const hotkeysSchemaName = 'org.gnome.shell.extensions.materialshell.bindings'; function log(...args: any[]) { const fields = { MESSAGE: `${args.join(', ')}` }; const domain = 'Material Shell'; GLib.log_structured(domain, GLib.LogLevelFlags.LEVEL_MESSAGE, fields); } // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function function init() { log('INITIALIZING PREFERENCES'); } // eslint-disable-next-line @typescript-eslint/no-unused-vars function buildPrefsWidget() { log('Prefs widget'); return new PrefsWidget(); } enum WidgetType { BOOLEAN = 0, COMBO = 1, INT = 2, DECIMAL = 3, INPUT = 4, COLOR = 5, CUSTOM = 6, } /* TODO make the hotkey edition through Dialog @registerGObjectClass class HotkeyDialog extends Gtk.Dialog { static metaInfo: GObject.MetaInfo = { GTypeName: 'HotkeyDialog', Template: Me.dir.get_child('hotkey_dialog.ui').get_uri(), Signals: { key_press_cb: { param_types: [GObject.TYPE_STRING], accumulator: 0, }, }, }; constructor(parent: Gtk.Window) { super({ destroyWithParent: true, transientFor: parent, }); this.connect('key_press_cb', (_, response) => { log('key', response); }); } } */ @registerGObjectClass class SettingListBoxRow extends Gtk.ListBoxRow { static metaInfo: GObject.MetaInfo = { GTypeName: 'SettingListBoxRow', Template: Me.dir.get_child('setting_list_box_row.ui').get_uri(), Properties: { 'settings-widget': GObject.ParamSpec.object( 'settings-widget', 'Settings Widget', 'The widget in which the user sets the settings value', GObject.ParamFlags.READWRITE, Gtk.Widget.$gtype ), }, InternalChildren: [ 'name_label', 'description_label', 'widget_container', ], }; private declare _name_label: Gtk.Label; private declare _description_label: Gtk.Label; private declare _widget_container: Gtk.Box; private _settings_widget: Gtk.Widget; constructor(summary: string, description: string, widget: Gtk.Widget) { super(); this._name_label.set_text(summary); this._description_label.set_text(description); this._settings_widget = widget; this._widget_container.append(this._settings_widget); } } @registerGObjectClass class HotkeyRowData extends GObject.Object { key: string; summary: string; accelName: string; constructor(key: string, summary: string, accelName: string) { super(); this.key = key; this.summary = summary; this.accelName = accelName; } } @registerGObjectClass class HotkeyListBox extends Gtk.ListBox { static metaInfo: GObject.MetaInfo = { GTypeName: 'HotkeyListBox', Template: Me.dir.get_child('hotkey_list_box.ui').get_uri(), }; settings: Gio.Settings; constructor() { super(); this.connect('row-activated', (_, row: HotkeyListBoxRow) => { row.openDialog(); }); this.settings = new Gio.Settings({ settings_schema: schemaSource.lookup(hotkeysSchemaName, false) || undefined, }); this.settings .list_keys() .map((key) => { const [ok, accelKey, accelerators, mods] = Gtk.accelerator_parse_with_keycode( this.settings.get_strv(key)[0], null ); if (!ok) { Me.log( `Could not parse key for ${key}: ${ this.settings.get_strv(key)[0] }` ); } let accelName; if (accelKey == 0) { accelName = 'Disabled'; } else { assert( accelKey !== null && mods !== null, 'parse should have succeeded' ); accelName = Gtk.accelerator_get_label(accelKey, mods); } const summary = this.settings.settings_schema .get_key(key) .get_summary(); return { key, summary, accelKey, mods, accelName, }; }) .sort((modelEntryA, modelEntryB) => { return modelEntryA.summary > modelEntryB.summary ? 1 : 0; }) .forEach((modelEntry) => { const row = this.createHotkeyRow( new HotkeyRowData( modelEntry.key, modelEntry.summary, modelEntry.accelName ) ); row.connect('accel-changed', (_, value) => { this.settings.set_strv(modelEntry.key, [value]); }); this.append(row); }); } createHotkeyRow(obj: GObject.Object): Gtk.Widget { const data = obj as HotkeyRowData; return new HotkeyListBoxRow(data.key, data.summary, data.accelName); } } //Todo: Replace Gtk TreeView with Gtk ListBox @registerGObjectClass class HotkeyListBoxRow extends Gtk.ListBoxRow { static metaInfo: GObject.MetaInfo = { GTypeName: 'HotkeyListBoxRow', Template: Me.dir.get_child('hotkey_list_box_row.ui').get_uri(), InternalChildren: ['accel_label', 'hotkey_label', 'dialog'], Signals: { accel_changed: { param_types: [GObject.TYPE_STRING], accumulator: 0, }, }, }; // Note: will be created by gjs from the InternalChildren meta info property private declare _accel_label: Gtk.Label; private declare _hotkey_label: Gtk.Label; private declare _dialog: Gtk.Dialog; key: string; constructor(key: string, hotkeyName: string, accel: string) { super(); this.key = key; this._accel_label.set_text(accel); this._hotkey_label.set_text(hotkeyName); this.connect('activate', () => this.openDialog()); } openDialog() { this._dialog.transient_for = this.get_root() as Gtk.Window; this._dialog.present(); ( assertNotNull(this.get_root()).get_surface() as Gdk.Toplevel ).inhibit_system_shortcuts(null); } onKeyPressed( _widget: Gtk.Widget, keyval: number, keycode: number, state: Gdk.ModifierType ) { let mask = state & Gtk.accelerator_get_default_mod_mask(); mask &= ~Gdk.ModifierType.LOCK_MASK; if (mask === 0 && keyval === Gdk.KEY_Escape) { this.closeDialog(); return Gdk.EVENT_STOP; } if (mask === 0 && keyval === Gdk.KEY_BackSpace) { this._accel_label.set_text('Disabled'); this.emit('accel-changed', ''); this.closeDialog(); return Gdk.EVENT_STOP; } if (!Gtk.accelerator_valid(keyval, mask)) return Gdk.EVENT_STOP; const accel = Gtk.accelerator_name_with_keycode( null, keyval, keycode, mask ); this._accel_label.set_text(Gtk.accelerator_get_label(keyval, mask)); this.emit('accel-changed', accel); /* this.keybinding = */ this.closeDialog(); return Gdk.EVENT_STOP; } closeDialog() { ( assertNotNull(this.get_root()).get_surface() as Gdk.Toplevel ).restore_system_shortcuts(); this._dialog.close(); } } @registerGObjectClass class SettingCategoryListBox extends Gtk.Box { static metaInfo: GObject.MetaInfo = { GTypeName: 'SettingCategoryListBox', Template: Me.dir.get_child('setting_category_list_box.ui').get_uri(), Properties: { title: GObject.ParamSpec.string( 'title', 'Title', 'The title of the category', GObject.ParamFlags.READWRITE, '' ), }, InternalChildren: ['title_label', 'list_box'], }; // Note: will be created by gjs from the InternalChildren meta info property private declare _title_label: Gtk.Label; // Note: will be created by gjs from the InternalChildren meta info property private declare _list_box: Gtk.ListBox; public settings: Gio.Settings; constructor(title: string, schema: string) { super(); this.settings = new Gio.Settings({ settings_schema: schemaSource.lookup(schema, false) || undefined, }); this.title = title; } get title(): string { return this._title_label.get_text(); } set title(value: string) { this._title_label.set_markup(`<span size="medium">${value}</span>`); } addSetting(key: string, type: WidgetType, customWidget?: Gtk.Widget) { const settingKey = this.settings.settings_schema.get_key(key); const summary = settingKey.get_summary(); const description = settingKey.get_description(); let widget: Gtk.Widget; switch (type) { case WidgetType.BOOLEAN: widget = new Gtk.Switch(); this.settings.bind( key, widget, 'active', Gio.SettingsBindFlags.DEFAULT ); break; case WidgetType.COMBO: const combo = (widget = new Gtk.ComboBoxText()); const a = settingKey .get_range() .get_child_value(1) .recursiveUnpack() as any[]; a.forEach((value) => { combo.append(value, value); }); this.settings.bind( key, widget, 'active-id', Gio.SettingsBindFlags.DEFAULT ); break; case WidgetType.COLOR: { const btn = (widget = new Gtk.ColorButton()); const rgba = new Gdk.RGBA(); rgba.parse(this.settings.get_string(key)); btn.set_rgba(rgba); widget.connect('color-set', (button) => { const rgba = button.get_rgba(); const css = rgba.to_string(); const hexString = cssHexString(css); this.settings.set_string(key, hexString); }); break; } case WidgetType.INT: const spin = (widget = Gtk.SpinButton.new_with_range( 0, 1000, 1 )); this.settings.bind( key, spin.get_adjustment(), 'value', Gio.SettingsBindFlags.DEFAULT ); break; case WidgetType.DECIMAL: const spin2 = (widget = Gtk.SpinButton.new_with_range( 0, 1, 0.1 )); this.settings.bind( key, spin2.get_adjustment(), 'value', Gio.SettingsBindFlags.DEFAULT ); break; case WidgetType.INPUT: widget = Gtk.Entry.new(); this.settings.bind( key, widget, 'text', Gio.SettingsBindFlags.DEFAULT ); break; case WidgetType.CUSTOM: if (customWidget == undefined) { throw new Error('Supplied custom widget is undefined'); } widget = customWidget; break; } widget.set_valign(Gtk.Align.CENTER); const row = new SettingListBoxRow(summary, description, widget); this._list_box.append(row); } } @registerGObjectClass class PrefsWidget extends Gtk.Box { static metaInfo: GObject.MetaInfo = { GTypeName: 'PrefsWidget', Template: Me.dir.get_child('prefs.ui').get_uri(), InternalChildren: ['settings_box'], }; // Note: will be created by gjs from the InternalChildren meta info property private declare _settings_box: Gtk.Box; constructor() { super(); const theme = new SettingCategoryListBox( 'Theme', 'org.gnome.shell.extensions.materialshell.theme' ); theme.addSetting('theme', WidgetType.COMBO); theme.addSetting('primary-color', WidgetType.COLOR); theme.addSetting('vertical-panel-position', WidgetType.COMBO); theme.addSetting('horizontal-panel-position', WidgetType.COMBO); theme.addSetting('panel-size', WidgetType.INT); theme.addSetting('panel-opacity', WidgetType.INT); theme.addSetting('panel-icon-style', WidgetType.COMBO); theme.addSetting('panel-icon-color', WidgetType.BOOLEAN); theme.addSetting('taskbar-item-style', WidgetType.COMBO); theme.addSetting('surface-opacity', WidgetType.INT); theme.addSetting('blur-background', WidgetType.BOOLEAN); theme.addSetting('clock-horizontal', WidgetType.BOOLEAN); theme.addSetting('clock-app-launcher', WidgetType.BOOLEAN); theme.addSetting('focus-effect', WidgetType.COMBO); this._settings_box.append(theme); const tweaks = new SettingCategoryListBox( 'Tweaks', 'org.gnome.shell.extensions.materialshell.tweaks' ); tweaks.addSetting('cycle-through-windows', WidgetType.BOOLEAN); tweaks.addSetting('cycle-through-workspaces', WidgetType.BOOLEAN); tweaks.addSetting('disable-notifications', WidgetType.BOOLEAN); tweaks.addSetting('enable-persistence', WidgetType.BOOLEAN); this._settings_box.append(tweaks); const layouts = new SettingCategoryListBox( 'Tiling layouts', 'org.gnome.shell.extensions.materialshell.layouts' ); const tilingLayouts = [ 'maximize', 'split', 'half', 'half-horizontal', 'half-vertical', 'ratio', 'grid', 'float', 'simple', 'simple-horizontal', 'simple-vertical', ]; layouts.addSetting( 'default-layout', WidgetType.CUSTOM, getDefaultLayoutComboBox(tilingLayouts, layouts.settings) ); tilingLayouts.forEach((layoutKey) => { layouts.addSetting(layoutKey, WidgetType.BOOLEAN); if (layoutKey === 'ratio') { layouts.addSetting('ratio-value', WidgetType.DECIMAL); } }); layouts.addSetting('gap', WidgetType.INT); layouts.addSetting('use-screen-gap', WidgetType.BOOLEAN); layouts.addSetting('screen-gap', WidgetType.INT); layouts.addSetting('tween-time', WidgetType.DECIMAL); layouts.addSetting('windows-excluded', WidgetType.INPUT); this._settings_box.append(layouts); } } function cssHexString(css: string) { let rrggbb = '#'; let start: number | undefined = undefined; for (let loop = 0; loop < 3; loop++) { let end = 0; let xx = ''; for (let loop = 0; loop < 2; loop++) { for (;;) { const x = css.slice(end, end + 1); if (x == '(' || x == ',' || x == ')') break; end++; } if (loop == 0) { end++; start = end; } } assert(start !== undefined, 'true by construction'); xx = parseInt(css.slice(start, end)).toString(16); if (xx.length == 1) xx = `0${xx}`; rrggbb += xx; css = css.slice(end); } return rrggbb; } function getDefaultLayoutComboBox( tilingLayouts: string[], setting: Gio.Settings ) { const widget = new Gtk.ComboBoxText(); const refreshComboBox = () => { widget.remove_all(); tilingLayouts.forEach((layoutKey) => { if (setting.get_boolean(layoutKey)) { widget.append(layoutKey, layoutKey); } }); }; tilingLayouts.forEach((layoutKey) => { if (setting.get_boolean(layoutKey)) { widget.append(layoutKey, layoutKey); } setting.connect(`changed::${layoutKey}`, refreshComboBox); }); setting.bind( 'default-layout', widget as any as GObject.Object, 'active-id', Gio.SettingsBindFlags.DEFAULT ); return widget; }
the_stack
import { Observable, Application, Button, ShowModalOptions, View } from '@nativescript/core'; import { Mediafilepicker, ImagePickerOptions, VideoPickerOptions, AudioPickerOptions, FilePickerOptions } from 'nativescript-mediafilepicker'; declare const AVCaptureSessionPreset1920x1080, AVCaptureSessionPresetHigh, AVCaptureSessionPresetLow, kUTTypePDF, kUTTypeText; export class HelloWorldModel extends Observable { private _hostView: View; constructor(hostView?: View) { super(); this._hostView = hostView; } public openModal(args) { const mainView: Button = <Button>args.object; const option: ShowModalOptions = { context: {}, closeCallback: () => { }, fullscreen: true }; mainView.showModal("modal-page", option); } /** * openImagePicker */ public openImagePicker() { let t = this; let options: ImagePickerOptions = { android: { isCaptureMood: false, isNeedCamera: true, maxNumberFiles: 10, isNeedFolderList: true }, ios: { isCaptureMood: false, isNeedCamera: true, maxNumberFiles: 10, hostView: this._hostView } }; let mediafilepicker = new Mediafilepicker(); mediafilepicker.openImagePicker(options); mediafilepicker.on("getFiles", function (res) { let results = res.object.get('results'); console.dir(results); if (results) { for (let i = 0; i < results.length; i++) { let result = results[i]; let file = result.file; console.log(file); if (result.file && Application.ios && !options.ios.isCaptureMood) { // We can copy the image to app directory for futher proccess. This will create a new directory name "filepicker". So, after your work you can delete it for reducing memory use. /* let fileName = file.replace(/^.*[\/]/, ''); mediafilepicker.copyPHImageToAppDirectory(result.rawData, fileName).then((res: any) => { console.dir(res); }).catch((e) => { console.dir(e); })*/ // or can get UIImage to display /*mediafilepicker.convertPHImageToUIImage(result.rawData).then(res => { console.log(res); });*/ } else if (result.file && Application.ios) { // So we have taken image & will get UIImage // We can copy it to app directory, if need let fileName = "myTmpImage.jpg"; mediafilepicker.copyUIImageToAppDirectory(result.rawData, fileName).then((res: any) => { console.dir(res); }).catch(e => { console.dir(e); }); } } } }); // for iOS iCloud downloading status mediafilepicker.on("exportStatus", function (res) { let msg = res.object.get('msg'); console.log(msg); }); mediafilepicker.on("error", function (res) { let msg = res.object.get('msg'); console.log(msg); }); mediafilepicker.on("cancel", function (res) { let msg = res.object.get('msg'); console.log(msg); }); } /** * openVideoPicker */ public openVideoPicker() { let allowedVideoQualities = []; if (Application.ios) { allowedVideoQualities = [AVCaptureSessionPreset1920x1080, AVCaptureSessionPresetHigh]; // get more from here: https://developer.apple.com/documentation/avfoundation/avcapturesessionpreset?language=objc } let options: VideoPickerOptions = { android: { isCaptureMood: false, isNeedCamera: true, maxNumberFiles: 2, isNeedFolderList: true, maxDuration: 20, }, ios: { isCaptureMood: false, hostView: this._hostView } }; let mediafilepicker = new Mediafilepicker(); mediafilepicker.openVideoPicker(options); mediafilepicker.on("getFiles", function (res) { let results = res.object.get('results'); console.dir(results); if (results) { for (let i = 0; i < results.length; i++) { let result = results[i]; console.dir(result); let file = result.file; console.log(file); } } }); // for iOS iCloud downloading status mediafilepicker.on("exportStatus", function (res) { let msg = res.object.get('msg'); console.log(msg); }); mediafilepicker.on("error", function (res) { let msg = res.object.get('msg'); console.log(msg); }); mediafilepicker.on("cancel", function (res) { let msg = res.object.get('msg'); console.log(msg); }); } /** * audio */ public openAudioPicker() { let options: AudioPickerOptions = { android: { isCaptureMood: false, isNeedRecorder: true, maxNumberFiles: 2, isNeedFolderList: true, maxSize: 102400 // Maximum size in bytes }, ios: { isCaptureMood: false, maxNumberFiles: 5, audioMaximumDuration: 10, hostView: this._hostView } }; let mediafilepicker = new Mediafilepicker(); mediafilepicker.openAudioPicker(options); mediafilepicker.on("getFiles", function (res) { let results = res.object.get('results'); console.dir(results); if (results) { for (let i = 0; i < results.length; i++) { let result = results[i]; console.log(result); if (result.file && Application.ios && !options.ios.isCaptureMood) { // We can copy the audio to app directory for futher proccess. This will create a new directory name "filepicker". So, after your work you can delete it for reducing memory use. let fileName = "tmpFile.m4a"; // use .m4a // copying file will require some time mediafilepicker.copyMPMediaFileToAPPDirectory(result.rawData, fileName).then((res) => { console.dir(res); }).catch((err) => { console.dir(err); }); } else if (result.file && Application.ios && options.ios.isCaptureMood) { // So we have recorded file in APP directory console.log(result.file); } } } }); mediafilepicker.on("error", function (res) { let msg = res.object.get('msg'); console.log(msg); }); mediafilepicker.on("cancel", function (res) { let msg = res.object.get('msg'); console.log(msg); }); } /** * openCustomFiles */ public openCustomFilesPicker() { let extensions = []; if (Application.ios) { extensions = [kUTTypePDF, kUTTypeText]; // you can get more types from here: https://developer.apple.com/documentation/mobilecoreservices/uttype } else { extensions = ['txt', 'pdf']; } let options: FilePickerOptions = { android: { extensions: extensions, maxNumberFiles: 2 }, ios: { extensions: extensions, multipleSelection: true, hostView: this._hostView } }; let mediafilepicker = new Mediafilepicker(); mediafilepicker.openFilePicker(options); mediafilepicker.on("getFiles", function (res) { let results = res.object.get('results'); console.dir(results); if (results) { for (let i = 0; i < results.length; i++) { let result = results[i]; console.log(result.file); } } }); mediafilepicker.on("error", function (res) { let msg = res.object.get('msg'); console.log(msg); }); mediafilepicker.on("cancel", function (res) { let msg = res.object.get('msg'); console.log(msg); }); } /** * imageCapture */ public imageCapture() { let options: ImagePickerOptions = { android: { isCaptureMood: true, }, ios: { isCaptureMood: true, hostView: this._hostView } }; let mediafilepicker = new Mediafilepicker(); mediafilepicker.openImagePicker(options); mediafilepicker.on("getFiles", function (res) { let results = res.object.get('results'); console.dir(results); }); mediafilepicker.on("error", function (res) { let msg = res.object.get('msg'); console.log(msg); }); mediafilepicker.on("cancel", function (res) { let msg = res.object.get('msg'); console.log(msg); }); } /** * videoCapture */ public videoCapture() { let allowedVideoQualities = []; if (Application.ios) { allowedVideoQualities = [AVCaptureSessionPreset1920x1080, AVCaptureSessionPresetHigh]; // get more from here: https://developer.apple.com/documentation/avfoundation/avcapturesessionpreset?language=objc } let options: VideoPickerOptions = { android: { isCaptureMood: true, maxDuration: 20, videoQuality: 1, }, ios: { isCaptureMood: true, videoMaximumDuration: 10, allowedVideoQualities: allowedVideoQualities, hostView: this._hostView } }; let mediafilepicker = new Mediafilepicker(); mediafilepicker.openVideoPicker(options); mediafilepicker.on("getFiles", function (res) { let results = res.object.get('results'); console.dir(results); }); mediafilepicker.on("error", function (res) { let msg = res.object.get('msg'); console.log(msg); }); mediafilepicker.on("cancel", function (res) { let msg = res.object.get('msg'); console.log(msg); }); } /** * audioCapture */ public audioCapture() { let options: AudioPickerOptions = { android: { isCaptureMood: true, maxSize: 102400 // Maximum size of recorded file in bytes. 5900 = ~ 1 second }, ios: { isCaptureMood: true, maxNumberFiles: 5, audioMaximumDuration: 10, hostView: this._hostView } }; let mediafilepicker = new Mediafilepicker(); mediafilepicker.openAudioPicker(options); mediafilepicker.on("getFiles", function (res) { let results = res.object.get('results'); console.dir(results); }); mediafilepicker.on("error", function (res) { let msg = res.object.get('msg'); console.log(msg); }); mediafilepicker.on("cancel", function (res) { let msg = res.object.get('msg'); console.log(msg); }); } }
the_stack
export default function TileBoundingRegion(options) { //>>includeStart('debug', pragmas.debug); Check.typeOf.object('options', options); Check.typeOf.object('options.rectangle', options.rectangle); //>>includeEnd('debug'); this.rectangle = Rectangle.clone(options.rectangle); this.minimumHeight = defaultValue(options.minimumHeight, 0.0); this.maximumHeight = defaultValue(options.maximumHeight, 0.0); /** * The world coordinates of the southwest corner of the tile's rectangle. * * @type {Cartesian3} * @default Cartesian3() */ this.southwestCornerCartesian = new Cartesian3(); /** * The world coordinates of the northeast corner of the tile's rectangle. * * @type {Cartesian3} * @default Cartesian3() */ this.northeastCornerCartesian = new Cartesian3(); /** * A normal that, along with southwestCornerCartesian, defines a plane at the western edge of * the tile. Any position above (in the direction of the normal) this plane is outside the tile. * * @type {Cartesian3} * @default Cartesian3() */ this.westNormal = new Cartesian3(); /** * A normal that, along with southwestCornerCartesian, defines a plane at the southern edge of * the tile. Any position above (in the direction of the normal) this plane is outside the tile. * Because points of constant latitude do not necessary lie in a plane, positions below this * plane are not necessarily inside the tile, but they are close. * * @type {Cartesian3} * @default Cartesian3() */ this.southNormal = new Cartesian3(); /** * A normal that, along with northeastCornerCartesian, defines a plane at the eastern edge of * the tile. Any position above (in the direction of the normal) this plane is outside the tile. * * @type {Cartesian3} * @default Cartesian3() */ this.eastNormal = new Cartesian3(); /** * A normal that, along with northeastCornerCartesian, defines a plane at the eastern edge of * the tile. Any position above (in the direction of the normal) this plane is outside the tile. * Because points of constant latitude do not necessary lie in a plane, positions below this * plane are not necessarily inside the tile, but they are close. * * @type {Cartesian3} * @default Cartesian3() */ this.northNormal = new Cartesian3(); var ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84); computeBox(this, options.rectangle, ellipsoid); if (defaultValue(options.computeBoundingVolumes, true)) { // An oriented bounding box that encloses this tile's region. This is used to calculate tile visibility. this._orientedBoundingBox = OrientedBoundingBox.fromRectangle( this.rectangle, this.minimumHeight, this.maximumHeight, ellipsoid ); this._boundingSphere = BoundingSphere.fromOrientedBoundingBox(this._orientedBoundingBox); } } defineProperties(TileBoundingRegion.prototype, { /** * The underlying bounding volume * * @memberof TileBoundingRegion.prototype * * @type {Object} * @readonly */ boundingVolume: { get: function() { return this._orientedBoundingBox; } }, /** * The underlying bounding sphere * * @memberof TileBoundingRegion.prototype * * @type {BoundingSphere} * @readonly */ boundingSphere: { get: function() { return this._boundingSphere; } } }); var cartesian3Scratch = new Cartesian3(); var cartesian3Scratch2 = new Cartesian3(); var cartesian3Scratch3 = new Cartesian3(); var eastWestNormalScratch = new Cartesian3(); var westernMidpointScratch = new Cartesian3(); var easternMidpointScratch = new Cartesian3(); var cartographicScratch = new Cartographic(); var planeScratch = new Plane(Cartesian3.UNIT_X, 0.0); var rayScratch = new Ray(); function computeBox(tileBB, rectangle, ellipsoid) { ellipsoid.cartographicToCartesian( Rectangle.southwest(rectangle), tileBB.southwestCornerCartesian ); ellipsoid.cartographicToCartesian( Rectangle.northeast(rectangle), tileBB.northeastCornerCartesian ); // The middle latitude on the western edge. cartographicScratch.longitude = rectangle.west; cartographicScratch.latitude = (rectangle.south + rectangle.north) * 0.5; cartographicScratch.height = 0.0; var westernMidpointCartesian = ellipsoid.cartographicToCartesian( cartographicScratch, westernMidpointScratch ); // Compute the normal of the plane on the western edge of the tile. var westNormal = Cartesian3.cross(westernMidpointCartesian, Cartesian3.UNIT_Z, cartesian3Scratch); Cartesian3.normalize(westNormal, tileBB.westNormal); // The middle latitude on the eastern edge. cartographicScratch.longitude = rectangle.east; var easternMidpointCartesian = ellipsoid.cartographicToCartesian( cartographicScratch, easternMidpointScratch ); // Compute the normal of the plane on the eastern edge of the tile. var eastNormal = Cartesian3.cross(Cartesian3.UNIT_Z, easternMidpointCartesian, cartesian3Scratch); Cartesian3.normalize(eastNormal, tileBB.eastNormal); // Compute the normal of the plane bounding the southern edge of the tile. var westVector = Cartesian3.subtract( westernMidpointCartesian, easternMidpointCartesian, cartesian3Scratch ); var eastWestNormal = Cartesian3.normalize(westVector, eastWestNormalScratch); var south = rectangle.south; var southSurfaceNormal; if (south > 0.0) { // Compute a plane that doesn't cut through the tile. cartographicScratch.longitude = (rectangle.west + rectangle.east) * 0.5; cartographicScratch.latitude = south; var southCenterCartesian = ellipsoid.cartographicToCartesian( cartographicScratch, rayScratch.origin ); Cartesian3.clone(eastWestNormal, rayScratch.direction); var westPlane = Plane.fromPointNormal( tileBB.southwestCornerCartesian, tileBB.westNormal, planeScratch ); // Find a point that is on the west and the south planes IntersectionTests.rayPlane(rayScratch, westPlane, tileBB.southwestCornerCartesian); southSurfaceNormal = ellipsoid.geodeticSurfaceNormal(southCenterCartesian, cartesian3Scratch2); } else { southSurfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic( Rectangle.southeast(rectangle), cartesian3Scratch2 ); } var southNormal = Cartesian3.cross(southSurfaceNormal, westVector, cartesian3Scratch3); Cartesian3.normalize(southNormal, tileBB.southNormal); // Compute the normal of the plane bounding the northern edge of the tile. var north = rectangle.north; var northSurfaceNormal; if (north < 0.0) { // Compute a plane that doesn't cut through the tile. cartographicScratch.longitude = (rectangle.west + rectangle.east) * 0.5; cartographicScratch.latitude = north; var northCenterCartesian = ellipsoid.cartographicToCartesian( cartographicScratch, rayScratch.origin ); Cartesian3.negate(eastWestNormal, rayScratch.direction); var eastPlane = Plane.fromPointNormal( tileBB.northeastCornerCartesian, tileBB.eastNormal, planeScratch ); // Find a point that is on the east and the north planes IntersectionTests.rayPlane(rayScratch, eastPlane, tileBB.northeastCornerCartesian); northSurfaceNormal = ellipsoid.geodeticSurfaceNormal(northCenterCartesian, cartesian3Scratch2); } else { northSurfaceNormal = ellipsoid.geodeticSurfaceNormalCartographic( Rectangle.northwest(rectangle), cartesian3Scratch2 ); } var northNormal = Cartesian3.cross(westVector, northSurfaceNormal, cartesian3Scratch3); Cartesian3.normalize(northNormal, tileBB.northNormal); } var southwestCornerScratch = new Cartesian3(); var northeastCornerScratch = new Cartesian3(); var negativeUnitY = new Cartesian3(0.0, -1.0, 0.0); var negativeUnitZ = new Cartesian3(0.0, 0.0, -1.0); var vectorScratch = new Cartesian3(); /** * Gets the distance from the camera to the closest point on the tile. This is used for level of detail selection. * * @param {FrameState} frameState The state information of the current rendering frame. * @returns {Number} The distance from the camera to the closest point on the tile, in meters. */ TileBoundingRegion.prototype.distanceToCamera = function(frameState) { //>>includeStart('debug', pragmas.debug); Check.defined('frameState', frameState); //>>includeEnd('debug'); var camera = frameState.camera; var cameraCartesianPosition = camera.positionWC; var cameraCartographicPosition = camera.positionCartographic; var result = 0.0; if (!Rectangle.contains(this.rectangle, cameraCartographicPosition)) { var southwestCornerCartesian = this.southwestCornerCartesian; var northeastCornerCartesian = this.northeastCornerCartesian; var westNormal = this.westNormal; var southNormal = this.southNormal; var eastNormal = this.eastNormal; var northNormal = this.northNormal; if (frameState.mode !== SceneMode.SCENE3D) { southwestCornerCartesian = frameState.mapProjection.project( Rectangle.southwest(this.rectangle), southwestCornerScratch ); southwestCornerCartesian.z = southwestCornerCartesian.y; southwestCornerCartesian.y = southwestCornerCartesian.x; southwestCornerCartesian.x = 0.0; northeastCornerCartesian = frameState.mapProjection.project( Rectangle.northeast(this.rectangle), northeastCornerScratch ); northeastCornerCartesian.z = northeastCornerCartesian.y; northeastCornerCartesian.y = northeastCornerCartesian.x; northeastCornerCartesian.x = 0.0; westNormal = negativeUnitY; eastNormal = Cartesian3.UNIT_Y; southNormal = negativeUnitZ; northNormal = Cartesian3.UNIT_Z; } var vectorFromSouthwestCorner = Cartesian3.subtract( cameraCartesianPosition, southwestCornerCartesian, vectorScratch ); var distanceToWestPlane = Cartesian3.dot(vectorFromSouthwestCorner, westNormal); var distanceToSouthPlane = Cartesian3.dot(vectorFromSouthwestCorner, southNormal); var vectorFromNortheastCorner = Cartesian3.subtract( cameraCartesianPosition, northeastCornerCartesian, vectorScratch ); var distanceToEastPlane = Cartesian3.dot(vectorFromNortheastCorner, eastNormal); var distanceToNorthPlane = Cartesian3.dot(vectorFromNortheastCorner, northNormal); if (distanceToWestPlane > 0.0) { result += distanceToWestPlane * distanceToWestPlane; } else if (distanceToEastPlane > 0.0) { result += distanceToEastPlane * distanceToEastPlane; } if (distanceToSouthPlane > 0.0) { result += distanceToSouthPlane * distanceToSouthPlane; } else if (distanceToNorthPlane > 0.0) { result += distanceToNorthPlane * distanceToNorthPlane; } } var cameraHeight; var minimumHeight; var maximumHeight; if (frameState.mode === SceneMode.SCENE3D) { cameraHeight = cameraCartographicPosition.height; minimumHeight = this.minimumHeight; maximumHeight = this.maximumHeight; } else { cameraHeight = cameraCartesianPosition.x; minimumHeight = 0.0; maximumHeight = 0.0; } if (cameraHeight > maximumHeight) { var distanceAboveTop = cameraHeight - maximumHeight; result += distanceAboveTop * distanceAboveTop; } else if (cameraHeight < minimumHeight) { var distanceBelowBottom = minimumHeight - cameraHeight; result += distanceBelowBottom * distanceBelowBottom; } return Math.sqrt(result); }; /** * Determines which side of a plane this box is located. * * @param {Plane} plane The plane to test against. * @returns {Intersect} {@link Intersect.INSIDE} if the entire box is on the side of the plane * the normal is pointing, {@link Intersect.OUTSIDE} if the entire box is * on the opposite side, and {@link Intersect.INTERSECTING} if the box * intersects the plane. */ TileBoundingRegion.prototype.intersectPlane = function(plane) { //>>includeStart('debug', pragmas.debug); Check.defined('plane', plane); //>>includeEnd('debug'); return this._orientedBoundingBox.intersectPlane(plane); }; /** * Creates a debug primitive that shows the outline of the tile bounding region. * * @param {Color} color The desired color of the primitive's mesh * @return {Primitive} * * @private */ TileBoundingRegion.prototype.createDebugVolume = function(color) { //>>includeStart('debug', pragmas.debug); Check.defined('color', color); //>>includeEnd('debug'); var modelMatrix = new Matrix4.clone(Matrix4.IDENTITY); var geometry = new RectangleOutlineGeometry({ rectangle: this.rectangle, height: this.minimumHeight, extrudedHeight: this.maximumHeight }); var instance = new GeometryInstance({ geometry: geometry, id: 'outline', modelMatrix: modelMatrix, attributes: { color: ColorGeometryInstanceAttribute.fromColor(color) } }); return new Primitive({ geometryInstances: instance, appearance: new PerInstanceColorAppearance({ translucent: false, flat: true }), asynchronous: false }); };
the_stack
import Component from 'vue-class-component'; import Vue from 'vue'; import {shell} from 'electron'; import * as fs from 'fs'; import * as marked from 'marked'; import * as dompurify from 'dompurify'; import { } from '../../../Config'; import { trimBetweenTags } from 'extraterm-trim-between-tags'; import { ExtensionMetadataAndState } from './ExtensionMetadataAndStateType'; import { ExtensionCard, EVENT_ENABLE_EXTENSION, EVENT_DISABLE_EXTENSION } from './ExtensionCardUi'; interface MenuPair { context: string; command: string; } @Component( { components: { "extension-card": ExtensionCard, }, props: { extension: Object, }, template: trimBetweenTags(` <div v-on:click.stop.prevent="onClick($event)"> <extension-card :extension="extension" :showDetailsButton="false" v-on:enable-extension="onEnableExtension" v-on:disable-extension="onDisableExtension" ></extension-card> <p v-if="extension.metadata.homepage != null"> <i class="fas fa-home"></i> Home page: <a :href="extension.metadata.homepage">{{extension.metadata.homepage}}</a> </p> <div class="gui-layout width-100pc cols-1-1"> <h3 class="sub-tab" v-bind:class="{selected: subtab==='details'}" v-on:click.stop="subtab = 'details'"> Details </h3> <h3 class="sub-tab" v-bind:class="{selected: subtab==='contributions'}" v-on:click.stop="subtab = 'contributions'"> Feature Contributions </h3> </div> <div v-if="subtab === 'details'" v-html="readmeText"> </div> <div v-if="subtab === 'contributions'"> <template v-if="extension.metadata.contributes.commands.length !== 0"> <h4>Commands</h4> <table class="width-100pc cols-1-1"> <thead> <tr> <th>Title</th> <th>Command</th> </tr> </thead> <tbody> <tr v-for="command in extension.metadata.contributes.commands"> <td>{{ command.title }}</td> <td>{{ command.command }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.keybindings.length !== 0"> <h4>Keybindings</h4> <table class="width-100pc"> <thead> <tr> <th>Path</th> </tr> </thead> <tbody> <tr v-for="keybindings in extension.metadata.contributes.keybindings"> <td>{{ keybindings.path }}</td> </tr> </tbody> </table> </template> <template v-if="menus.length !== 0"> <h4>Menus</h4> <table class="width-100pc cols-1-1"> <thead> <tr> <th>Context</th> <th>Command</th> </tr> </thead> <tbody> <tr v-for="menuPair in menus"> <td>{{ menuPair.context }}</td> <td>{{ menuPair.command }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.sessionBackends.length !== 0"> <h4>Session backends</h4> <table class="width-100pc cols-1-1"> <thead> <tr> <th>Name</th> <th>Type</th> </tr> </thead> <tbody> <tr v-for="backend in extension.metadata.contributes.sessionBackends"> <td>{{ backend.name }}</td> <td>{{ backend.type }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.sessionEditors.length !== 0"> <h4>Session editors</h4> <table class="width-100pc cols-1-1"> <thead> <tr> <th>Name</th> <th>Type</th> </tr> </thead> <tbody> <tr v-for="sessionEditor in extension.metadata.contributes.sessionEditors"> <td>{{ sessionEditor.name }}</td> <td>{{ sessionEditor.type }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.sessionSettings.length !== 0"> <h4>Session settings</h4> <table class="width-100pc cols-1-1"> <thead> <tr> <th>Name</th> <th>ID</th> </tr> </thead> <tbody> <tr v-for="sessionSettings in extension.metadata.contributes.sessionSettings"> <td>{{ sessionSettings.name }}</td> <td>{{ sessionSettings.id }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.syntaxThemes.length !== 0"> <h4>Syntax themes</h4> <table class="width-100pc"> <thead> <tr> <th>Path</th> </tr> </thead> <tbody> <tr v-for="syntaxTheme in extension.metadata.contributes.syntaxThemes"> <td>{{ syntaxTheme.path }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.syntaxThemeProviders.length !== 0"> <h4>Syntax theme providers</h4> <table class="width-100pc cols-1-1"> <thead> <tr> <th>Name</th> <th>Formats</th> </tr> </thead> <tbody> <tr v-for="syntaxThemeProvider in extension.metadata.contributes.syntaxThemeProviders"> <td>{{ syntaxThemeProvider.name }}</td> <td>{{ syntaxThemeProvider.humanFormatNames.join(", ") }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.tabTitleWidgets.length !== 0"> <h4>Tab title widgets</h4> <table class="width-100pc"> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> <tr v-for="tabTitleWidget in extension.metadata.contributes.tabTitleWidgets"> <td>{{ tabTitleWidget.name }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.terminalBorderWidgets.length !== 0"> <h4>Terminal border widgets</h4> <table class="width-100pc cols-1-1"> <thead> <tr> <th>Name</th> <th>Border</th> </tr> </thead> <tbody> <tr v-for="terminalBorderWidget in extension.metadata.contributes.terminalBorderWidgets"> <td>{{ terminalBorderWidget.name }}</td> <td>{{ terminalBorderWidget.border }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.terminalThemes.length !== 0"> <h4>Terminal themes</h4> <table class="width-100pc"> <thead> <tr> <th>Path</th> </tr> </thead> <tbody> <tr v-for="terminalTheme in extension.metadata.contributes.terminalThemes"> <td>{{ terminalTheme.path }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.terminalThemeProviders.length !== 0"> <h4>Terminal themes</h4> <table class="width-100pc cols-1-1"> <thead> <tr> <th>Name</th> <th>Formats</th> </tr> </thead> <tbody> <tr v-for="terminalThemeProvider in extension.metadata.contributes.terminalThemeProviders"> <td>{{ terminalThemeProvider.name }}</td> <td>{{ terminalThemeProvider.humanFormatNames.join(", ") }}</td> </tr> </tbody> </table> </template> <template v-if="extension.metadata.contributes.viewers.length !== 0"> <h4>Viewers</h4> <table class="width-100pc cols-1-1"> <thead> <tr> <th>Name</th> <th>Mime-types</th> </tr> </thead> <tbody> <tr v-for="viewer in extension.metadata.contributes.viewers"> <td>{{ viewer.name }}</td> <td>{{ viewer.mimeTypes.join(", ") }}</td> </tr> </tbody> </table> </template> </div> </div> `) } ) export class ExtensionDetails extends Vue { extension: ExtensionMetadataAndState; rawReadmeText: string = null; loadingReadmeText: boolean = false; subtab: 'details' | 'contributions' = 'details'; constructor() { super(); } get readmeText(): string { if (! this.loadingReadmeText) { if (this.extension.metadata.readmePath != null) { this.loadingReadmeText = true; fs.readFile(this.extension.metadata.readmePath, {encoding: "utf8"}, (err: NodeJS.ErrnoException, data: string) => { if (err != null) { this.rawReadmeText = "<p>(Missing)</p>"; return; } this.rawReadmeText = dompurify.sanitize(marked(data)); }); } else { this.rawReadmeText = "<p>(Missing)</p>"; } } return this.rawReadmeText == null ? "" : this.rawReadmeText; } get menus(): MenuPair[] { const menus = this.extension.metadata.contributes.menus; return [ ...menus.commandPalette.map(m => ({ context: "Command palette", command: m.command })), ...menus.contextMenu.map(m => ({ context: "Context menu", command: m.command })), ...menus.emptyPane.map(m => ({ context: "Empty pane", command: m.command })), ...menus.newTerminal.map(m => ({ context: "New terminal", command: m.command })), ...menus.terminalTab.map(m => ({ context: "Terminal tab", command: m.command })), ]; } onClick(ev: MouseEvent): void { if ((<HTMLElement> ev.target).tagName === "A") { const href = (<HTMLAnchorElement> ev.target).href; shell.openExternal(href); } } onEnableExtension(extensionName: string): void { this.$emit(EVENT_ENABLE_EXTENSION, extensionName); } onDisableExtension(extensionName: string): void { this.$emit(EVENT_DISABLE_EXTENSION, extensionName); } }
the_stack
import * as _ from 'lodash'; import * as errors from '../../shared/utils/errors'; import Session from './session'; import Cursor from './cursor'; import { AttachedChildInfo } from './document'; import { Row, Col, Char, Chars, SerializedBlock, SerializedPath, Line } from './types'; import Path from './path'; // validate inserting id as a child of parent_id const validateRowInsertion = async function( session: Session, parent_id: number, id: number, options: {noSiblingCheck?: boolean} = {} ) { // check that there won't be doubled siblings if (!options.noSiblingCheck) { if (await session.document._hasChild(parent_id, id)) { session.showMessage('Cloned rows cannot be inserted as siblings', {text_class: 'error'}); return false; } } // check that there are no cycles // Precondition: tree is not already circular // It is sufficient to check if the row is an ancestor of the new parent, // because if there was a clone underneath the row which was an ancestor of 'parent', // then 'row' would also be an ancestor of 'parent'. if (_.includes(await session.document.allAncestors(parent_id, { inclusive: true }), id)) { session.showMessage('Cloned rows cannot be nested under themselves', {text_class: 'error'}); return false; } return true; }; export default class Mutation { public str() { return ''; } public async validate(_session: Session): Promise<boolean> { return true; } public async mutate(_session: Session): Promise<void> { throw new errors.NotImplemented(); } public async rewind(_session: Session): Promise<Array<Mutation>> { return []; } public async remutate(session: Session): Promise<void> { return this.mutate(session); } public async moveCursor(_cursor: Cursor): Promise<void> { return; } } export class AddChars extends Mutation { private row: Row; private col: Col; private chars: Array<Char>; constructor(row: Row, col: Col, chars: Array<Char>) { super(); this.row = row; this.col = col; this.chars = chars; } public str() { return `row ${this.row}, col ${this.col}, nchars ${this.chars.length}`; } public async mutate(session: Session) { await session.document.writeChars(this.row, this.col, this.chars); } public async rewind() { return [ new DelChars(this.row, this.col, this.chars.length), ]; } public async moveCursor(cursor: Cursor) { if (!(cursor.path.row === this.row)) { return; } if (cursor.col >= this.col) { await cursor.setCol(cursor.col + this.chars.length); } } } export class DelChars extends Mutation { private row: Row; private col: Col; private nchars: number; public deletedChars: Line = []; constructor(row: Row, col: Col, nchars: number) { super(); this.row = row; this.col = col; this.nchars = nchars; } public str() { return `row ${this.row}, col ${this.col}, nchars ${this.nchars}`; } public async mutate(session: Session) { this.deletedChars = await session.document.deleteChars(this.row, this.col, this.nchars); } public async rewind() { return [ new AddChars(this.row, this.col, this.deletedChars), ]; } public async moveCursor(cursor: Cursor) { if (cursor.row !== this.row) { return; } if (cursor.col < this.col) { return; } else if (cursor.col < this.col + this.nchars) { await cursor.setCol(this.col); } else { await cursor.setCol(cursor.col - this.nchars); } } } export class ChangeChars extends Mutation { private row: Row; private col: Col; private nchars: number; private transform?: (chars: Chars) => Chars; private newChars?: Array<Char>; private deletedChars: Array<Char> = []; public ncharsDeleted: number = 0; constructor( row: Row, col: Col, nchars: number, transform?: (chars: Array<Char>) => Array<Char>, newChars?: Array<Char>, ) { super(); this.row = row; this.col = col; this.nchars = nchars; this.transform = transform; this.newChars = newChars; } public str() { return `change row ${this.row}, col ${this.col}, nchars ${this.nchars}`; } public async mutate(session: Session) { this.deletedChars = await session.document.deleteChars(this.row, this.col, this.nchars); this.ncharsDeleted = this.deletedChars.length; if (this.transform) { this.newChars = this.transform(this.deletedChars); errors.assert(this.newChars.length === this.ncharsDeleted); } if (!this.newChars) { throw new Error('Changechars should receive either transform or newChars'); } await session.document.writeChars(this.row, this.col, this.newChars); } public async rewind() { if (this.newChars == null) { throw new Error('No new chars after mutation?'); } return [ new ChangeChars(this.row, this.col, this.newChars.length, undefined, this.deletedChars), ]; } public async remutate(session: Session) { if (this.newChars == null) { throw new Error('No new chars after mutation?'); } await session.document.deleteChars(this.row, this.col, this.ncharsDeleted); await session.document.writeChars(this.row, this.col, this.newChars); } // doesn't move cursors } export class MoveBlock extends Mutation { private path: Path; private parent: Path; private old_parent: Path; private index: number; private old_index: number = -1; constructor(path: Path, parent: Path, index: number) { super(); this.path = path; this.parent = parent; if (this.path.parent == null) { throw new Error('Can\'t move root'); } this.old_parent = this.path.parent; if (index === undefined) { this.index = -1; } else { this.index = index; } } public str() { return `move ${this.path.row} from ${this.old_parent.row} to ${this.parent.row}`; } public async validate(session: Session) { if (this.path.isRoot()) { session.showMessage('Cannot detach root', {text_class: 'error'}); return false; } // if parent is the same, don't do sibling clone validation const sameParent = this.parent.row === this.old_parent.row; return await validateRowInsertion(session, this.parent.row, this.path.row, {noSiblingCheck: sameParent}); } public async mutate(session: Session) { const info = await session.document._move(this.path.row, this.old_parent.row, this.parent.row, this.index); this.old_index = info.old.child_index; } public async rewind() { return [ new MoveBlock(this.parent.extend([this.path.row]), this.old_parent, this.old_index), ]; } public async moveCursor(cursor: Cursor) { const walk = cursor.path.walkFrom(this.path); if (walk === null) { return; } // TODO: other cursors could also // be on a relevant path.. await cursor._setPath((this.parent.extend([this.path.row])).extend(walk)); } } export class AttachBlocks extends Mutation { private parent: Row; private cloned_rows: Array<Row>; private nrows: number; private index: number; constructor(parent: Row, cloned_rows: Array<Row>, index: number) { super(); this.parent = parent; this.cloned_rows = cloned_rows; this.nrows = this.cloned_rows.length; if (index === undefined) { this.index = -1; } else { this.index = index; } } public str() { return `parent ${this.parent}, index ${this.index}`; } public async validate(session: Session) { for (let i = 0; i < this.cloned_rows.length; i++) { const row = this.cloned_rows[i]; if (!await validateRowInsertion(session, this.parent, row)) { return false; } } return true; } public async mutate(session: Session) { await session.document._attachChildren(this.parent, this.cloned_rows, this.index); } public async rewind() { return [ new DetachBlocks(this.parent, this.index, this.nrows), ]; } } type DetachBlocksOptions = {addNew?: boolean, noNew?: boolean}; export class DetachBlocks extends Mutation { private parent: Row; private index: number; private nrows: number; public deleted: Array<Row> = []; private next: SerializedPath = []; private created_info: AttachedChildInfo | null = null; private options: DetachBlocksOptions; constructor(parent: Row, index: number, nrows: number = 1, options: DetachBlocksOptions = {}) { super(); this.parent = parent; this.index = index; this.nrows = nrows; this.options = options; } public str() { return `parent ${this.parent}, index ${this.index}, nrows ${this.nrows}`; } public async mutate(session: Session) { this.deleted = await session.document._getChildren(this.parent, this.index, this.index + this.nrows - 1); for (let i = 0; i < this.deleted.length; i++) { const row = this.deleted[i]; await session.document._detach(row, this.parent); } this.created_info = null; if (this.options.addNew) { const info = await session.document._newChild(this.parent, this.index); this.created_info = info; } const children = await session.document._getChildren(this.parent); // a path, relative to the parent let next: Array<Row>; if (this.index < children.length) { next = [children[this.index]]; } else { if (this.index === 0) { next = []; if (this.parent === session.document.root.row) { if (!this.options.noNew) { const info = await session.document._newChild(this.parent); this.created_info = info; next = [info.row]; } } } else { const child = children[this.index - 1]; const walk = await session.document.walkToLastVisible(child); next = [child].concat(walk); } } this.next = next; } public async rewind() { const mutations: Array<Mutation> = []; if (this.created_info !== null) { mutations.push(new DetachBlocks(this.parent, this.created_info.child_index, 1, {noNew: true})); } mutations.push(new AttachBlocks(this.parent, this.deleted, this.index)); return mutations; } public async remutate(session: Session) { for (let i = 0; i < this.deleted.length; i++) { const row = this.deleted[i]; await session.document._detach(row, this.parent); } if (this.created_info !== null) { await session.document._attach(this.created_info.row, this.parent, this.created_info.child_index); } } public async moveCursor(cursor: Cursor) { const result = cursor.path.shedUntil(this.parent); if (result === null) { return; } const [walk, ancestor] = result; if (walk.length === 0) { return; } const child = walk[0]; if ((this.deleted.indexOf(child)) === -1) { return; } await cursor.setPosition(ancestor.extend(this.next), 0); } } // creates new blocks (as opposed to attaching ones that already exist) export class AddBlocks extends Mutation { private parent: Path; private serialized_rows: Array<SerializedBlock>; private index: number; private nrows: number; public added_rows: Array<Path> = []; constructor(parent: Path, index: number, serialized_rows: Array<SerializedBlock>) { super(); this.parent = parent; this.serialized_rows = serialized_rows; if (index === undefined) { this.index = -1; } else { this.index = index; } this.nrows = this.serialized_rows.length; } public str() { return `parent ${this.parent.row}, index ${this.index}`; } public async mutate(session: Session) { let index = this.index; const id_mapping = {}; this.added_rows = []; for (let i = 0; i < this.serialized_rows.length; i++) { const serialized_row = this.serialized_rows[i]; const row = await session.document.loadTo(serialized_row, this.parent, index, id_mapping); this.added_rows.push(row); index += 1; } } public async rewind() { return [ new DetachBlocks(this.parent.row, this.index, this.nrows), ]; } public async remutate(session: Session) { let index = this.index; for (let i = 0; i < this.added_rows.length; i++) { const sib = this.added_rows[i]; await session.document.attachChild(this.parent, sib, index); index += 1; } } } export class ToggleBlock extends Mutation { private row: Row; constructor(row: Row) { super(); this.row = row; } public str() { return `row ${this.row}`; } public async mutate(session: Session) { await session.document.toggleCollapsed(this.row); } public async rewind() { return [ this, ]; } // TODO: if a cursor is within the toggle block and their // viewRoot isn't, do a moveCursor? }
the_stack
import * as THREE from 'three'; /// <reference path="potpack.d.ts"/> import potpack, { PotPackItem } from 'potpack'; const tmpOrigin = new THREE.Vector3(); const tmpU = new THREE.Vector3(); const tmpV = new THREE.Vector3(); const tmpW = new THREE.Vector3(); const tmpNormal = new THREE.Vector3(); const tmpUAxis = new THREE.Vector3(); const tmpVAxis = new THREE.Vector3(); const tmpWLocal = new THREE.Vector2(); const tmpMinLocal = new THREE.Vector2(); const tmpMaxLocal = new THREE.Vector2(); // used for auto-indexing const tmpVert = new THREE.Vector3(); const tmpVert2 = new THREE.Vector3(); const tmpNormal2 = new THREE.Vector3(); function findVertex( posArray: ArrayLike<number>, normalArray: ArrayLike<number>, vertexIndex: number ): number { tmpVert.fromArray(posArray, vertexIndex * 3); tmpNormal.fromArray(normalArray, vertexIndex * 3); // finish search before current vertex (since latter is the fallback return) for (let vStart = 0; vStart < vertexIndex; vStart += 1) { tmpVert2.fromArray(posArray, vStart * 3); tmpNormal2.fromArray(normalArray, vStart * 3); if (tmpVert2.equals(tmpVert) && tmpNormal2.equals(tmpNormal)) { return vStart; } } return vertexIndex; } function convertGeometryToIndexed(buffer: THREE.BufferGeometry) { const posArray = buffer.attributes.position.array; const posVertexCount = Math.floor(posArray.length / 3); const faceCount = Math.floor(posVertexCount / 3); const normalArray = buffer.attributes.normal.array; const indexAttr = new THREE.Uint16BufferAttribute(faceCount * 3, 3); indexAttr.count = faceCount * 3; // @todo without this the mesh does not show all faces for (let faceIndex = 0; faceIndex < faceCount; faceIndex += 1) { const vStart = faceIndex * 3; const a = findVertex(posArray, normalArray, vStart); const b = findVertex(posArray, normalArray, vStart + 1); const c = findVertex(posArray, normalArray, vStart + 2); indexAttr.setXYZ(faceIndex, a, b, c); } buffer.setIndex(indexAttr); } function guessOrthogonalOrigin( indexArray: ArrayLike<number>, vStart: number, posArray: ArrayLike<number> ): number { let minAbsDot = 1; let minI = 0; for (let i = 0; i < 3; i += 1) { // for this ortho origin choice, compute defining edges tmpOrigin.fromArray(posArray, indexArray[vStart + i] * 3); tmpU.fromArray(posArray, indexArray[vStart + ((i + 2) % 3)] * 3); tmpV.fromArray(posArray, indexArray[vStart + ((i + 1) % 3)] * 3); tmpU.sub(tmpOrigin); tmpV.sub(tmpOrigin); // normalize and compute cross (cosine of angle) tmpU.normalize(); tmpV.normalize(); const absDot = Math.abs(tmpU.dot(tmpV)); // compare with current minimum if (minAbsDot > absDot) { minAbsDot = absDot; minI = i; } } return minI; } // @todo support opt-in inside opt-out groups export const AUTO_UV2_OPT_OUT_FLAG = Symbol('auto-UV2 opt out flag'); // based on traverse() in https://github.com/mrdoob/three.js/blob/dev/src/core/Object3D.js function traverseAutoUV2Items( object: THREE.Object3D, callback: (object: THREE.Object3D) => void ) { // skip everything inside opt-out wrappers if ( Object.prototype.hasOwnProperty.call(object.userData, AUTO_UV2_OPT_OUT_FLAG) ) { return; } callback(object); for (const childObject of object.children) { traverseAutoUV2Items(childObject, callback); } } const MAX_AUTO_SIZE = 512; // @todo make this configurable? but 512x512 is a lot to compute already function autoSelectSize(layoutSize: number): number { // start with reasonable minimum size and keep trying increasing powers of 2 for (let size = 4; size <= MAX_AUTO_SIZE; size *= 2) { if (layoutSize < size) { return size; } } throw new Error( `minimum lightmap dimension for auto-UV2 is ${layoutSize} which is too large: please reduce texelsPerUnit and/or polygon count` ); } interface AutoUVBox extends PotPackItem { uv2Attr: THREE.Float32BufferAttribute; uAxis: THREE.Vector3; vAxis: THREE.Vector3; posArray: ArrayLike<number>; posIndices: number[]; posLocalX: number[]; posLocalY: number[]; } export interface AutoUV2Settings { texelsPerUnit: number; } export function computeAutoUV2Layout( initialWidth: number | undefined, initialHeight: number | undefined, scene: THREE.Scene, { texelsPerUnit }: AutoUV2Settings ): [number, number] { const layoutBoxes: AutoUVBox[] = []; let hasPredefinedUV2 = false; traverseAutoUV2Items(scene, (mesh) => { if (!(mesh instanceof THREE.Mesh)) { return; } const buffer = mesh.geometry; if (!(buffer instanceof THREE.BufferGeometry)) { throw new Error('expecting buffer geometry'); } // automatically convert to indexed if (!buffer.index) { convertGeometryToIndexed(buffer); } const indexAttr = buffer.index; if (!indexAttr) { throw new Error('unexpected missing geometry index attr'); } const indexArray = indexAttr.array; const faceCount = Math.floor(indexArray.length / 3); const posArray = buffer.attributes.position.array; const normalArray = buffer.attributes.normal.array; const vertexBoxMap: (AutoUVBox | undefined)[] = new Array( posArray.length / 3 ); // complain if found predefined UV2 in a scene with computed UV2 if (buffer.attributes.uv2) { if (layoutBoxes.length > 0) { throw new Error( 'found a mesh with "uv2" attribute in a scene with auto-calculated UV2 data: please do not mix-and-match' ); } hasPredefinedUV2 = true; return; } // complain if trying to compute UV2 in a scene with predefined UV2 if (hasPredefinedUV2) { throw new Error( 'found a mesh with missing "uv2" attribute in a scene with predefined UV2 data: please do not mix-and-match' ); } // pre-create uv2 attribute const uv2Attr = new THREE.Float32BufferAttribute( (2 * posArray.length) / 3, 2 ); buffer.setAttribute('uv2', uv2Attr); for (let vStart = 0; vStart < faceCount * 3; vStart += 3) { // see if this face shares a vertex with an existing layout box let existingBox: AutoUVBox | undefined; for (let i = 0; i < 3; i += 1) { const possibleBox = vertexBoxMap[indexArray[vStart + i]]; if (!possibleBox) { continue; } if (existingBox && existingBox !== possibleBox) { // absorb layout box into the other // (this may happen if same polygon's faces are defined non-consecutively) existingBox.posIndices.push(...possibleBox.posIndices); existingBox.posLocalX.push(...possibleBox.posLocalX); existingBox.posLocalY.push(...possibleBox.posLocalY); // re-assign by-vertex lookup for (const index of possibleBox.posIndices) { vertexBoxMap[index] = existingBox; } // remove from main list const removedBoxIndex = layoutBoxes.indexOf(possibleBox); if (removedBoxIndex === -1) { throw new Error('unexpected orphaned layout box'); } layoutBoxes.splice(removedBoxIndex, 1); } else { existingBox = possibleBox; } } // set up new layout box if needed if (!existingBox) { // @todo guess axis choice based on angle? const originFI = guessOrthogonalOrigin(indexArray, vStart, posArray); const vOrigin = vStart + originFI; const vU = vStart + ((originFI + 2) % 3); // prev in face const vV = vStart + ((originFI + 1) % 3); // next in face // get the plane-defining edge vectors tmpOrigin.fromArray(posArray, indexArray[vOrigin] * 3); tmpU.fromArray(posArray, indexArray[vU] * 3); tmpV.fromArray(posArray, indexArray[vV] * 3); tmpU.sub(tmpOrigin); tmpV.sub(tmpOrigin); // compute orthogonal coordinate system for face plane tmpNormal.fromArray(normalArray, indexArray[vOrigin] * 3); tmpUAxis.crossVectors(tmpV, tmpNormal); tmpVAxis.crossVectors(tmpNormal, tmpUAxis); tmpUAxis.normalize(); tmpVAxis.normalize(); existingBox = { x: 0, // filled later y: 0, // filled later w: 0, // filled later h: 0, // filled later uv2Attr, uAxis: tmpUAxis.clone(), vAxis: tmpVAxis.clone(), posArray, posIndices: [], posLocalX: [], posLocalY: [] }; layoutBoxes.push(existingBox); } // add this face's vertices to the layout box local point set // @todo warn if normals deviate too much for (let i = 0; i < 3; i += 1) { const index = indexArray[vStart + i]; if (vertexBoxMap[index]) { continue; } vertexBoxMap[index] = existingBox; existingBox.posIndices.push(index); existingBox.posLocalX.push(0); // filled later existingBox.posLocalY.push(0); // filled later } } }); // fill in local coords and compute dimensions for layout boxes based on polygon point sets inside them for (const layoutBox of layoutBoxes) { const { uAxis, vAxis, posArray, posIndices, posLocalX, posLocalY } = layoutBox; // compute min and max extents of all coords tmpMinLocal.set(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY); tmpMaxLocal.set(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY); for (let i = 0; i < posIndices.length; i += 1) { const index = posIndices[i]; tmpW.fromArray(posArray, index * 3); tmpWLocal.set(tmpW.dot(uAxis), tmpW.dot(vAxis)); tmpMinLocal.min(tmpWLocal); tmpMaxLocal.max(tmpWLocal); posLocalX[i] = tmpWLocal.x; posLocalY[i] = tmpWLocal.y; } const realWidth = tmpMaxLocal.x - tmpMinLocal.x; const realHeight = tmpMaxLocal.y - tmpMinLocal.y; if (realWidth < 0 || realHeight < 0) { throw new Error('zero-point polygon?'); } // texel box is aligned to texel grid const boxWidthInTexels = Math.ceil(realWidth * texelsPerUnit); const boxHeightInTexels = Math.ceil(realHeight * texelsPerUnit); // layout box positioning is in texels layoutBox.w = boxWidthInTexels + 2; // plus margins layoutBox.h = boxHeightInTexels + 2; // plus margins // make vertex local coords expressed as 0..1 inside texel box for (let i = 0; i < posIndices.length; i += 1) { posLocalX[i] = (posLocalX[i] - tmpMinLocal.x) / realWidth; posLocalY[i] = (posLocalY[i] - tmpMinLocal.y) / realHeight; } } // bail out if no layout is necessary if (layoutBoxes.length === 0) { return [initialWidth || 0, initialHeight || 0]; // report preferred size if given } // main layout magic const { w: layoutWidth, h: layoutHeight } = potpack(layoutBoxes); // check layout results against width/height if specified if ( (initialWidth && layoutWidth > initialWidth) || (initialHeight && layoutHeight > initialHeight) ) { throw new Error( `minimum lightmap size for auto-UV2 is ${layoutWidth}x${layoutHeight} which is too large to fit provided ${initialWidth}x${initialHeight}: please reduce texelsPerUnit and/or polygon count` ); } // auto-select sizing if needed const finalWidth = initialWidth || autoSelectSize(layoutWidth); const finalHeight = initialHeight || autoSelectSize(layoutHeight); // based on layout box positions, fill in UV2 attribute data for (const layoutBox of layoutBoxes) { const { x, y, w, h, uv2Attr, posIndices, posLocalX, posLocalY } = layoutBox; // inner texel box without margins const ix = x + 1; const iy = y + 1; const iw = w - 2; const ih = h - 2; // convert texel box placement into atlas UV coordinates for (let i = 0; i < posIndices.length; i += 1) { uv2Attr.setXY( posIndices[i], (ix + posLocalX[i] * iw) / finalWidth, (iy + posLocalY[i] * ih) / finalHeight ); } } // report final dimensions return [finalWidth, finalHeight]; }
the_stack
import { BaseContract, ethers } from "ethers"; import { ContractWrapper } from "../core/classes/contract-wrapper"; import { IStorage } from "../core"; import { AbiFunction, AbiSchema, AbiTypeSchema, ContractSource, PreDeployMetadata, PreDeployMetadataFetched, PublishedMetadata, } from "../schema/contracts/custom"; import { z } from "zod"; import { Feature, FeatureName, FeatureWithEnabled, SUPPORTED_FEATURES, } from "../constants/contract-features"; import { decodeFirstSync } from "cbor"; import { toB58String } from "multihashes"; /** * @internal * @param abi * @param feature */ function matchesAbiInterface( abi: z.input<typeof AbiSchema>, feature: Feature, ): boolean { // returns true if all the functions in `interfaceToMatch` are found in `contract` (removing any duplicates) const contractFn = [ ...new Set(extractFunctionsFromAbi(abi).map((f) => f.name)), ]; const interfaceFn = [ ...new Set( feature.abis .flatMap((i) => extractFunctionsFromAbi(i)) .map((f) => f.name), ), ]; return ( contractFn.filter((k) => interfaceFn.includes(k)).length === interfaceFn.length ); } /** * @internal */ export async function extractConstructorParams( predeployMetadataUri: string, storage: IStorage, ) { const meta = await fetchPreDeployMetadata(predeployMetadataUri, storage); return extractConstructorParamsFromAbi(meta.abi); } /** * @internal * @param predeployUri * @param storage */ export async function extractFunctions( predeployMetadataUri: string, storage: IStorage, ): Promise<AbiFunction[]> { const metadata = await fetchPreDeployMetadata(predeployMetadataUri, storage); return extractFunctionsFromAbi(metadata.abi); } /** * * @param abi * @returns * @internal */ export function extractConstructorParamsFromAbi( abi: z.input<typeof AbiSchema>, ) { for (const input of abi) { if (input.type === "constructor") { return input.inputs ?? []; } } return []; } /** * @internal * @param abi */ export function extractFunctionsFromAbi( abi: z.input<typeof AbiSchema>, ): AbiFunction[] { const functions = abi.filter((el) => el.type === "function"); const parsed = []; for (const f of functions) { const args = f.inputs?.map((i) => `${i.name || "key"}: ${toJSType(i)}`)?.join(", ") || ""; const fargs = args ? `, ${args}` : ""; const out = f.outputs?.map((o) => toJSType(o, true))?.join(", "); const promise = out ? `: Promise<${out}>` : `: Promise<TransactionResult>`; const signature = `contract.call("${f.name}"${fargs})${promise}`; parsed.push({ inputs: f.inputs ?? [], outputs: f.outputs ?? [], name: f.name ?? "unknown", signature, stateMutability: f.stateMutability ?? "", }); } return parsed; } function toJSType( contractType: z.input<typeof AbiTypeSchema>, isReturnType = false, withName = false, ): string { let jsType = contractType.type; let isArray = false; if (jsType.endsWith("[]")) { isArray = true; jsType = jsType.slice(0, -2); } if (jsType.startsWith("bytes")) { jsType = "BytesLike"; } if (jsType.startsWith("uint") || jsType.startsWith("int")) { jsType = isReturnType ? "BigNumber" : "BigNumberish"; } if (jsType.startsWith("bool")) { jsType = "boolean"; } if (jsType === "address") { jsType = "string"; } if (jsType === "tuple") { if (contractType.components) { jsType = `{ ${contractType.components .map((a) => toJSType(a, false, true)) .join(", ")} }`; } } if (isArray) { jsType += "[]"; } if (withName) { jsType = `${contractType.name}: ${jsType}`; } return jsType; } /** * @internal * @param address * @param provider */ export async function resolveContractUriFromAddress( address: string, provider: ethers.providers.Provider, ): Promise<string | undefined> { const bytecode = await provider.getCode(address); if (bytecode === "0x") { const chain = await provider.getNetwork(); throw new Error( `Contract at ${address} does not exist on chain '${chain.name}' (chainId: ${chain.chainId})`, ); } return extractIPFSHashFromBytecode(bytecode); } /** * @internal * @param bytecode */ function extractIPFSHashFromBytecode(bytecode: string): string | undefined { try { const numericBytecode = hexToBytes(bytecode); const cborLength: number = numericBytecode[numericBytecode.length - 2] * 0x100 + numericBytecode[numericBytecode.length - 1]; const bytecodeBuffer = Buffer.from( numericBytecode.slice(numericBytecode.length - 2 - cborLength, -2), ); const cborData = decodeFirstSync(bytecodeBuffer); if (cborData["ipfs"]) { return `ipfs://${toB58String(cborData["ipfs"])}`; } } catch (e) { console.error("failed to extract ipfs hash from bytecode", e); } return undefined; } /** * @internal * @param hex */ function hexToBytes(hex: string | number) { hex = hex.toString(16); if (!hex.startsWith("0x")) { hex = `0x${hex}`; } if (!isHexStrict(hex)) { throw new Error(`Given value "${hex}" is not a valid hex string.`); } hex = hex.replace(/^0x/i, ""); const bytes = []; for (let c = 0; c < hex.length; c += 2) { bytes.push(parseInt(hex.slice(c, c + 2), 16)); } return bytes; } /** * @internal * @param hex */ function isHexStrict(hex: string | number) { return ( (typeof hex === "string" || typeof hex === "number") && /^(-)?0x[0-9a-f]*$/i.test(hex.toString()) ); } /** * @internal * @param address * @param provider * @param storage */ export async function fetchContractMetadataFromAddress( address: string, provider: ethers.providers.Provider, storage: IStorage, ) { const compilerMetadataUri = await resolveContractUriFromAddress( address, provider, ); if (!compilerMetadataUri) { throw new Error(`Could not resolve metadata for contract at ${address}`); } return await fetchContractMetadata(compilerMetadataUri, storage); } /** * @internal * @param compilerMetadataUri * @param storage */ async function fetchContractMetadata( compilerMetadataUri: string, storage: IStorage, ): Promise<PublishedMetadata> { const metadata = await storage.get(compilerMetadataUri); const abi = AbiSchema.parse(metadata.output.abi); const compilationTarget = metadata.settings.compilationTarget; const targets = Object.keys(compilationTarget); const name = compilationTarget[targets[0]]; return { name, abi, metadata, }; } /** * @internal * @param publishedMetadata * @param storage */ export async function fetchSourceFilesFromMetadata( publishedMetadata: PublishedMetadata, storage: IStorage, ): Promise<ContractSource[]> { return await Promise.all( Object.entries(publishedMetadata.metadata.sources).map( async ([path, info]) => { const urls = (info as any).urls as string[]; const ipfsLink = urls.find((url) => url.includes("ipfs")); if (ipfsLink) { const ipfsHash = ipfsLink.split("ipfs/")[1]; // 5 sec timeout for sources that haven't been uploaded to ipfs const timeout = new Promise<string>((_r, rej) => setTimeout(() => rej("timeout"), 5000), ); const source = await Promise.race([ storage.getRaw(`ipfs://${ipfsHash}`), timeout, ]); return { filename: path, source, }; } else { return { filename: path, source: "Could not find source for this contract", }; } }, ), ); } /** * @internal * @param publishMetadataUri * @param storage */ export async function fetchPreDeployMetadata( publishMetadataUri: string, storage: IStorage, ): Promise<PreDeployMetadataFetched> { const pubMeta = PreDeployMetadata.parse( await storage.get(publishMetadataUri), ); const deployBytecode = await storage.getRaw(pubMeta.bytecodeUri); const parsedMeta = await fetchContractMetadata(pubMeta.metadataUri, storage); return { name: parsedMeta.name, abi: parsedMeta.abi, bytecode: deployBytecode, }; } /** * @internal * @param bytecode * @param storage */ export async function fetchContractMetadataFromBytecode( bytecode: string, storage: IStorage, ) { const metadataUri = extractIPFSHashFromBytecode(bytecode); if (!metadataUri) { throw new Error("No metadata found in bytecode"); } return await fetchContractMetadata(metadataUri, storage); } /** * Processes ALL supported features and sets whether the passed in abi supports each individual feature * @internal * @param abi * @param features * @returns the nested struct of all features and whether they're detected in the abi */ export function detectFeatures( abi: z.input<typeof AbiSchema>, features: Record<string, Feature> = SUPPORTED_FEATURES, ): Record<string, FeatureWithEnabled> { const results: Record<string, FeatureWithEnabled> = {}; for (const featureKey in features) { const feature = features[featureKey]; const enabled = matchesAbiInterface(abi, feature); const childResults = detectFeatures(abi, feature.features); results[featureKey] = { ...feature, features: childResults, enabled, } as FeatureWithEnabled; } return results; } /** * Checks whether the given ABI supports a given feature * @internal * @param abi * @param featureName */ export function isFeatureEnabled( abi: z.input<typeof AbiSchema>, featureName: FeatureName, ): boolean { const features = detectFeatures(abi); return _featureEnabled(features, featureName); } /** * Type guard for contractWrappers depending on passed feature name * @internal * @param contractWrapper * @param featureName */ export function detectContractFeature<T extends BaseContract>( contractWrapper: ContractWrapper<BaseContract>, featureName: FeatureName, ): contractWrapper is ContractWrapper<T> { return isFeatureEnabled(AbiSchema.parse(contractWrapper.abi), featureName); } /** * Searches the feature map for featureName and returns whether its enabled * @internal * @param features * @param featureName */ function _featureEnabled( features: Record<string, FeatureWithEnabled>, featureName: FeatureName, ): boolean { const keys = Object.keys(features); if (!keys.includes(featureName)) { let found = false; for (const key of keys) { const f = features[key]; found = _featureEnabled( f.features as Record<string, FeatureWithEnabled>, featureName, ); if (found) { break; } } return found; } const feature = features[featureName]; return feature.enabled; } /** * @internal * @param contractWrapper * @param functionName */ export function hasFunction<TContract extends BaseContract>( functionName: string, contractWrapper: ContractWrapper<any>, ): contractWrapper is ContractWrapper<TContract> { return functionName in contractWrapper.readContract.functions; }
the_stack
import { Comparer } from '@esfx/equatable'; const binaryOperators = { "+": add, "-": sub, "*": mul, "**": pow, "/": div, "%": mod, "<<": shl, ">>": sar, ">>>": shr, "&": bitand, "|": bitor, "^": bitxor, "&&": and, "||": or, "??": coalesce, "<": lt, "<=": le, ">": gt, ">=": ge, "==": weq, "!=": wne, "===": eq, "!==": ne, }; const unaryOperators = { "+": plus, "-": neg, "~": bitnot, "!": not, }; const unspecifiedOperators = { ...binaryOperators, ...unaryOperators, "+": addOrPlus, "-": subOrNeg, }; export type BinaryOperators = typeof binaryOperators; export type UnaryOperators = typeof unaryOperators; export type Operators = typeof unspecifiedOperators; export function operator<K extends keyof Operators>(op: K): Operators[K]; export function operator<K extends keyof UnaryOperators>(op: K, arity: 1): UnaryOperators[K]; export function operator<K extends keyof BinaryOperators>(op: K, arity: 2): BinaryOperators[K]; export function operator<K extends keyof Operators>(op: K, arity?: 1 | 2) { const f = arity === 1 ? unaryOperators[op as keyof UnaryOperators] : arity === 2 ? binaryOperators[op as keyof BinaryOperators] : unspecifiedOperators[op]; if (!f) throw new TypeError("Invalid operator"); return f; } function addOrPlus(x: number, y: number): number; function addOrPlus(x: bigint, y: bigint): bigint; function addOrPlus(x: string, y: string | number | boolean | object | null | undefined): string; function addOrPlus(x: string | number | boolean | object | null | undefined, y: string): string; function addOrPlus(x: number): number; function addOrPlus(x: any, y?: any): number | string | bigint { return arguments.length === 1 ? plus(x) : add(x, y); } /** * Add/concat (i.e. `x + y`). */ export function add(x: number, y: number): number; export function add(x: bigint, y: bigint): bigint; export function add(x: string, y: string | number | boolean | object | null | undefined): string; export function add(x: string | number | boolean | object | null | undefined, y: string): string; export function add(x: any, y: any) { return x + y; } function subOrNeg(x: number, y: number): number; function subOrNeg(x: bigint, y: bigint): bigint; function subOrNeg(x: number): number; function subOrNeg(x: bigint): bigint; function subOrNeg(x: any, y?: any): any { return arguments.length === 1 ? neg(x) : sub(x, y); } /** * Subtract (i.e. `x - y`). */ export function sub(x: number, y: number): number; export function sub(x: bigint, y: bigint): bigint; export function sub(x: any, y: any): number | bigint { return x - y; } /** * Multiply (i.e. `x * y`). */ export function mul(x: number, y: number): number; export function mul(x: bigint, y: bigint): bigint; export function mul(x: any, y: any): any { return x * y; } /** * Exponentiate (i.e. `x ** y`). */ export function pow(x: number, y: number): number; export function pow(x: bigint, y: bigint): bigint; export function pow(x: any, y: any): any { return x ** y; } /** * Divide (i.e. `x / y`). */ export function div(x: number, y: number): number; export function div(x: bigint, y: bigint): bigint; export function div(x: any, y: any): any { return x / y; } /** * Modulo (i.e. `x % y`). */ export function mod(x: number, y: number): number; export function mod(x: bigint, y: bigint): bigint; export function mod(x: any, y: any): any { return x % y; } /** * Left shift (i.e. `x << n`). */ export function shl(x: number, n: number): number; export function shl(x: bigint, n: bigint): bigint; export function shl(x: any, n: any): any { return x << n; } export { shl as sal }; /** * Signed right shift (i.e. `x >> n`). */ export function sar(x: number, n: number): number; export function sar(x: bigint, n: bigint): bigint; export function sar(x: any, n: any): any { return x >> n; } /** * Unsigned right shift (i.e. `x >>> n`). */ export function shr(x: number, n: number): number; export function shr(x: bigint, n: bigint): bigint; export function shr(x: any, n: any): any { return x >>> n; } /** * Negate (i.e. `-x`). */ export function neg(x: number): number; export function neg(x: bigint): bigint; export function neg(x: any): any { return -x; } /** * Unary plus (i.e. `+x`). */ export function plus(x: number) { return +x; } /** * Bitwise AND (i.e. `x & y`). */ export function bitand(x: number, y: number): number; export function bitand(x: bigint, y: bigint): bigint; export function bitand(x: any, y: any): any { return x & y; } /** * Bitwise OR (i.e. `x | y`). */ export function bitor(x: number, y: number): number; export function bitor(x: bigint, y: bigint): bigint; export function bitor(x: any, y: any): any { return x | y; } /** * Bitwise XOR (i.e. `x ^ y`). */ export function bitxor(x: number, y: number): number; export function bitxor(x: bigint, y: bigint): bigint; export function bitxor(x: any, y: any): any { return x ^ y; } /** * Bitwise NOT (i.e. `~x`). */ export function bitnot(x: number): number; export function bitnot(x: bigint): bigint; export function bitnot(x: any): any { return ~x; } /** * Logical AND (i.e. `x && y`). */ export function and(x: boolean, y: boolean) { return x && y; } /** * Logical OR (i.e. `x || y`). */ export function or(x: boolean, y: boolean) { return x || y; } /** * Logical XOR (i.e. `x ? !y : y`). */ export function xor(x: boolean, y: boolean) { return x ? !y : y; } /** * Logical NOT (i.e. `!x`). */ export function not(x: boolean) { return !x; } /** * Nullish Coalesce (i.e. `x ?? y`). */ export function coalesce<T, U>(x: T, y: U): NonNullable<T> | U { // TODO: Not supported by jest/ts-jest? // return x ?? y; return x !== undefined && x !== null ? x! : y; } /** * Relational greater-than (i.e. `x > y`). */ export function gt<T>(x: T, y: T) { return Comparer.defaultComparer.compare(x, y) > 0; } /** * Creates a copy of `gt` for a specific `Comparer`. */ gt.withComparer = <T>(comparer: Comparer<T>): (x: T, y: T) => boolean => (x, y) => comparer.compare(x, y) > 0; /** * Relational greater-than-equals (i.e. `x >= y`). */ export function ge<T>(x: T, y: T) { return Comparer.defaultComparer.compare(x, y) >= 0; } /** * Creates a copy of `ge` for a specific `Comparer`. */ ge.withComparer = <T>(comparer: Comparer<T>): (x: T, y: T) => boolean => (x, y) => comparer.compare(x, y) >= 0; /** * Relational less-than (i.e. `x < y`). */ export function lt<T>(x: T, y: T) { return Comparer.defaultComparer.compare(x, y) < 0; } /** * Creates a copy of `lt` for a specific `Comparer`. */ lt.withComparer = <T>(comparer: Comparer<T>): (x: T, y: T) => boolean => (x, y) => comparer.compare(x, y) < 0; /** * Relational less-than-equals (i.e. `x <= y`). */ export function le<T>(x: T, y: T) { return Comparer.defaultComparer.compare(x, y) <= 0; } /** * Creates a copy of `le` for a specific `Comparer`. */ le.withComparer = <T>(comparer: Comparer<T>): (x: T, y: T) => boolean => (x, y) => comparer.compare(x, y) <= 0; /** * Relational equals (i.e. `x >= y && x <= y`). */ export function req<T>(x: T, y: T) { return Comparer.defaultComparer.compare(x, y) === 0; } /** * Creates a copy of `eq` for a specific `Comparer`. */ req.withComparer = <T>(comparer: Comparer<T>): (x: T, y: T) => boolean => (x, y) => comparer.compare(x, y) === 0; /** * Weak equality (i.e. `x == y`). */ export function weq<T>(x: T, y: T) { return x == y; } /** * Strict equality (i.e. `x === y`). */ export function eq<T>(x: T, y: T) { return x === y; } /** * Relational not-equals (i.e. `x < y || x > y`). */ export function rne<T>(x: T, y: T) { return Comparer.defaultComparer.compare(x, y) !== 0; } /** * Creates a copy of `ne` for a specific `Comparer`. */ rne.withComparer = <T>(comparer: Comparer<T>): (x: T, y: T) => boolean => (x, y) => comparer.compare(x, y) !== 0; /** * Weak inequality (i.e. `x != y`). */ export function wne<T>(x: T, y: T) { return x != y; } /** * Strict equality (i.e. `x !== y`). */ export function ne<T>(x: T, y: T) { return x !== y; } /** * Relational minimum (i.e. `x <= y ? x : y`). */ export function min<T>(x: T, y: T) { return Comparer.defaultComparer.compare(x, y) <= 0 ? x : y; } /** * Creates a copy of `min` for a specific `Comparer`. */ min.withComparer = <T>(comparer: Comparer<T>): (x: T, y: T) => T => (x, y) => comparer.compare(x, y) <= 0 ? x : y; /** * Relational minimum using a provided selector (i.e. `f(x) <= f(y) ? x : y`). */ export function minBy<T, K>(x: T, y: T, f: (v: T) => K) { return Comparer.defaultComparer.compare(f(x), f(y)) <= 0 ? x : y; } /** * Creates a copy of `minBy` for a specific `Comparer`. */ minBy.withComparer = <K>(comparer: Comparer<K>): <T>(x: T, y: T, f: (v: T) => K) => T => (x, y, f) => comparer.compare(f(x), f(y)) <= 0 ? x : y; /** * Relational maximum (i.e. `x >= y ? x : y`). */ export function max<T>(x: T, y: T) { return Comparer.defaultComparer.compare(x, y) >= 0 ? x : y; } /** * Creates a copy of `min` for a specific `Comparer`. */ max.withComparer = <K>(comparer: Comparer<K>): (x: K, y: K) => K => (x, y) => comparer.compare(x, y) >= 0 ? x : y; /** * Relational maximum using a provided selector (i.e. `f(x) <= f(y) ? x : y`). */ export function maxBy<T, K>(x: T, y: T, f: (v: T) => K) { return Comparer.defaultComparer.compare(f(x), f(y)) >= 0 ? x : y; } /** * Creates a copy of `maxBy` for a specific `Comparer`. */ maxBy.withComparer = <K>(comparer: Comparer<K>): <T>(x: T, y: T, f: (v: T) => K) => T => (x, y, f) => comparer.compare(f(x), f(y)) >= 0 ? x : y;
the_stack
import { IEpicTimelineState } from "../Contracts"; import { EpicTimelineActions, EpicTimelineActionTypes, PortfolioItemsReceivedAction, PortfolioItemDeletedAction } from "../Actions/EpicTimelineActions"; import produce from "immer"; import { ProgressTrackingCriteria, LoadingStatus, IWorkItemIcon } from "../../Contracts"; import { MergeType } from "../../Models/PortfolioPlanningQueryModels"; import { defaultIProjectComparer, defaultIWorkItemComparer } from "../../Common/Utilities/Comparers"; export function epicTimelineReducer(state: IEpicTimelineState, action: EpicTimelineActions): IEpicTimelineState { return produce(state || getDefaultState(), (draft: IEpicTimelineState) => { switch (action.type) { case EpicTimelineActionTypes.UpdateDates: { const { epicId, startDate, endDate } = action.payload; const epicToUpdate = draft.epics.find(epic => epic.id === epicId); epicToUpdate.startDate = startDate.toDate(); epicToUpdate.startDate.setHours(0, 0, 0, 0); epicToUpdate.endDate = endDate.toDate(); epicToUpdate.endDate.setHours(0, 0, 0, 0); epicToUpdate.itemUpdating = true; break; } case EpicTimelineActionTypes.ShiftItem: { const { itemId, startDate } = action.payload; const epicToUpdate = draft.epics.find(epic => epic.id === itemId); const epicDuration = epicToUpdate.endDate.getTime() - epicToUpdate.startDate.getTime(); epicToUpdate.startDate = startDate.toDate(); epicToUpdate.startDate.setHours(0, 0, 0, 0); epicToUpdate.endDate = startDate.add(epicDuration, "milliseconds").toDate(); epicToUpdate.endDate.setHours(0, 0, 0, 0); epicToUpdate.itemUpdating = true; break; } case EpicTimelineActionTypes.UpdateItemFinished: { const { itemId } = action.payload; const epicToUpdate = draft.epics.find(epic => epic.id === itemId); epicToUpdate.itemUpdating = false; break; } case EpicTimelineActionTypes.ToggleItemDetailsDialogHidden: { const { hidden } = action.payload; draft.setDatesDialogHidden = hidden; break; } case EpicTimelineActionTypes.SetSelectedItemId: { const { id } = action.payload; draft.selectedItemId = id; break; } case EpicTimelineActionTypes.PortfolioItemsReceived: const { result } = action.payload; const { items, projects } = result; draft.planLoadingStatus = LoadingStatus.Loaded; draft.exceptionMessage = items.exceptionMessage || projects.exceptionMessage; return handlePortfolioItemsReceived(draft, action as PortfolioItemsReceivedAction); case EpicTimelineActionTypes.OpenAddItemPanel: { draft.addItemsPanelOpen = true; break; } case EpicTimelineActionTypes.CloseAddItemPanel: { draft.addItemsPanelOpen = false; draft.isNewPlanExperience = false; break; } case EpicTimelineActionTypes.PortfolioItemDeleted: { return handlePortfolioItemDeleted(state, action as PortfolioItemDeletedAction); } case EpicTimelineActionTypes.ToggleProgressTrackingCriteria: { draft.progressTrackingCriteria = action.payload.criteria; break; } case EpicTimelineActionTypes.ToggleLoadingStatus: { const { status } = action.payload; draft.planLoadingStatus = status; break; } case EpicTimelineActionTypes.ResetPlanState: { draft.planLoadingStatus = LoadingStatus.NotLoaded; draft.selectedItemId = undefined; draft.setDatesDialogHidden = true; draft.addItemsPanelOpen = false; draft.planSettingsPanelOpen = false; draft.epics = []; draft.projects = []; draft.teams = {}; draft.isNewPlanExperience = false; draft.deletePlanDialogHidden = true; break; } case EpicTimelineActionTypes.TogglePlanSettingsPanelOpen: { const { isOpen } = action.payload; draft.planSettingsPanelOpen = isOpen; break; } case EpicTimelineActionTypes.ToggleIsNewPlanExperience: { draft.isNewPlanExperience = action.payload.isNewPlanExperience; break; } case EpicTimelineActionTypes.ToggleDeletePlanDialogHidden: { draft.deletePlanDialogHidden = action.payload.hidden; break; } case EpicTimelineActionTypes.HandleGeneralException: { draft.exceptionMessage = action.payload.message || action.payload.exceptionMessage; break; } case EpicTimelineActionTypes.DismissErrorMessageCard: { draft.exceptionMessage = ""; break; } } }); } export function getDefaultState(): IEpicTimelineState { return { planLoadingStatus: LoadingStatus.NotLoaded, exceptionMessage: "", projects: [], teams: {}, epics: [], message: "Initial message", addItemsPanelOpen: false, setDatesDialogHidden: true, planSettingsPanelOpen: false, selectedItemId: null, progressTrackingCriteria: ProgressTrackingCriteria.CompletedCount, isNewPlanExperience: false, deletePlanDialogHidden: true, planTelemetry: null }; } function handlePortfolioItemsReceived( state: IEpicTimelineState, action: PortfolioItemsReceivedAction ): IEpicTimelineState { return produce(state, draft => { const { result, projectConfigurations } = action.payload; const { items, projects, teamAreas, mergeStrategy } = result; if (mergeStrategy === MergeType.Replace) { draft.projects = projects.projects.map(project => { return { id: project.ProjectSK, title: project.ProjectName, configuration: projectConfigurations[project.ProjectSK.toLowerCase()] }; }); draft.epics = items.items.map(item => { // Using the first team found for the area, if available. const teamIdValue: string = teamAreas.teamsInArea[item.AreaId] && teamAreas.teamsInArea[item.AreaId][0] ? teamAreas.teamsInArea[item.AreaId][0].teamId : null; const backlogLevelName: string = projectConfigurations[item.ProjectId] ? projectConfigurations[item.ProjectId].backlogLevelNamesByWorkItemType[ item.WorkItemType.toLowerCase() ] : null; const iconProps: IWorkItemIcon = projectConfigurations[item.ProjectId] ? projectConfigurations[item.ProjectId].iconInfoByWorkItemType[item.WorkItemType.toLowerCase()] : null; return { id: item.WorkItemId, backlogLevel: backlogLevelName, project: item.ProjectId, teamId: teamIdValue, title: item.Title, iconProps, startDate: item.StartDate, endDate: item.TargetDate, completedCount: item.CompletedCount, totalCount: item.TotalCount, completedEffort: item.CompletedEffort, totalEffort: item.TotalEffort, effortProgress: item.EffortProgress, countProgress: item.CountProgress, itemUpdating: false }; }); draft.teams = {}; if (teamAreas.teamsInArea) { Object.keys(teamAreas.teamsInArea).forEach(areaId => { const teams = teamAreas.teamsInArea[areaId]; teams.forEach(team => { if (!draft.teams[team.teamId]) { draft.teams[team.teamId] = { teamId: team.teamId, teamName: team.teamName }; } }); }); } } else if (mergeStrategy === MergeType.Add) { projects.projects.forEach(newProjectInfo => { const filteredProjects = draft.projects.filter(p => p.id === newProjectInfo.ProjectSK); if (filteredProjects.length === 0) { draft.projects.push({ id: newProjectInfo.ProjectSK, title: newProjectInfo.ProjectName, configuration: projectConfigurations[newProjectInfo.ProjectSK.toLowerCase()] }); } }); // TODO change draft.projects and draft.epics to maps items.items.forEach(newItemInfo => { const filteredItems = draft.epics.filter(p => p.id === newItemInfo.WorkItemId); if (filteredItems.length === 0) { // Using the first team found for the area, if available. const teamIdValue: string = teamAreas.teamsInArea[newItemInfo.AreaId] && teamAreas.teamsInArea[newItemInfo.AreaId][0] ? teamAreas.teamsInArea[newItemInfo.AreaId][0].teamId : null; const backlogLevelName: string = projectConfigurations[newItemInfo.ProjectId] ? projectConfigurations[newItemInfo.ProjectId].backlogLevelNamesByWorkItemType[ newItemInfo.WorkItemType.toLowerCase() ] : null; const iconProps: IWorkItemIcon = projectConfigurations[newItemInfo.ProjectId] ? projectConfigurations[newItemInfo.ProjectId].iconInfoByWorkItemType[ newItemInfo.WorkItemType.toLowerCase() ] : null; draft.epics.push({ id: newItemInfo.WorkItemId, backlogLevel: backlogLevelName, project: newItemInfo.ProjectId, teamId: teamIdValue, iconProps, title: newItemInfo.Title, startDate: newItemInfo.StartDate, endDate: newItemInfo.TargetDate, completedCount: newItemInfo.CompletedCount, totalCount: newItemInfo.TotalCount, completedEffort: newItemInfo.CompletedEffort, totalEffort: newItemInfo.TotalEffort, effortProgress: newItemInfo.EffortProgress, countProgress: newItemInfo.CountProgress, itemUpdating: false }); } }); if (teamAreas.teamsInArea && draft.teams) { Object.keys(teamAreas.teamsInArea).forEach(areaId => { const teams = teamAreas.teamsInArea[areaId]; teams.forEach(team => { if (!draft.teams[team.teamId]) { draft.teams[team.teamId] = { teamId: team.teamId, teamName: team.teamName }; } }); }); } // Sort projects by name for displaying in the timeline. draft.projects.sort(defaultIProjectComparer); // Not loading anymore. draft.planLoadingStatus = LoadingStatus.Loaded; } // Sort timeline items by name. if (draft.epics) { draft.epics.sort(defaultIWorkItemComparer); } }); } function handlePortfolioItemDeleted(state: IEpicTimelineState, action: PortfolioItemDeletedAction): IEpicTimelineState { return produce(state, draft => { const { itemIdToRemove } = action.payload; const indexToRemoveEpic = state.epics.findIndex(epic => epic.id === itemIdToRemove); const removedEpic = draft.epics.splice(indexToRemoveEpic, 1)[0]; draft.selectedItemId = undefined; // Remove the project if it's the last epic in the project if (!draft.epics.some(epic => epic.project === removedEpic.project)) { const indexToRemoveProject = state.projects.findIndex(project => project.id === removedEpic.project); draft.projects.splice(indexToRemoveProject, 1); } // Remove team if all team items have been removed. Object.keys(draft.teams).forEach(teamId => { if (!draft.epics.some(epic => epic.teamId === teamId)) { delete draft.teams[teamId]; } }); }); }
the_stack
import { LogTypes, StorageTypes } from '@requestnetwork/types'; import Utils from '@requestnetwork/utils'; import * as Bluebird from 'bluebird'; import { EventEmitter } from 'events'; import { getMaxConcurrency } from './config'; import ethereumEntriesToIpfsContent from './ethereum-entries-to-ipfs-content'; import EthereumMetadataCache from './ethereum-metadata-cache'; import IgnoredDataIds from './ignored-dataIds'; import SmartContractManager from './smart-contract-manager'; import * as Keyv from 'keyv'; // time to wait before considering the web3 provider is not reachable const WEB3_PROVIDER_TIMEOUT = 10000; /** * EthereumStorage * @notice Manages storage layer of the Request Network Protocol v2 */ export class EthereumStorage implements StorageTypes.IStorage { /** * Manager for the storage smart contract * This attribute is left public for mocking purpose to facilitate tests on the module */ public smartContractManager: SmartContractManager; /** * Storage for IPFS */ private ipfsStorage: StorageTypes.IIpfsStorage; /** * Cache to store Ethereum metadata */ public ethereumMetadataCache: EthereumMetadataCache; /** Data ids ignored by the node */ public ignoredDataIds: IgnoredDataIds; /** * Maximum number of concurrent calls */ public maxConcurrency: number; /** * Timestamp of the dataId not mined on ethereum yet */ private buffer: { [id: string]: number | undefined }; /** * Url where can be reached the data buffered by this storage */ private externalBufferUrl: string; /** * Logger instance */ private logger: LogTypes.ILogger; private isInitialized = false; /** * Constructor * @param ipfsGatewayConnection Information structure to connect to the ipfs gateway * @param web3Connection Information structure to connect to the Ethereum network * @param [options.getLastBlockNumberDelay] the minimum delay to wait between fetches of lastBlockNumber * @param metadataStore a Keyv store to persist the metadata in ethereumMetadataCache */ public constructor( externalBufferUrl: string, ipfsStorage: StorageTypes.IIpfsStorage, web3Connection?: StorageTypes.IWeb3Connection, { getLastBlockNumberDelay, logger, maxConcurrency, maxRetries, retryDelay, }: { getLastBlockNumberDelay?: number; logger?: LogTypes.ILogger; maxConcurrency?: number; maxRetries?: number; retryDelay?: number; } = {}, metadataStore?: Keyv.Store<any>, ) { this.maxConcurrency = maxConcurrency || getMaxConcurrency(); this.logger = logger || new Utils.SimpleLogger(); this.ipfsStorage = ipfsStorage; this.smartContractManager = new SmartContractManager(web3Connection, { getLastBlockNumberDelay, logger: this.logger, maxConcurrency: this.maxConcurrency, maxRetries, retryDelay, }); this.ethereumMetadataCache = new EthereumMetadataCache(metadataStore); this.ignoredDataIds = new IgnoredDataIds(metadataStore); this.buffer = {}; this.externalBufferUrl = externalBufferUrl; } /** * Function to initialize the storage * Checks the connection with ipfs * Checks the connection with Ethereum * Adds the known IPFS node (ipfs swarm connect) */ public async initialize(): Promise<void> { if (this.isInitialized) { throw new Error('ethereum-storage is already initialized'); } // check ethereum node connection - will throw if the ethereum node is not reachable this.logger.info('Checking ethereum node connection', ['ethereum', 'sanity']); try { await this.smartContractManager.checkWeb3ProviderConnection(WEB3_PROVIDER_TIMEOUT); } catch (error) { throw Error(`Ethereum node is not accessible: ${error}`); } // check if contracts are deployed on ethereum this.logger.info('Checking ethereum node contract deployment', ['ethereum', 'sanity']); try { await this.smartContractManager.checkContracts(); } catch (error) { throw Error(error); } // Check IPFS node state - will throw in case of error await this.ipfsStorage.initialize(); this.isInitialized = true; } /** * Update Ethereum network connection information and reconnect * Missing value are filled with default config value * @param web3Connection Information structure to connect to the Ethereum network */ public async updateEthereumNetwork(web3Connection: StorageTypes.IWeb3Connection): Promise<void> { this.smartContractManager = new SmartContractManager(web3Connection); // check ethereum node connection - will throw if the ethereum node is not reachable try { await this.smartContractManager.checkWeb3ProviderConnection(WEB3_PROVIDER_TIMEOUT); } catch (error) { throw Error(`Ethereum node is not accessible: ${error}`); } } /** * Append content into the storage: add the content to ipfs and the hash on Ethereum * @param content Content to add into the storage * @returns Promise resolving id used to retrieve the content */ public async append(content: string): Promise<StorageTypes.IAppendResult> { if (!this.isInitialized) { throw new Error('Ethereum storage must be initialized'); } const { ipfsHash, ipfsSize } = await this.ipfsStorage.ipfsAdd(content); const timestamp = Utils.getCurrentTimestampInSecond(); const result: StorageTypes.IAppendResult = Object.assign(new EventEmitter(), { content, id: ipfsHash, meta: { ipfs: { size: ipfsSize }, local: { location: this.externalBufferUrl }, state: StorageTypes.ContentState.PENDING, storageType: StorageTypes.StorageSystemType.LOCAL, timestamp, }, }); // store in the buffer the timestamp this.buffer[ipfsHash] = timestamp; const feesParameters: StorageTypes.IFeesParameters = { contentSize: ipfsSize }; this.smartContractManager .addHashAndSizeToEthereum(ipfsHash, feesParameters) .then(async (ethereumMetadata: StorageTypes.IEthereumMetadata) => { const resultAfterBroadcast: StorageTypes.IEntry = { content, id: ipfsHash, meta: { ethereum: ethereumMetadata, ipfs: { size: ipfsSize }, state: StorageTypes.ContentState.CONFIRMED, storageType: StorageTypes.StorageSystemType.ETHEREUM_IPFS, timestamp: ethereumMetadata.blockTimestamp, }, }; // Save the metadata of the new ipfsHash into the Ethereum metadata cache await this.ethereumMetadataCache.saveDataIdMeta(ipfsHash, ethereumMetadata); result.emit('confirmed', resultAfterBroadcast); }) .catch((error) => { result.emit('error', error); }); return result; } /** * Read content from the storage * @param Id Id used to retrieve content * @returns Promise resolving content from id */ public async read(id: string): Promise<StorageTypes.IEntry> { if (!this.isInitialized) { throw new Error('Ethereum storage must be initialized'); } if (!id) { throw Error('No id provided'); } // Get Ethereum metadata let bufferTimestamp: number | undefined; // Check if the data as been added on ethereum const ethereumMetadata = await this.ethereumMetadataCache.getDataIdMeta(id); // Clear buffer if needed if (!ethereumMetadata) { bufferTimestamp = this.buffer[id]; if (!bufferTimestamp) { throw Error('No content found from this id'); } } else { delete this.buffer[id]; } const ipfsObject = await this.ipfsStorage.read(id); const meta = ethereumMetadata ? { ethereum: ethereumMetadata, ipfs: { size: ipfsObject.ipfsSize }, state: StorageTypes.ContentState.CONFIRMED, storageType: StorageTypes.StorageSystemType.ETHEREUM_IPFS, timestamp: ethereumMetadata.blockTimestamp, } : { ipfs: { size: ipfsObject.ipfsSize }, local: { location: this.externalBufferUrl }, state: StorageTypes.ContentState.PENDING, storageType: StorageTypes.StorageSystemType.LOCAL, timestamp: bufferTimestamp || 0, }; return { content: ipfsObject.content, id, meta, }; } /** * Read a list of content from the storage * * @param dataIds A list of dataIds used to retrieve the content * @returns Promise resolving the list of contents */ public async readMany(dataIds: string[]): Promise<StorageTypes.IEntry[]> { const totalCount = dataIds.length; // Concurrently get all the content from the id's in the parameters return Bluebird.map( dataIds, async (dataId, currentIndex) => { const startTime = Date.now(); const data = await this.read(dataId); this.logger.debug( `[${currentIndex + 1}/${totalCount}] read ${dataId}. Took ${Date.now() - startTime} ms`, ['read'], ); return data; }, { concurrency: this.maxConcurrency, }, ); } /** * Get all data stored on the storage * * @param options timestamp boundaries for the data retrieval * @returns Promise resolving stored data */ public async getData( options?: StorageTypes.ITimestampBoundaries, ): Promise<StorageTypes.IEntriesWithLastTimestamp> { if (!this.isInitialized) { throw new Error('Ethereum storage must be initialized'); } this.logger.info('Fetching dataIds from Ethereum', ['ethereum']); const { ethereumEntries, lastTimestamp } = await this.smartContractManager.getEntriesFromEthereum(options); // If no hash was found on ethereum, we return an empty list if (!ethereumEntries.length) { this.logger.info('No new data found.', ['ethereum']); return { entries: [], lastTimestamp, }; } this.logger.debug('Fetching data from IPFS and checking correctness', ['ipfs']); const entries = await ethereumEntriesToIpfsContent( ethereumEntries, this.ipfsStorage, this.ignoredDataIds, this.logger, this.maxConcurrency, ); const ids = entries.map((entry) => entry.id) || []; // Pin data asynchronously // eslint-disable-next-line @typescript-eslint/no-floating-promises this.ipfsStorage.pinDataToIPFS(ids); // Save existing ethereum metadata to the ethereum metadata cache for (const entry of entries) { const ethereumMetadata = entry.meta.ethereum; if (ethereumMetadata) { // PROT-504: The saving of dataId's metadata should be encapsulated when retrieving dataId inside smart contract (getPastEvents) await this.ethereumMetadataCache.saveDataIdMeta(entry.id, ethereumMetadata); } } return { entries, lastTimestamp, }; } /** * Try to get some previous ignored data * * @param options timestamp boundaries for the data retrieval * @returns Promise resolving stored data */ public async getIgnoredData(): Promise<StorageTypes.IEntry[]> { if (!this.isInitialized) { throw new Error('Ethereum storage must be initialized'); } this.logger.info('Getting some previous ignored dataIds', ['ethereum']); const ethereumEntries: StorageTypes.IEthereumEntry[] = await this.ignoredDataIds.getDataIdsToRetry(); // If no hash was found on ethereum, we return an empty list if (!ethereumEntries.length) { this.logger.info('No new data found.', ['ethereum']); return []; } this.logger.debug('Fetching data from IPFS and checking correctness', ['ipfs']); const entries = await ethereumEntriesToIpfsContent( ethereumEntries, this.ipfsStorage, this.ignoredDataIds, this.logger, this.maxConcurrency, ); const ids = entries.map((entry) => entry.id) || []; // Pin data asynchronously void this.ipfsStorage.pinDataToIPFS(ids); // Save existing ethereum metadata to the ethereum metadata cache for (const entry of entries) { const ethereumMetadata = entry.meta.ethereum; if (ethereumMetadata) { // PROT-504: The saving of dataId's metadata should be encapsulated when retrieving dataId inside smart contract (getPastEvents) await this.ethereumMetadataCache.saveDataIdMeta(entry.id, ethereumMetadata); } } return entries; } /** * Get Information on the dataIds retrieved and ignored by the ethereum storage * * @param detailed if true get the list of the files hash * @returns Promise resolving object with dataIds retrieved and ignored */ public async _getStatus(detailed = false): Promise<any> { const dataIds = await this.ethereumMetadataCache.getDataIds(); const dataIdsWithReason = await this.ignoredDataIds.getDataIdsWithReasons(); const ethereum = this.smartContractManager.getConfig(); const ipfs = await this.ipfsStorage.getConfig(); return { dataIds: { count: dataIds.length, values: detailed ? dataIds : undefined, }, ethereum, ignoredDataIds: { count: Object.keys(dataIdsWithReason).length, values: detailed ? dataIdsWithReason : undefined, }, ipfs, }; } }
the_stack
* @module DisplayStyles */ import { assert, Id64String } from "@itwin/core-bentley"; import { ModelMapLayerSettings } from "./MapLayerSettings"; /** Describes how a [[SpatialClassifier]] affects the display of classified geometry - that is, geometry intersecting * the classifier. * @public * @extensions */ export enum SpatialClassifierInsideDisplay { /** The geometry is not displayed. */ Off = 0, /** The geometry is displayed without alteration. */ On = 1, /** The geometry is darkened. */ Dimmed = 2, /** The geometry is tinted by the [Viewport.hilite]($frontend) color. */ Hilite = 3, /** The geometry is tinted with the colors of the classifier elements. */ ElementColor = 4, } /** Describes how a [[SpatialClassifier]] affects the display of unclassified geometry - that is, geometry not intersecting * the classifier. * @public * @extensions */ export enum SpatialClassifierOutsideDisplay { /** The geometry is not displayed. */ Off = 0, /** The geometry is displayed without alteration. */ On = 1, /** The geometry is darkened. */ Dimmed = 2, } /** JSON representation of a [[SpatialClassifierFlags]]. * @public * @extensions */ export interface SpatialClassifierFlagsProps { /** @see [[SpatialClassifierFlags.inside]]. */ inside: SpatialClassifierInsideDisplay; /** @see [[SpatialClassifierFlags.outside]]. */ outside: SpatialClassifierOutsideDisplay; /** @see [[SpatialClassifierFlags.isVolumeClassifier]]. */ isVolumeClassifier?: boolean; } /** Flags affecting how a [[SpatialClassifier]] is applied. * @public */ export class SpatialClassifierFlags { /** How geometry intersecting the classifier should be displayed. */ public readonly inside: SpatialClassifierInsideDisplay; /** How geometry not intersecting the classifier should be displayed. */ public readonly outside: SpatialClassifierOutsideDisplay; /** True for volume classification; false for planar classification. */ public readonly isVolumeClassifier: boolean; /** Construct new flags. */ public constructor(inside = SpatialClassifierInsideDisplay.ElementColor, outside = SpatialClassifierOutsideDisplay.Dimmed, isVolumeClassifier = false) { this.inside = insideDisplay(inside); this.outside = outsideDisplay(outside); this.isVolumeClassifier = isVolumeClassifier; } /** Construct from JSON representation. */ public static fromJSON(props: SpatialClassifierFlagsProps): SpatialClassifierFlags { return new SpatialClassifierFlags(props.inside, props.outside, true === props.isVolumeClassifier); } /** Convert to JSON representation. */ public toJSON(): SpatialClassifierFlagsProps { const props: SpatialClassifierFlagsProps = { inside: this.inside, outside: this.outside, }; if (this.isVolumeClassifier) props.isVolumeClassifier = true; return props; } /** Create flags indentical to these ones except for any properties explicitly specified by `changedProps`. */ public clone(changedProps?: Partial<SpatialClassifierFlagsProps>): SpatialClassifierFlags { if (!changedProps) return this; return SpatialClassifierFlags.fromJSON({ ...this.toJSON(), ...changedProps }); } /** Return true if these flags are equivalent to `other`. */ public equals(other: SpatialClassifierFlags): boolean { if (other === this) return true; return other.inside === this.inside && other.outside === this.outside && other.isVolumeClassifier === this.isVolumeClassifier; } /** Return true if these flags are equivalent to `props`. */ public equalsProps(props: SpatialClassifierFlagsProps): boolean { return this.inside === props.inside && this.outside === props.outside && this.isVolumeClassifier === (true === props.isVolumeClassifier); } } /** JSON representation of a [[SpatialClassifier]]. * @public * @extensions */ export interface SpatialClassifierProps { /** @see [[SpatialClassifier.modelId]]. */ modelId: Id64String; /** @see [[SpatialClassifier.expand]]. */ expand: number; /** @see [[SpatialClassifier.flags]]. */ flags: SpatialClassifierFlagsProps; /** @see [[SpatialClassifier.name]]. */ name: string; /** Records whether this is the active classifier. * @see [[SpatialClassifier.active]]. */ isActive?: boolean; } /** Describes how to use the geometry of one [GeometricModel]($backend) to classify the contents of other models - most typically, reality models. * Applying a classifier divides the geometry of the classified model into two groups: * - Classified (intersecting the classifier); and * - Unclassified (not intersecting the classifier). * For example, a model containing the building footprints for a city block could be used to classify a reality mesh captured from photographs of the * real-world block. Then, buildings within the reality mesh can be selected individually, and present the properties of the classifier geometry (e.g., * the address of the building). The appearance of the geometry can also be customized based using [[SpatialClassifierInsideDisplay]] and [[SpatialClassifierOutsideDisplay]]. * Two types of classification are supported: * - Planar classification, in which the geometry of the classifier model is projected onto a plane to classify geometry within a region extruded perpendicular * the plane (e.g., the building footprints example); and * - Volume classification, in which closed volumes within the classifier classify geometry that intersects those same volumes (e.g., imagine using boxes instead * of footprints to classify buildings, or floors of buildings). * @see this (interactive example)[https://www.itwinjs.org/sample-showcase/?group=Viewer+Features&sample=classifier-sample]. * @see [[SpatialClassifiers]] to define a set of classifiers. * @see [[ContextRealityModel.classifiers]] to classify a context reality model. * @see [SpatialModelState.classifiers]($frontend) to classify a persistent reality model. * @public */ export class SpatialClassifier { /** The Id of the [GeometricModel]($backend) whose geometry is used to produce the classifier. */ public readonly modelId: Id64String; /** A distance in meters by which to expand the classifier geometry. For example, if line strings are used to represent streets, * you might expand them to the average width of a street. */ public readonly expand: number; /** Flags controlling how to apply the classifier. */ public readonly flags: SpatialClassifierFlags; /** A user-friendly name, useful for identifying individual classifiers within a [[SpatialClassifiers]]. */ public readonly name: string; /** Construct a new classifier. */ public constructor(modelId: Id64String, name: string, flags = new SpatialClassifierFlags(), expand = 0) { this.modelId = modelId; this.expand = expand; this.flags = flags; this.name = name; } /** Construct from JSON representation. */ public static fromJSON(props: SpatialClassifierProps): SpatialClassifier { return new SpatialClassifier(props.modelId, props.name, SpatialClassifierFlags.fromJSON(props.flags), props.expand); } /** Convert to JSON representation. * @note This method always sets the [[SpatialClassifierProps.isActive]] property to `false`. */ public toJSON(): SpatialClassifierProps { return { modelId: this.modelId, expand: this.expand, flags: this.flags.toJSON(), name: this.name, isActive: false, }; } /** Construct from Model Map Layer. * @beta */ public static fromModelMapLayer(mapLayer: ModelMapLayerSettings): SpatialClassifier { const flags = SpatialClassifierFlags.fromJSON({ inside: SpatialClassifierInsideDisplay.Off, outside: SpatialClassifierOutsideDisplay.Off }); return new SpatialClassifier(mapLayer.modelId, mapLayer.name, flags); } /** Create a classifier identical to this one except for any properties explicitly specified by `changedProps`. */ public clone(changedProps?: Partial<SpatialClassifierProps>): SpatialClassifier { if (!changedProps) return this; return SpatialClassifier.fromJSON({ ...this.toJSON(), ...changedProps }); } /** Return true if this classifier is equivalent to `other`. */ public equals(other: SpatialClassifier): boolean { if (other === this) return true; return this.modelId === other.modelId && this.expand === other.expand && this.name === other.name && this.flags.equals(other.flags); } /** Return true if this classifier is equivalent to `props`. */ public equalsProps(props: SpatialClassifierProps): boolean { return this.modelId === props.modelId && this.expand === props.expand && this.name === props.name && this.flags.equalsProps(props.flags); } } /** An object that can store the JSON representation of a list of [[SpatialClassifier]]s. * @see [[SpatialClassifiers]]. * @public * @extensions */ export interface SpatialClassifiersContainer { /** The list of classifiers. */ classifiers?: SpatialClassifierProps[]; } /** A set of [[SpatialClassifier]]s for a given reality model. At most one of the classifiers can be actively classifying the model at any given time. * The set of classifiers can be presented to the user, listed by name, so that the active classifier can be changed. * The set of classifiers is populated from its JSON representation and that representation is kept in sync as the set of classifiers is modified. * @see this (interactive example)[https://www.itwinjs.org/sample-showcase/?group=Viewer+Features&sample=classifier-sample]. * @see [[SpatialClassifier]] for details on how spatial classification works. * @see [[ContextRealityModel.classifiers]] to define classifiers for a context reality model. * @see [SpatialModelState.classifiers]($frontend) to define classifiers for a persistent reality model. * @public */ export class SpatialClassifiers implements Iterable<SpatialClassifier> { private readonly _json: SpatialClassifiersContainer; private readonly _classifiers: SpatialClassifier[] = []; private _active?: SpatialClassifier; /** Construct a new set of classifiers from the JSON representation. The set will be initialized from `container.classifiers` and that JSON representation * will be kept in sync with changes made to the set. The caller should not directly modify `container.classifiers` or its contents as that will cause the set to become out * of sync with the JSON representation. * The [[active]] classifier will be determined by the first [[SpatialClassifierProps]] whose `isActive` property is set to `true`, if any. */ public constructor(container: SpatialClassifiersContainer) { this._json = container; const json = this._array; if (!json) return; for (const props of json) { const classifier = SpatialClassifier.fromJSON(props); this._classifiers.push(classifier); if (props.isActive) { if (!this._active) this._active = classifier; else props.isActive = false; } } } /** The classifier currently classifying the target reality model. The classifier passed to the setter must be one obtained from this set, or one equivalent to * one contained in this set; in the latter case, the equivalent classifier contained in this set becomes active. */ /** The classifier currently classifying the target reality model, if any. * @see [[setActive]] to change the active classifier. */ public get active(): SpatialClassifier | undefined { return this._active; } /** Change the [[active]] classifier. The input must be a classifier belonging to this set, or equivalent to one in the set. * If no equivalent classifier exists in the set, the active classifier remains unchanged. * @param The classifier to set as active, or `undefined` to clear the active classifier. * @returns the active classifier. */ public setActive(active: SpatialClassifier | undefined): SpatialClassifier | undefined { const array = this._array; if (!array) return this.active; if (active) { active = this.findEquivalent(active); if (!active) return this.active; } if (active === this.active) return this.active; let propsIndex = -1; if (active) { propsIndex = array.findIndex((x) => active!.equalsProps(x)); if (-1 === propsIndex) return this.active; } this._active = active; for (let i = 0; i < array.length; i++) array[i].isActive = (i === propsIndex); return this.active; } /** Obtain an iterator over the classifiers contained in this set. */ public [Symbol.iterator](): Iterator<SpatialClassifier> { return this._classifiers[Symbol.iterator](); } /** The number of classifiers in this set. */ public get size(): number { return this._array?.length ?? 0; } /** Returns the first classifier that satisfies `criterion`, or `undefined` if no classifier satisfies it. */ public find(criterion: (classifier: SpatialClassifier) => boolean): SpatialClassifier | undefined { return this._classifiers.find(criterion); } /** Find the first classifier that is equivalent to the supplied classifier, or `undefined` if no equivalent classifier exists in this set. */ public findEquivalent(classifier: SpatialClassifier): SpatialClassifier | undefined { return this.find((x) => x.equals(classifier)); } /** Return true if the specified classifier or one equivalent to it exists in this set. */ public has(classifier: SpatialClassifier): boolean { return undefined !== this.findEquivalent(classifier); } /** Add a classifier to this set. If an equivalent classifier already exists, the supplied classifier is not added. * @param classifier The classifier to add. * @returns The equivalent pre-existing classifier, if one existed; or the supplied classifier, if it was added to the set. */ public add(classifier: SpatialClassifier): SpatialClassifier { const existing = this.findEquivalent(classifier); if (existing) return existing; let array = this._array; if (!array) array = this._json.classifiers = []; this._classifiers.push(classifier); array.push(classifier.toJSON()); return classifier; } /** Replace an existing classifier with a different one. * @param toReplace The classifier to be replaced. * @param replacement The classifier to replace `toReplace`. * @returns true if a classifier equivalent to `toReplace` existed in the set and was replaced by `replacement`. * @note If `toReplace` was the [[active]] classifier, `replacement` will become active. */ public replace(toReplace: SpatialClassifier, replacement: SpatialClassifier): boolean { const list = this._array; if (!list) return false; const classifierIndex = this._classifiers.findIndex((x) => x.equals(toReplace)); if (-1 === classifierIndex) return false; const propsIndex = list.findIndex((x) => toReplace.equalsProps(x)); assert(propsIndex === classifierIndex); if (-1 === propsIndex) return false; toReplace = this._classifiers[classifierIndex]; const wasActive = this.active === toReplace; this._classifiers[classifierIndex] = replacement; const props = list[propsIndex] = replacement.toJSON(); if (wasActive) { props.isActive = true; this._active = replacement; } return true; } /** Remove the first classifier equivalent to `classifier` from this set. * @param classifier The classifier to remove. * @returns The classifier that was actually removed, or `undefined` if none was removed. */ public delete(classifier: SpatialClassifier): SpatialClassifier | undefined { const list = this._array; if (!list) return undefined; const classifierIndex = this._classifiers.findIndex((x) => x.equals(classifier)); if (-1 === classifierIndex) return undefined; classifier = this._classifiers[classifierIndex]; const propsIndex = list.findIndex((x) => classifier.equalsProps(x)); assert(propsIndex === classifierIndex); if (-1 === propsIndex) return undefined; list.splice(propsIndex, 1); this._classifiers.splice(classifierIndex, 1); if (list.length === 0) this._json.classifiers = undefined; if (classifier === this.active) this._active = undefined; return classifier; } /** Remove all classifiers from this set. */ public clear(): void { this._classifiers.length = 0; this._json.classifiers = undefined; this._active = undefined; } private get _array(): SpatialClassifierProps[] | undefined { return Array.isArray(this._json.classifiers) ? this._json.classifiers : undefined; } } function insideDisplay(display: number): SpatialClassifierInsideDisplay { switch (display) { case SpatialClassifierInsideDisplay.Off: case SpatialClassifierInsideDisplay.On: case SpatialClassifierInsideDisplay.Dimmed: case SpatialClassifierInsideDisplay.Hilite: case SpatialClassifierInsideDisplay.ElementColor: return display; default: return SpatialClassifierInsideDisplay.ElementColor; } } function outsideDisplay(display: number): SpatialClassifierOutsideDisplay { switch (display) { case SpatialClassifierOutsideDisplay.Off: case SpatialClassifierOutsideDisplay.On: case SpatialClassifierOutsideDisplay.Dimmed: return display; default: return SpatialClassifierOutsideDisplay.Dimmed; } }
the_stack
import { AfterContentInit, ContentChildren, Directive, ElementRef, HostBinding, Inject, Input, NgZone, OnDestroy, QueryList, Renderer2 } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { MDCTopAppBarAdapter, MDCTopAppBarBaseFoundation, MDCTopAppBarFoundation, MDCFixedTopAppBarFoundation, MDCShortTopAppBarFoundation } from '@material/top-app-bar'; import { events } from '@material/dom'; import { asBoolean, asBooleanOrNull } from '../../utils/value.utils'; /** * A directive for a top-app-bar row. The content of a top-app-bar should always be embedded * in <code>mdcTopAppBarRow</code> rows. Multiple rows are allowed, which rows are visible * depends on the style of the toolbar, and the scroll position of the content of * the page. */ @Directive({ selector: '[mdcTopAppBarRow]' }) export class MdcTopAppBarRowDirective { /** @internal */ @HostBinding('class.mdc-top-app-bar__row') readonly _cls = true; constructor(public _elm: ElementRef) { } } /** * A directive for a top-app-bar section. A top-app-bar row should always be composed of * <code>mdcTopAppBarSection</code> sections. Multiple sections, with different alignment options, * are allowed per row. */ @Directive({ selector: '[mdcTopAppBarSection]' }) export class MdcTopAppBarSectionDirective { /** @internal */ @HostBinding('class.mdc-top-app-bar__section') readonly _cls = true; private _alignEnd = false; private _alignStart = false; /** * Make the section align to the start of the toolbar row (default alignment is to the * center). */ @Input() @HostBinding('class.mdc-top-app-bar__section--align-start') get alignStart() { return this._alignStart; } set alignStart(val: boolean) { this._alignStart = asBoolean(val); } static ngAcceptInputType_alignStart: boolean | ''; /** * Make the section align to the end of the toolbar row (default alignment is to the * center). */ @Input() @HostBinding('class.mdc-top-app-bar__section--align-end') get alignEnd() { return this._alignEnd; } set alignEnd(val: boolean) { this._alignEnd = asBoolean(val); } static ngAcceptInputType_alignEnd: boolean | ''; } /** * This directive adds extra styling to toolbar text that represents the title of the toolbar. * The directive should be a child of an element with the <code>mdcTopAppBarSection</code> directive. */ @Directive({ selector: '[mdcTopAppBarTitle]' }) export class MdcTopAppBarTitleDirective { /** @internal */ @HostBinding('class.mdc-top-app-bar__title') readonly _cls = true; constructor(public _elm: ElementRef) { } } /** * Directive for the navigation icon of a top-app-bar. Typically placed on the * far left (for left-to-right languages). The <code>mdcTopAppBarNavIcon</code> * directive should be used on a child of an element with the * <code>mdcTopAppBarSection</code> directive. It typically opens a navigation menu * or drawer. */ @Directive({ selector: '[mdcTopAppBarNavIcon]' }) export class MdcTopAppBarNavIconDirective { /** @internal */ @HostBinding('class.mdc-top-app-bar__navigation-icon') readonly _cls = true; constructor(public _elm: ElementRef) { } } /** * Directive for action items of a top-app-bar. Typically placed on the side * opposite the navigation item. The <code>mdcTopAppBarAction</code> directive * should be used on a child of an element with the <code>mdcTopAppBarSection</code> * directive. */ @Directive({ selector: '[mdcTopAppBarAction]' }) export class MdcTopAppBarActionDirective { /** @internal */ @HostBinding('class.mdc-top-app-bar__action-item') readonly _cls = true; /** * A label for the action item. The value will be applied to both the * <code>aria-label</code>, and <code>alt</code> attribute of the item. */ @Input() @HostBinding('attr.aria-label') @HostBinding('attr.alt') label: string | null = null; constructor(public _elm: ElementRef) { } } /** * A directive for a top-app-bar. All content inside a top-app-bar should be * embedded inside <code>mdcTopAppBarRow</code> rows. */ @Directive({ selector: '[mdcTopAppBar]' }) export class MdcTopAppBarDirective implements AfterContentInit, OnDestroy { /** @internal */ @HostBinding('class.mdc-top-app-bar') readonly _cls = true; private document: Document; /** @internal */ @ContentChildren(MdcTopAppBarActionDirective, {descendants: true}) _actionItems?: QueryList<MdcTopAppBarActionDirective>; private handleScroll = () => { if (this.viewport && (this._type === 'short' || this._type === 'fixed')) this._updateViewPort(); this.foundation?.handleTargetScroll(); } private handleResize = () => { if (this.viewport && (this._type === 'short' || this._type === 'fixed')) this._updateViewPort(); this.foundation?.handleWindowResize(); } private updateViewport = () => { if (this.viewport && (this._type === 'short' || this._type === 'fixed')) this._updateViewPort(); } private _viewport: HTMLElement | null = null; private _fixedAdjust: HTMLElement | null = null; private _type: 'short' | 'fixed' | 'default' = 'default'; private _prominent = false; private _dense = false; private _collapsedOverride: boolean | null = null; private _collapsedState: boolean | null = null; private mdcAdapter: MDCTopAppBarAdapter = { hasClass: (className: string) => { if (className === 'mdc-top-app-bar--short-collapsed') // the foundation uses this during initialisation to determine whether // a short top-app-bar should always be displayed collapsed. // our component instead uses the _collapsed field value to override // the collapsed state return false; return this._elm.nativeElement.classList.contains(className); }, addClass: (className: string) => { if (className === 'mdc-top-app-bar--short-collapsed') this._collapsedState = true; else if (className !== 'mdc-top-app-bar--short-has-action-item') // we add/remove mdc-top-app-bar--short-has-action-item dynamically based on the actual number of items // this is better than the foundation that looks only at the nr of items during initialisation this._rndr.addClass(this._elm.nativeElement, className); }, removeClass: (className: string) => { if (className === 'mdc-top-app-bar--short-collapsed') this._collapsedState = false; else this._rndr.removeClass(this._elm.nativeElement, className); }, setStyle: (property, value) => this._rndr.setStyle(this._elm.nativeElement, property, value), getTopAppBarHeight: () => this._elm.nativeElement.clientHeight, notifyNavigationIconClicked: () => {}, // not a special event in our implementation getViewportScrollY: () => this._viewport ? this._viewport.scrollTop : this.document.defaultView!.pageYOffset, getTotalActionItems: () => this._actionItems!.length }; private foundation: MDCTopAppBarBaseFoundation | null = null; constructor(private _rndr: Renderer2, private _elm: ElementRef, private zone: NgZone, @Inject(DOCUMENT) doc: any) { this.document = doc as Document; } ngAfterContentInit() { this.foundationReInit(); } ngOnDestroy() { this.removeScrollListeners(); this.foundation?.destroy(); this.foundation = null; } private foundationReInit() { if (this.foundation) this.foundation.destroy(); // undo viewport init specific for a foundation implementation: this.removeScrollListeners(); this._elm.nativeElement.style.top = null; // remove classes set by foundations, if we reinitialize/switch foundation: this._rndr.removeClass(this._elm.nativeElement, 'mdc-top-app-bar--fixed-scrolled'); if (this._type === 'short') this.foundation = new MDCShortTopAppBarFoundation(this.mdcAdapter); else if (this._type === 'fixed') this.foundation = new MDCFixedTopAppBarFoundation(this.mdcAdapter); else this.foundation = new MDCTopAppBarFoundation(this.mdcAdapter); this.initFixedAdjust(); this.zone.runOutsideAngular(() => { (this._viewport || this.document.defaultView!).addEventListener('scroll', this.handleScroll, events.applyPassive()); (this._viewport || this.document.defaultView!).addEventListener('touchmove', this.updateViewport, events.applyPassive()); this.document.defaultView!.addEventListener('resize', this.handleResize, events.applyPassive()); }); if (this.viewport && (this._type === 'short' || this._type === 'fixed')) this._updateViewPort(); this.foundation.init(); } private initFixedAdjust() { if (this.foundation && this._fixedAdjust) { this._rndr.removeClass(this._fixedAdjust, 'mdc-top-app-bar--fixed-adjust'); this._rndr.removeClass(this._fixedAdjust, 'mdc-top-app-bar--dense-fixed-adjust'); this._rndr.removeClass(this._fixedAdjust, 'mdc-top-app-bar--short-fixed-adjust'); this._rndr.removeClass(this._fixedAdjust, 'mdc-top-app-bar--prominent-fixed-adjust'); this._rndr.removeClass(this._fixedAdjust, 'mdc-top-app-bar--dense-prominent-fixed-adjust'); if (this.prominent && this.dense) this._rndr.addClass(this._fixedAdjust, 'mdc-top-app-bar--dense-prominent-fixed-adjust'); else if (this._prominent) this._rndr.addClass(this._fixedAdjust, 'mdc-top-app-bar--prominent-fixed-adjust'); else if (this._type === 'short') this._rndr.addClass(this._fixedAdjust, 'mdc-top-app-bar--short-fixed-adjust'); else if (this._dense) this._rndr.addClass(this._fixedAdjust, 'mdc-top-app-bar--dense-fixed-adjust'); else this._rndr.addClass(this._fixedAdjust, 'mdc-top-app-bar--fixed-adjust'); } } private removeScrollListeners() { (this._viewport || this.document.defaultView!).removeEventListener('scroll', this.handleScroll, events.applyPassive()); (this._viewport || this.document.defaultView!).removeEventListener('touchmove', this.updateViewport, events.applyPassive()); this.document.defaultView!.removeEventListener('resize', this.handleResize, events.applyPassive()); } /** * The top-app-bar can have different styles. Set this property to <code>fixed</code> * for a top-app-bar fixed to the top of the screen or viewport. * Set to <code>short</code> for a top-app-bar that will collapse to the navigation * icon side when scrolled. * Otherwise, the default is a top-app-bar that scrolls with the content. */ @Input() get mdcTopAppBar() { return this._type; } set mdcTopAppBar(val) { if (val !== 'short' && val !== 'fixed') val = 'default'; if (val !== this._type) { this._type = val; if (this.foundation) this.foundationReInit(); } } static ngAcceptInputType_mdcTopAppBar: 'short' | 'fixed' | 'default' | ''; /** * If set to a value other than false, the top-app-bar will be styled as a taller * bar. */ @Input() @HostBinding('class.mdc-top-app-bar--prominent') get prominent() { return this._prominent; } set prominent(val: boolean) { let newValue = asBoolean(val); if (newValue !== this._prominent) { this._prominent = asBoolean(val); this.initFixedAdjust(); } } static ngAcceptInputType_prominent: boolean | ''; /** * If set to a value other than false, the top-app-bar will be styled a bit more * compact. */ @Input() @HostBinding('class.mdc-top-app-bar--dense') get dense() { return this._dense; } set dense(val: boolean) { let newValue = asBoolean(val); if (newValue !== this._dense) { this._dense = asBoolean(val); this.initFixedAdjust(); } } static ngAcceptInputType_dense: boolean | ''; /** * Set this property to true or false to force the collapsed/uncollapsed state of a short * top-app-bar. Set this property to null to return to the default handling, where * <code>collapsed</code> is based on the scroll position of the viewport. * This property has no effect if the <code>mdcTopAppBar</code> has a value other than * <code>short</code>. */ @Input() @HostBinding('class.mdc-top-app-bar--short-collapsed') get collapsed() { if (this._type !== 'short') return false; return this._collapsedOverride == null ? !!this._collapsedState : this._collapsedOverride; } set collapsed(val: boolean) { this._collapsedOverride = asBooleanOrNull(val); } static ngAcceptInputType_collapsed: boolean | ''; /** * Top-app-bars are positioned over the rest of their viewport. This means that * some of the content will be hidden under the bar, unless the position of that * content is changed relative to the bar. Assign the <code>HTMLElement</code> * of the content to this property, so that the <code>mdcTopAppBar</code> * can add spacing to the content making the top visible when the content is scrolled * up. */ @Input() get fixedAdjust() { return this._fixedAdjust; } set fixedAdjust(el: HTMLElement | null) { if (this._fixedAdjust !== el) { this._fixedAdjust = el; this.initFixedAdjust(); } } /** * Assign any <code>HTMLElement</code> to this property to place a top-app-bar fixed to that element * (usually the parent container), instead of to the browser window. This property is mainly added for creating nice * demos of toolbars embedded inside other pages (such as on this documentation page). It is not recommended to use * this for a real application toolbar. The position is kept fixed to the container element by listening * for scroll/resize events, and using javascript to recompute the position. This may influence the smoothness * of the scrolling experience, especially on mobile devices. * The viewport element must have css styling: <code>position: relative</code>, and should have a fixed * height. */ @Input() get viewport() { return this._viewport; } set viewport(elm: HTMLElement | null) { if (this._viewport !== elm) { this.removeScrollListeners(); this._viewport = elm; if (this.foundation) this.foundationReInit(); } } /** @internal */ @HostBinding('class.mdc-top-app-bar--short-has-action-item') get _hasActionItems() { return this._type === 'short' && this._actionItems!.length > 0; } /** @internal */ _updateViewPort = () => { // simulate 'fixed' relative to view position of parent: this._elm.nativeElement.style.top = this._viewport!.scrollTop + 'px'; } /** @internal */ @HostBinding('class.mdc-top-app-bar--fixed') get _fixed() { return this._type === 'fixed'; } /** @internal */ @HostBinding('class.mdc-top-app-bar--short') get _short() { return this._type === 'short'; } /** @internal */ @HostBinding('style.position') get _position() { return this._viewport ? 'absolute' : null; } } export const TOP_APP_BAR_DIRECTIVES = [ MdcTopAppBarRowDirective, MdcTopAppBarSectionDirective, MdcTopAppBarTitleDirective, MdcTopAppBarNavIconDirective, MdcTopAppBarActionDirective, MdcTopAppBarDirective ];
the_stack