-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathcompliance.ts
More file actions
2333 lines (1884 loc) · 54.5 KB
/
compliance.ts
File metadata and controls
2333 lines (1884 loc) · 54.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
EnumFromScopedModule,
IDoublable,
IFriendly,
MyFirstStruct,
Number,
StructWithOnlyOptionals,
Value
} from '@scope/jsii-calc-lib';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import * as crypto from 'crypto';
import { promisify } from 'util';
import { IFriendlyRandomGenerator, IRandomNumberGenerator, Multiply } from './calculator';
const bundled = require('jsii-calc-bundled');
import base = require('@scope/jsii-calc-base');
const readFile = promisify(fs.readFile);
export enum AllTypesEnum {
MY_ENUM_VALUE,
YOUR_ENUM_VALUE = 100,
THIS_IS_GREAT
}
export enum StringEnum {
A = 'A!',
B = 'B?',
C = 'C.'
}
export class EnumDispenser {
public static randomStringLikeEnum(): StringEnum {
// Haha! I lied, it's not random!! *EVIL LAUGHTER*
return StringEnum.B;
}
public static randomIntegerLikeEnum(): AllTypesEnum {
// Haha! I lied, it's not random!! *EVIL LAUGHTER*
return AllTypesEnum.YOUR_ENUM_VALUE;
}
private constructor() { }
}
/**
* This class includes property for all types supported by jsii. The setters will validate
* that the value set is of the expected type and throw otherwise.
*/
export class AllTypes {
// boolean
private boolValue = false;
get booleanProperty() {
return this.boolValue;
}
set booleanProperty(value: boolean) {
if (typeof(value) !== 'boolean') {
throw new Error('not a boolean');
}
this.boolValue = value;
}
// string
private stringValue = 'first value';
get stringProperty() {
return this.stringValue;
}
set stringProperty(value: string) {
if (typeof(value) !== 'string') {
throw new Error('not a string');
}
this.stringValue = value;
}
// number
private numberValue = 0;
get numberProperty() {
return this.numberValue;
}
set numberProperty(value: number) {
if (typeof(value) !== 'number') {
throw new Error('not a number');
}
this.numberValue = value;
}
// date
private dateValue = new Date();
get dateProperty(): Date {
return this.dateValue;
}
set dateProperty(value: Date) {
// https://stackoverflow.com/a/643827/737957
if (Object.prototype.toString.call(value) !== '[object Date]') {
throw new Error('not a date: ' + value + ' type=' + typeof(value));
}
this.dateValue = value;
}
// json
private jsonValue: object = {};
get jsonProperty(): object {
return this.jsonValue;
}
set jsonProperty(value: object) {
if (typeof(value) !== 'object') {
throw new Error('not an object');
}
this.jsonValue = value;
}
// map
private mapValue: { [key: string]: Number } = {};
get mapProperty(): { [key: string]: Number } {
return this.mapValue;
}
set mapProperty(value: { [key: string]: Number }) {
if (typeof(value) !== 'object') {
throw new Error('not a map');
}
this.mapValue = value;
}
// array
private arrayValue: string[] = [];
get arrayProperty(): string[] {
return this.arrayValue;
}
set arrayProperty(value: string[]) {
if (!Array.isArray(value)) {
throw new Error('not an array');
}
this.arrayValue = value;
}
// non-typed (any)
anyProperty: any;
anyArrayProperty: any[] = [];
anyMapProperty: { [key: string]: any } = {};
// non-typed (unknown)
unknownProperty: unknown;
unknownArrayProperty: unknown[] = [];
unknownMapProperty: { [key: string]: unknown } = {};
// unions
unionProperty: string | number | Number | Multiply = 'foo';
unionArrayProperty: (Value | number)[] = [];
unionMapProperty: { [key: string]: (Number | number | string) } = {};
// enum
public optionalEnumValue?: StringEnum;
private enumValue: AllTypesEnum = AllTypesEnum.THIS_IS_GREAT;
get enumProperty() {
return this.enumValue;
}
set enumProperty(value: AllTypesEnum) {
this.enumValue = value;
switch (value) {
case AllTypesEnum.MY_ENUM_VALUE:
case AllTypesEnum.YOUR_ENUM_VALUE:
case AllTypesEnum.THIS_IS_GREAT:
return;
default:
throw new Error('Invalid enum: ' + value);
}
}
get enumPropertyValue(): number {
return this.enumValue.valueOf();
}
enumMethod(value: StringEnum) {
return value;
}
public anyOut(): any {
const ret = new Number(42);
Object.defineProperty(ret, 'tag', {
value: "you're it"
});
return ret;
}
public anyIn(inp: any) {
if (inp.tag !== "you're it") {
throw new Error(`Not the same object that I gave you, got: ${JSON.stringify(inp)}`);
}
}
}
//
// Return an object literal from JavaScript which conforms to a class (effectively treating
// the class as an interface). We want the native code to be able to wrap the resulting object
// in a native class.
//
export class JSObjectLiteralToNative {
returnLiteral(): JSObjectLiteralToNativeClass {
return {
propA: 'Hello',
propB: 102
};
}
}
export class JSObjectLiteralToNativeClass {
propA: string = 'A';
propB: number = 0;
}
/**
* Verify that object references can be passed inside collections.
*/
export class ObjectRefsInCollections {
/**
* Returns the sum of all values
*/
sumFromArray(values: Value[]) {
let sum = 0;
for (let val of values) {
sum += val.value;
}
return sum;
}
/**
* Returns the sum of all values in a map
*/
sumFromMap(values: { [key: string]: Value }) {
let sum = 0;
for (let key of Object.keys(values)) {
sum += values[key].value;
}
return sum;
}
}
export class RuntimeTypeChecking {
/**
* Used to verify verification of number of method arguments.
*/
public methodWithOptionalArguments(arg1: number, arg2: string, arg3?: Date) {
arg1;
arg2;
arg3;
}
public methodWithDefaultedArguments(arg1: number = 2, arg2?: string, arg3: Date = new Date()) {
arg1;
arg2;
arg3;
}
public methodWithOptionalAnyArgument(arg?: any) {
arg;
}
}
export class OptionalConstructorArgument {
public constructor(public readonly arg1: number,
public readonly arg2: string,
public readonly arg3?: Date) {
}
}
export class DefaultedConstructorArgument {
public constructor(public readonly arg1: number = 2,
public readonly arg2?: string,
public readonly arg3: Date = new Date()) {
}
}
export namespace DerivedClassHasNoProperties {
export class Base {
prop: string = '';
}
export class Derived extends Base {
}
}
export class AsyncVirtualMethods {
async callMe() {
return await this.overrideMe(10) + this.dontOverrideMe() + await this.overrideMeToo();
}
async overrideMe(mult: number) {
return 12 * mult;
}
async overrideMeToo() {
return 0;
}
/**
* Just calls "overrideMeToo"
*/
callMe2() {
return this.overrideMeToo();
}
/**
* This method calls the "callMe" async method indirectly, which will then
* invoke a virtual method. This is a "double promise" situation, which
* means that callbacks are not going to be available immediate, but only
* after an "immediates" cycle.
*/
async callMeDoublePromise() {
return new Promise<number>(ok => {
setImmediate(() => {
this.callMe().then(ok);
});
});
}
dontOverrideMe() {
return 8;
}
}
export class SyncVirtualMethods {
callerIsMethod() {
return this.virtualMethod(10);
}
get callerIsProperty() {
return this.virtualMethod(10);
}
set callerIsProperty(x: number) {
this.virtualMethod(x);
}
async callerIsAsync() {
return this.virtualMethod(10);
}
virtualMethod(n: number): number {
return n * 2;
}
// read-write property
theProperty: string = 'initial value';
modifyValueOfTheProperty(value: string) {
this.theProperty = value;
}
retrieveValueOfTheProperty() {
return this.theProperty;
}
// read-only property
readonly readonlyProperty: string = 'readonly-property-initial-value';
retrieveReadOnlyProperty() {
return this.readonlyProperty;
}
// property backed by functions
get otherProperty() {
return 'other property';
}
set otherProperty(value: string) {
this.valueOfOtherProperty = value;
}
valueOfOtherProperty: string = '';
public modifyOtherProperty(value: string) {
this.otherProperty = value;
}
public retrieveOtherProperty() {
return this.otherProperty;
}
// property with a short name (makes sure for example that java's
// convertion of getA to "a" is not assuming that the length is > 1).
a: number = 0;
readA() {
return this.a;
}
writeA(value: number) {
this.a = value;
}
}
export class VirtualMethodPlayground {
async serialSumAsync(count: number) {
let sum = 0;
for (let i = 0; i < count; ++i) {
const result = await this.overrideMeAsync(i);
sum += result;
}
return sum;
}
async parallelSumAsync(count: number) {
let all = new Array<Promise<number>>();
for (let i = 0; i < count; ++i) {
all.push(this.overrideMeAsync(i));
}
const result = await Promise.all(all);
return result.reduce((x, i) => x + i, 0);
}
sumSync(count: number) {
let sum = 0;
for (let i = 0; i < count; ++i) {
sum += this.overrideMeSync(i);
}
return sum;
}
async overrideMeAsync(index: number) {
return 10 * index;
}
overrideMeSync(index: number) {
return 10 * index;
}
}
export class DoubleTrouble implements IFriendlyRandomGenerator {
next() {
return 12;
}
hello() {
return 'world';
}
}
export class Polymorphism {
sayHello(friendly: IFriendly) {
return `oh, ${friendly.hello()}`;
}
}
/**
* This allows us to test that a reference can be stored for objects that
* implement interfaces.
*/
export class NumberGenerator {
constructor(public generator: IRandomNumberGenerator) {
}
nextTimes100() {
return this.generator.next() * 100;
}
isSameGenerator(gen: IRandomNumberGenerator) {
return this.generator === gen;
}
}
export class JSObjectLiteralForInterface {
giveMeFriendly(): IFriendly {
return {
hello: () => 'I am literally friendly!'
};
}
giveMeFriendlyGenerator(): IFriendlyRandomGenerator {
return {
hello: () => 'giveMeFriendlyGenerator',
next: () => 42
};
}
}
export class GreetingAugmenter {
betterGreeting(friendly: IFriendly): string {
return friendly.hello() + ' Let me buy you a drink!';
}
}
/**
* A struct which derives from another struct.
*/
export interface DerivedStruct extends MyFirstStruct {
/**
* An example of a non primitive property.
*/
readonly nonPrimitive: DoubleTrouble
readonly bool: boolean
readonly anotherRequired: Date
readonly optionalArray?: string[]
readonly optionalAny?: any
/**
* This is optional.
*/
readonly anotherOptional?: { [key: string]: Value }
}
export class GiveMeStructs {
/**
* Returns the "anumber" from a MyFirstStruct struct;
*/
readFirstNumber(first: MyFirstStruct) {
return first.anumber;
}
/**
* Returns the boolean from a DerivedStruct struct.
*/
readDerivedNonPrimitive(derived: DerivedStruct) {
return derived.nonPrimitive;
}
/**
* Accepts a struct of type DerivedStruct and returns a struct of type FirstStruct.
*/
derivedToFirst(derived: DerivedStruct) {
return derived as MyFirstStruct;
}
get structLiteral(): StructWithOnlyOptionals {
return {
optional1: 'optional1FromStructLiteral',
optional3: false
};
}
}
export interface IInterfaceWithProperties {
readonly readOnlyString: string;
readWriteString: string;
}
export interface IInterfaceWithPropertiesExtension extends IInterfaceWithProperties {
foo: number;
}
export class UsesInterfaceWithProperties {
constructor(public readonly obj: IInterfaceWithProperties) {
}
public justRead() {
return this.obj.readOnlyString;
}
public writeAndRead(value: string) {
this.obj.readWriteString = value;
return this.obj.readWriteString;
}
public readStringAndNumber(ext: IInterfaceWithPropertiesExtension) {
return `base=${ext.readOnlyString} child=${ext.foo} keys=[${Object.keys(ext).join(',')}]`;
}
}
export class AllowedMethodNames {
/**
* getXxx() is not allowed (see negatives), but getXxx(a, ...) is okay.
*/
public getFoo(withParam: string) {
return withParam;
}
public getBar(_p1: string, _p2: number) {
return;
}
/**
* setFoo(x) is not allowed (see negatives), but setXxx(a, b, ...) is okay.
*/
public setFoo(_x: string, _y: number) {
return;
}
public setBar(_x: string, _y: number, _z: boolean) {
return;
}
}
export interface IReturnsNumber {
obtainNumber(): IDoublable;
readonly numberProp: Number;
}
export class OverrideReturnsObject {
public test(obj: IReturnsNumber) {
return obj.obtainNumber().doubleValue + obj.numberProp.doubleValue;
}
}
export class Thrower {
public throwError() {
this.doThrowError();
}
private doThrowError() {
throw new Error();
}
}
export class VariadicMethod {
private readonly prefix: number[];
/**
* @param prefix a prefix that will be use for all values returned by `#asArray`.
*/
constructor(...prefix: number[]) {
this.prefix = prefix;
}
/**
* @param first the first element of the array to be returned (after the `prefix` provided at construction time).
* @param others other elements to be included in the array.
*/
public asArray(first: number, ...others: number[]): number[] {
return [...this.prefix, first, ...others];
}
}
export class VariadicInvoker {
public constructor(private readonly method: VariadicMethod) { }
public asArray(...values: number[]): number[] {
const [first, ...rest] = values;
return this.method.asArray(first, ...rest);
}
}
export class Statics {
constructor(public readonly value: string) {
}
/**
* Jsdocs for static method
* @param name The name of the person to say hello to
*/
public static staticMethod(name: string) {
return `hello ,${name}!`;
}
public justMethod() {
return this.value;
}
/**
* Jsdocs for static property.
*/
public static readonly Foo = 'hello';
/**
* Constants may also use all-caps.
*/
public static readonly BAR = 1234;
/**
* Constants can also use camelCase.
*/
public static readonly zooBar: { [name: string]: string } = { hello: 'world' };
private static _instance?: Statics;
/**
* Jsdocs for static getter.
*/
public static get instance(): Statics {
if (!this._instance) {
this._instance = new Statics('default');
}
return this._instance;
}
/**
*Jsdocs for static setter.
*/
public static set instance(val: Statics) {
this._instance = val;
}
public static nonConstStatic = 100; // this should not be represented as a constant in target languages
public static readonly ConstObj = new DoubleTrouble(); // should be initialized statically
}
// https://en.wikipedia.org/wiki/List_of_Java_keywords
export class JavaReservedWords {
public abstract() {
}
public assert() {
}
public boolean() {
}
public break() {
}
public byte() {
}
public case() {
}
public catch() {
}
public char() {
}
public class() {
}
public const() {
}
public continue() {
}
public default() {
}
public double() {
}
public do() {
}
public else() {
}
public enum() {
}
public extends() {
}
public false() {
}
public final() {
}
public finally() {
}
public float() {
}
public for() {
}
public goto() {
}
public if() {
}
public implements() {
}
public import() {
}
public instanceof() {
}
public int() {
}
public interface() {
}
public long() {
}
public native() {
}
public new() {
}
public null() {
}
public package() {
}
public private() {
}
public protected() {
}
public public() {
}
public return() {
}
public short() {
}
public static() {
}
public strictfp() {
}
public super() {
}
public switch() {
}
public synchronized() {
}
public this() {
}
public throw() {
}
public throws() {
}
public transient() {
}
public true() {
}
public try() {
}
public void() {
}
public volatile() {
}
public while = 'hello';
}
export class PythonReservedWords {
public and() {}
public as() {}
public assert() {}
public async() {}
public await() {}
public break() {}
public class() {}
public continue() {}
public def() {}
public del() {}
public elif() {}
public else() {}
public except() {}
public finally() {}
public for() {}
public from() {}
public global() {}
public if() {}
public import() {}
public in() {}
public is() {}
public lambda() {}
public nonlocal() {}
public not() {}
public or() {}
public pass() {}
public raise() {}
public return() {}
public try() {}
public while() {}
public with() {}
public yield() {}
}
export interface UnionProperties {
readonly foo?: string | number;
readonly bar: AllTypes | string | number;
}
export class UseBundledDependency {
value() {
return bundled;
}
}
/**
* Test fixture to verify that jsii modules can use the node standard library.
*/
export class NodeStandardLibrary {
/**
* Reads a local resource file (resource.txt) asynchronously.
* @returns "Hello, resource!"
*/
public async fsReadFile() {
const value = await readFile(path.join(__dirname, 'resource.txt'));
return value.toString();
}
/**
* Sync version of fsReadFile.
* @returns "Hello, resource! SYNC!"
*/
public fsReadFileSync() {
return fs.readFileSync(path.join(__dirname, 'resource.txt')).toString() + ' SYNC!';
}
/**
* Returns the current os.platform() from the "os" node module.
*/
public get osPlatform() {
return os.platform();
}