forked from aws/jsii
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel.ts
More file actions
1532 lines (1346 loc) · 45.1 KB
/
Copy pathkernel.ts
File metadata and controls
1532 lines (1346 loc) · 45.1 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 * as spec from '@jsii/spec';
import * as cp from 'child_process';
import * as fs from 'fs-extra';
import { createRequire } from 'module';
import * as os from 'os';
import * as path from 'path';
import * as api from './api';
import { TOKEN_REF } from './api';
import { jsiiTypeFqn, ObjectTable, tagJsiiConstructor } from './objects';
import * as onExit from './on-exit';
import * as wire from './serialization';
import * as tar from './tar-cache';
export const ASSEMBLY_SUPPORTED_FEATURES: spec.JsiiFeature[] = [
'intersection-types',
'class-covariant-overrides',
];
export const enum JsiiErrorType {
JSII_FAULT = '@jsii/kernel.Fault',
RUNTIME_ERROR = '@jsii/kernel.RuntimeError',
}
export interface JsiiError extends Error {
readonly name: JsiiErrorType;
}
export class JsiiFault extends Error implements JsiiError {
public readonly name = JsiiErrorType.JSII_FAULT;
public constructor(message: string) {
super(message);
}
}
export class RuntimeError extends Error implements JsiiError {
public readonly name = JsiiErrorType.RUNTIME_ERROR;
public constructor(message: string) {
super(message);
}
}
export class Kernel {
/**
* Set to true for verbose debugging.
*/
public traceEnabled = false;
/**
* Set to true for timing data to be emitted.
*/
public debugTimingEnabled = false;
/**
* Set to true to validate assemblies upon loading (slow).
*/
public validateAssemblies = false;
readonly #assemblies = new Map<string, Assembly>();
readonly #objects = new ObjectTable(this.#typeInfoForFqn.bind(this));
readonly #cbs = new Map<string, Callback>();
readonly #waiting = new Map<string, Callback>();
readonly #promises = new Map<string, AsyncInvocation>();
// Lazy caches for O(1) method/property lookup by name (replaces linear search)
readonly #methodMapCache = new Map<string, Map<string, spec.Method>>();
readonly #propertyMapCache = new Map<string, Map<string, spec.Property>>();
// Cache for O(1) FQN-to-Type lookups (assemblies are immutable after load)
readonly #typeCache = new Map<string, spec.Type>();
readonly #serializerHost: wire.SerializerHost;
#nextid = 20000; // incrementing counter for objid, cbid, promiseid
#syncInProgress?: string; // forbids async calls (begin) while processing sync calls (get/set/invoke)
#installDir?: string;
/** The internal require function, used instead of the global "require" so that webpack does not transform it... */
#require?: typeof require;
/**
* Creates a jsii kernel object.
*
* @param callbackHandler This handler is invoked when a synchronous callback is called.
* It's responsibility is to execute the callback and return it's
* result (or throw an error).
*/
public constructor(public callbackHandler: (callback: api.Callback) => any) {
this.#serializerHost = {
objects: this.#objects,
debug: this.#debug.bind(this),
isVisibleType: this.#isVisibleType.bind(this),
findSymbol: this.#findSymbol.bind(this),
lookupType: this.#typeInfoForFqn.bind(this),
};
}
public load(req: api.LoadRequest): api.LoadResponse {
return this.#debugTime(
() => this.#load(req),
`load(${JSON.stringify(req, null, 2)})`,
);
}
#load(req: api.LoadRequest): api.LoadResponse {
this.#debug('load', req);
if ('assembly' in req) {
throw new JsiiFault(
'`assembly` field is deprecated for "load", use `name`, `version` and `tarball` instead',
);
}
const pkgname = req.name;
const pkgver = req.version;
// check if we already have such a module
const packageDir = this.#getPackageDir(pkgname);
if (fs.pathExistsSync(packageDir)) {
// module exists, verify version
const epkg = fs.readJsonSync(path.join(packageDir, 'package.json'));
if (epkg.version !== pkgver) {
throw new JsiiFault(
`Multiple versions ${pkgver} and ${epkg.version} of the ` +
`package '${pkgname}' cannot be loaded together since this is unsupported by ` +
'some runtime environments',
);
}
// same version, no-op
this.#debug('look up already-loaded assembly', pkgname);
const assm = this.#assemblies.get(pkgname)!;
return {
assembly: assm.metadata.name,
types: Object.keys(assm.metadata.types ?? {}).length,
};
}
// Force umask to have npm-install-like permissions
const originalUmask = process.umask(0o022);
try {
// untar the archive to its final location
const { cache } = this.#debugTime(
() =>
tar.extract(
req.tarball,
packageDir,
{
strict: true,
strip: 1, // Removes the 'package/' path element from entries
unlink: true,
},
req.name,
req.version,
),
`tar.extract(${req.tarball}) => ${packageDir}`,
);
if (cache != null) {
this.#debug(
`Package cache enabled, extraction resulted in a cache ${cache}`,
);
}
} finally {
// Reset umask to the initial value
process.umask(originalUmask);
}
// read .jsii metadata from the root of the package
let assmSpec: spec.Assembly;
try {
assmSpec = this.#debugTime(
() =>
spec.loadAssemblyFromPath(
packageDir,
this.validateAssemblies,
ASSEMBLY_SUPPORTED_FEATURES,
),
`loadAssemblyFromPath(${packageDir})`,
);
} catch (e: any) {
throw new JsiiFault(
`Error for package tarball ${req.tarball}: ${e.message}`,
);
}
// We do a `require.resolve` call, as otherwise, requiring with a directory will cause any `exports` from
// `package.json` to be ignored, preventing injection of a "lazy index" entry point.
const entryPoint = this.#require!.resolve(assmSpec.name, {
paths: [this.#installDir!],
});
// load the module and capture its closure
const closure = this.#debugTime(
() => this.#require!(entryPoint),
`require(${entryPoint})`,
);
const assm = new Assembly(assmSpec, closure);
this.#debugTime(
() => this.#addAssembly(assm),
`registerAssembly({ name: ${assm.metadata.name}, types: ${
Object.keys(assm.metadata.types ?? {}).length
} })`,
);
return {
assembly: assmSpec.name,
types: Object.keys(assmSpec.types ?? {}).length,
};
}
public getBinScriptCommand(
req: api.GetScriptCommandRequest,
): api.GetScriptCommandResponse {
return this.#getBinScriptCommand(req);
}
public invokeBinScript(
req: api.InvokeScriptRequest,
): api.InvokeScriptResponse {
const { command, args, env } = this.#getBinScriptCommand(req);
const result = cp.spawnSync(command, args, {
encoding: 'utf-8',
env,
shell: true,
});
return {
stdout: result.stdout,
stderr: result.stderr,
status: result.status,
signal: result.signal,
};
}
public create(req: api.CreateRequest): api.CreateResponse {
return this.#create(req);
}
public del(req: api.DelRequest): api.DelResponse {
const { objref } = req;
this.#debug('del', objref);
this.#objects.deleteObject(objref);
return {};
}
public sget(req: api.StaticGetRequest): api.GetResponse {
const { fqn, property } = req;
const symbol = `${fqn}.${property}`;
this.#debug('sget', symbol);
const ti = this.#typeInfoForProperty(property, fqn);
if (!ti.static) {
throw new JsiiFault(`property ${symbol} is not static`);
}
const prototype = this.#findSymbol(fqn);
const value = this.#ensureSync(
`property ${property}`,
() => prototype[property],
);
this.#debug('value:', value);
const ret = this.#fromSandbox(value, ti, `of static property ${symbol}`);
this.#debug('ret', ret);
return { value: ret };
}
public sset(req: api.StaticSetRequest): api.SetResponse {
const { fqn, property, value } = req;
const symbol = `${fqn}.${property}`;
this.#debug('sset', symbol);
const ti = this.#typeInfoForProperty(property, fqn);
if (!ti.static) {
throw new JsiiFault(`property ${symbol} is not static`);
}
if (ti.immutable) {
throw new JsiiFault(`static property ${symbol} is readonly`);
}
const prototype = this.#findSymbol(fqn);
this.#ensureSync(
`property ${property}`,
() =>
(prototype[property] = this.#toSandbox(
value,
ti,
`assigned to static property ${symbol}`,
)),
);
return {};
}
public get(req: api.GetRequest): api.GetResponse {
const { objref, property } = req;
this.#debug('get', objref, property);
const { instance, fqn, interfaces } = this.#objects.findObject(objref);
const ti = this.#typeInfoForProperty(property, fqn, interfaces);
// if the property is overridden by the native code and "get" is called on the object, it
// means that the native code is trying to access the "super" property. in order to enable
// that, we actually keep a copy of the original property descriptor when we override,
// so `findPropertyTarget` will return either the original property name ("property") or
// the "super" property name (somehing like "$jsii$super$<property>$").
const propertyToGet = this.#findPropertyTarget(instance, property);
// make the actual "get", and block any async calls that might be performed
// by jsii overrides.
const value = this.#ensureSync(
`property '${objref[TOKEN_REF]}.${propertyToGet}'`,
() => instance[propertyToGet],
);
this.#debug('value:', value);
const ret = this.#fromSandbox(value, ti, `of property ${fqn}.${property}`);
this.#debug('ret:', ret);
return { value: ret };
}
public set(req: api.SetRequest): api.SetResponse {
const { objref, property, value } = req;
this.#debug('set', objref, property, value);
const { instance, fqn, interfaces } = this.#objects.findObject(objref);
const propInfo = this.#typeInfoForProperty(req.property, fqn, interfaces);
if (propInfo.immutable) {
throw new JsiiFault(
`Cannot set value of immutable property ${req.property} to ${req.value}`,
);
}
const propertyToSet = this.#findPropertyTarget(instance, property);
this.#ensureSync(
`property '${objref[TOKEN_REF]}.${propertyToSet}'`,
() =>
(instance[propertyToSet] = this.#toSandbox(
value,
propInfo,
`assigned to property ${fqn}.${property}`,
)),
);
return {};
}
public invoke(req: api.InvokeRequest): api.InvokeResponse {
const { objref, method } = req;
const args = req.args ?? [];
this.#debug('invoke', objref, method, args);
const { ti, obj, fn } = this.#findInvokeTarget(objref, method, args);
// verify this is not an async method
if (ti.async) {
throw new JsiiFault(`${method} is an async method, use "begin" instead`);
}
const fqn = jsiiTypeFqn(obj, this.#isVisibleType.bind(this));
const ret = this.#ensureSync(
`method '${objref[TOKEN_REF]}.${method}'`,
() => {
return fn.apply(
obj,
this.#toSandboxValues(
args,
`method ${fqn ? `${fqn}#` : ''}${method}`,
ti.parameters,
),
);
},
);
const result = this.#fromSandbox(
ret,
ti.returns ?? 'void',
`returned by method ${fqn ? `${fqn}#` : ''}${method}`,
);
this.#debug('invoke result', result);
return { result };
}
public sinvoke(req: api.StaticInvokeRequest): api.InvokeResponse {
const { fqn, method } = req;
const args = req.args ?? [];
this.#debug('sinvoke', fqn, method, args);
const ti = this.#typeInfoForMethod(method, fqn);
if (!ti.static) {
throw new JsiiFault(`${fqn}.${method} is not a static method`);
}
// verify this is not an async method
if (ti.async) {
throw new JsiiFault(`${method} is an async method, use "begin" instead`);
}
const prototype = this.#findSymbol(fqn);
const fn = prototype[method] as (...params: any[]) => any;
const ret = this.#ensureSync(`method '${fqn}.${method}'`, () => {
return fn.apply(
prototype,
this.#toSandboxValues(
args,
`static method ${fqn}.${method}`,
ti.parameters,
),
);
});
this.#debug('method returned:', ret);
return {
result: this.#fromSandbox(
ret,
ti.returns ?? 'void',
`returned by static method ${fqn}.${method}`,
),
};
}
public begin(req: api.BeginRequest): api.BeginResponse {
const { objref, method } = req;
const args = req.args ?? [];
this.#debug('begin', objref, method, args);
if (this.#syncInProgress) {
throw new JsiiFault(
`Cannot invoke async method '${req.objref[TOKEN_REF]}.${req.method}' while sync ${this.#syncInProgress} is being processed`,
);
}
const { ti, obj, fn } = this.#findInvokeTarget(objref, method, args);
// verify this is indeed an async method
if (!ti.async) {
throw new JsiiFault(`Method ${method} is expected to be an async method`);
}
const fqn = jsiiTypeFqn(obj, this.#isVisibleType.bind(this));
const promise = fn.apply(
obj,
this.#toSandboxValues(
args,
`async method ${fqn ? `${fqn}#` : ''}${method}`,
ti.parameters,
),
) as Promise<any>;
// since we are planning to resolve this promise in a different scope
// we need to handle rejections here [1]
// [1]: https://stackoverflow.com/questions/40920179/should-i-refrain-from-handling-promise-rejection-asynchronously/40921505
promise.catch((_) => undefined);
const prid = this.#makeprid();
this.#promises.set(prid, {
promise,
method: ti,
});
return { promiseid: prid };
}
public async end(req: api.EndRequest): Promise<api.EndResponse> {
const { promiseid } = req;
this.#debug('end', promiseid);
const storedPromise = this.#promises.get(promiseid);
if (storedPromise == null) {
throw new JsiiFault(`Cannot find promise with ID: ${promiseid}`);
}
const { promise, method } = storedPromise;
let result;
try {
result = await promise;
this.#debug('promise result:', result);
} catch (e: any) {
this.#debug('promise error:', e);
if (e.name === JsiiErrorType.JSII_FAULT) {
if (e instanceof JsiiFault) {
throw e;
}
throw new JsiiFault(e.message);
}
// default to RuntimeError, since non-kernel errors may not
// have their `name` field defined
if (e instanceof RuntimeError) {
throw e;
}
throw new RuntimeError(e);
} finally {
this.#promises.delete(promiseid);
}
return {
result: this.#fromSandbox(
result,
method.returns ?? 'void',
`returned by async method ${method.name}`,
),
};
}
public callbacks(_req?: api.CallbacksRequest): api.CallbacksResponse {
this.#debug('callbacks');
const ret = Array.from(this.#cbs.entries()).map(([cbid, cb]) => {
this.#waiting.set(cbid, cb); // move to waiting
this.#cbs.delete(cbid); // remove from created
const callback: api.Callback = {
cbid,
cookie: cb.override.cookie,
invoke: {
objref: cb.objref,
method: cb.override.method,
args: cb.args,
},
};
return callback;
});
return { callbacks: ret };
}
public complete(req: api.CompleteRequest): api.CompleteResponse {
const { cbid, err, result, name } = req;
this.#debug('complete', cbid, err, result);
const cb = this.#waiting.get(cbid);
if (!cb) {
throw new JsiiFault(`Callback ${cbid} not found`);
}
if (err) {
this.#debug('completed with error:', err);
cb.fail(
name === JsiiErrorType.JSII_FAULT
? new JsiiFault(err)
: new RuntimeError(err),
);
} else {
const sandoxResult = this.#toSandbox(
result,
cb.expectedReturnType ?? 'void',
// eslint-disable-next-line @typescript-eslint/no-base-to-string
`returned by callback ${cb.toString()}`,
);
this.#debug('completed with result:', sandoxResult);
cb.succeed(sandoxResult);
}
this.#waiting.delete(cbid);
return { cbid };
}
/**
* Returns the language-specific names for a jsii module.
* @param assemblyName The name of the jsii module (i.e. jsii$jsii_calculator_lib$)
*/
public naming(req: api.NamingRequest): api.NamingResponse {
const assemblyName = req.assembly;
this.#debug('naming', assemblyName);
const assembly = this.#assemblyFor(assemblyName);
const targets = assembly.metadata.targets;
if (!targets) {
throw new JsiiFault(
`Unexpected - "targets" for ${assemblyName} is missing!`,
);
}
return { naming: targets };
}
public stats(_req?: api.StatsRequest): api.StatsResponse {
return {
objectCount: this.#objects.count,
};
}
#addAssembly(assm: Assembly) {
this.#assemblies.set(assm.metadata.name, assm);
// Invalidate type cache as assembly data may have changed
this.#typeCache.clear();
// We can use jsii runtime type information from jsii 1.19.0 onwards... Note that a version of
// 0.0.0 means we are assessing against a development tree, which is newer...
const jsiiVersion = assm.metadata.jsiiVersion.split(' ', 1)[0];
const [jsiiMajor, jsiiMinor, _jsiiPatch, ..._rest] = jsiiVersion
.split('.')
.map((str) => parseInt(str, 10));
if (
jsiiVersion === '0.0.0' ||
jsiiMajor > 1 ||
(jsiiMajor === 1 && jsiiMinor >= 19)
) {
this.#debug('Using compiler-woven runtime type information!');
return;
}
// add the __jsii__.fqn property on every constructor. this allows
// traversing between the javascript and jsii worlds given any object.
for (const fqn of Object.keys(assm.metadata.types ?? {})) {
const typedef = assm.metadata.types![fqn];
switch (typedef.kind) {
case spec.TypeKind.Interface:
continue; // interfaces don't really exist
case spec.TypeKind.Class:
case spec.TypeKind.Enum:
const constructor = this.#findSymbol(fqn);
tagJsiiConstructor(constructor, fqn);
}
}
}
// find the javascript constructor function for a jsii FQN.
#findCtor(
fqn: string,
args: any[],
): { ctor: any; parameters?: spec.Parameter[] } {
if (fqn === wire.EMPTY_OBJECT_FQN) {
return { ctor: Object };
}
const typeinfo = this.#typeInfoForFqn(fqn);
switch (typeinfo.kind) {
case spec.TypeKind.Class:
const classType = typeinfo;
this.#validateMethodArguments(classType.initializer, args);
return {
ctor: this.#findSymbol(fqn),
parameters: classType.initializer && classType.initializer.parameters,
};
case spec.TypeKind.Interface:
throw new JsiiFault(
`Cannot create an object with an FQN of an interface: ${fqn}`,
);
case spec.TypeKind.Enum:
default:
throw new JsiiFault(`Unexpected FQN kind: ${fqn}`);
}
}
#getPackageDir(pkgname: string): string {
if (!this.#installDir) {
this.#installDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsii-kernel-'));
this.#require = createRequire(this.#installDir);
fs.mkdirpSync(path.join(this.#installDir, 'node_modules'));
this.#debug('creating jsii-kernel modules workdir:', this.#installDir);
onExit.removeSync(this.#installDir);
}
return path.join(this.#installDir, 'node_modules', pkgname);
}
#create(req: api.CreateRequest): api.CreateResponse {
this.#debug('create', req);
const { fqn, interfaces, overrides } = req;
const requestArgs = req.args ?? [];
const ctorResult = this.#findCtor(fqn, requestArgs);
const ctor = ctorResult.ctor;
const obj = new ctor(
...this.#toSandboxValues(
requestArgs,
`new ${fqn}`,
ctorResult.parameters,
),
);
const objref = this.#objects.registerObject(obj, fqn, req.interfaces ?? []);
// overrides: for each one of the override method names, installs a
// method on the newly created object which represents the remote "reverse proxy".
if (overrides) {
this.#debug('overrides', overrides);
const overrideTypeErrorMessage =
'Override can either be "method" or "property"';
const methods = new Set<string>();
const properties = new Set<string>();
for (const override of overrides) {
if (api.isMethodOverride(override)) {
if (api.isPropertyOverride(override)) {
throw new JsiiFault(overrideTypeErrorMessage);
}
if (methods.has(override.method)) {
throw new JsiiFault(
`Duplicate override for method '${override.method}'`,
);
}
methods.add(override.method);
this.#applyMethodOverride(obj, objref, fqn, interfaces, override);
} else if (api.isPropertyOverride(override)) {
if (api.isMethodOverride(override)) {
throw new JsiiFault(overrideTypeErrorMessage);
}
if (properties.has(override.property)) {
throw new JsiiFault(
`Duplicate override for property '${override.property}'`,
);
}
properties.add(override.property);
this.#applyPropertyOverride(obj, objref, fqn, interfaces, override);
} else {
throw new JsiiFault(overrideTypeErrorMessage);
}
}
}
return objref;
}
#getSuperPropertyName(name: string) {
return `$jsii$super$${name}$`;
}
#applyPropertyOverride(
obj: any,
objref: api.ObjRef,
typeFqn: string,
interfaces: string[] | undefined,
override: api.PropertyOverride,
) {
// error if we can find a method with this name
if (this.#tryTypeInfoForMethod(override.property, typeFqn, interfaces)) {
throw new JsiiFault(
`Trying to override method '${override.property}' as a property`,
);
}
let propInfo = this.#tryTypeInfoForProperty(
override.property,
typeFqn,
interfaces,
);
// if this is a private property (i.e. doesn't have `propInfo` the object has a key)
if (!propInfo && override.property in obj) {
this.#debug(`Skipping override of private property ${override.property}`);
return;
}
// We've overriding a property on an object we have NO type information on (probably
// because it's an anonymous object).
// Pretend it's 'prop: any';
//
// FIXME: We could do better type checking during the conversion if JSII clients
// would tell us the intended interface type.
propInfo ??= {
name: override.property,
type: spec.CANONICAL_ANY,
};
this.#defineOverridenProperty(obj, objref, override, propInfo);
}
#defineOverridenProperty(
obj: any,
objref: api.ObjRef,
override: api.PropertyOverride,
propInfo: spec.Property,
) {
const propertyName = override.property;
this.#debug('apply override', propertyName);
// save the old property under $jsii$super$<prop>$ so that property overrides
// can still access it via `super.<prop>`.
const prev = getPropertyDescriptor(obj, propertyName) ?? {
value: obj[propertyName],
writable: true,
enumerable: true,
configurable: true,
};
const prevEnumerable = prev.enumerable;
prev.enumerable = false;
Object.defineProperty(obj, this.#getSuperPropertyName(propertyName), prev);
// we add callbacks for both 'get' and 'set', even if the property
// is readonly. this is fine because if you try to set() a readonly
// property, it will fail.
Object.defineProperty(obj, propertyName, {
enumerable: prevEnumerable,
configurable: prev.configurable,
get: () => {
this.#debug('virtual get', objref, propertyName, {
cookie: override.cookie,
});
const result = this.callbackHandler({
cookie: override.cookie,
cbid: this.#makecbid(),
get: { objref, property: propertyName },
});
this.#debug('callback returned', result);
return this.#toSandbox(
result,
propInfo,
`returned by callback property ${propertyName}`,
);
},
set: (value: any) => {
this.#debug('virtual set', objref, propertyName, {
cookie: override.cookie,
});
this.callbackHandler({
cookie: override.cookie,
cbid: this.#makecbid(),
set: {
objref,
property: propertyName,
value: this.#fromSandbox(
value,
propInfo,
`assigned to callback property ${propertyName}`,
),
},
});
},
});
function getPropertyDescriptor(
obj: any,
propertyName: string,
): PropertyDescriptor | undefined {
const direct = Object.getOwnPropertyDescriptor(obj, propertyName);
if (direct != null) {
return direct;
}
const proto = Object.getPrototypeOf(obj);
if (proto == null && proto !== Object.prototype) {
// We reached Object or the prototype chain root, all hope is lost!
return undefined;
}
return getPropertyDescriptor(proto, propertyName);
}
}
#applyMethodOverride(
obj: any,
objref: api.ObjRef,
typeFqn: string,
interfaces: string[] | undefined,
override: api.MethodOverride,
) {
// error if we can find a property with this name
if (this.#tryTypeInfoForProperty(override.method, typeFqn, interfaces)) {
throw new JsiiFault(
`Trying to override property '${override.method}' as a method`,
);
}
let methodInfo = this.#tryTypeInfoForMethod(
override.method,
typeFqn,
interfaces,
);
// If this is a private method (doesn't have methodInfo, key resolves on the object), we
// are going to skip the override.
if (!methodInfo && obj[override.method]) {
this.#debug(`Skipping override of private method ${override.method}`);
return;
}
// We've overriding a method on an object we have NO type information on (probably
// because it's an anonymous object).
// Pretend it's an (...args: any[]) => any
methodInfo ??= {
name: override.method,
returns: { type: spec.CANONICAL_ANY },
parameters: [
{
name: 'args',
type: spec.CANONICAL_ANY,
variadic: true,
},
],
variadic: true,
};
this.#defineOverridenMethod(obj, objref, override, methodInfo);
}
#defineOverridenMethod(
obj: any,
objref: api.ObjRef,
override: api.MethodOverride,
methodInfo: spec.Method,
) {
const methodName = override.method;
const fqn = jsiiTypeFqn(obj, this.#isVisibleType.bind(this));
const methodContext = `${methodInfo.async ? 'async ' : ''}method${
fqn ? `${fqn}#` : methodName
}`;
if (methodInfo.async) {
// async method override
Object.defineProperty(obj, methodName, {
enumerable: false,
configurable: false,
writable: false,
value: (...methodArgs: any[]) => {
this.#debug('invoke async method override', override);
const args = this.#toSandboxValues(
methodArgs,
methodContext,
methodInfo.parameters,
);
return new Promise<any>((succeed, fail) => {
const cbid = this.#makecbid();
this.#debug('adding callback to queue', cbid);
this.#cbs.set(cbid, {
objref,
override,
args,
expectedReturnType: methodInfo.returns ?? 'void',
succeed,
fail,
});
});
},
});
} else {
// sync method override (method info is not required)
Object.defineProperty(obj, methodName, {
enumerable: false,
configurable: false,
writable: false,
value: (...methodArgs: any[]) => {
this.#debug(
'invoke sync method override',
override,
'args',
methodArgs,
);
// We should be validating the actual arguments according to the
// declared parameters here, but let's just assume the JSII runtime on the
// other end has done its work.
const result = this.callbackHandler({
cookie: override.cookie,
cbid: this.#makecbid(),
invoke: {
objref,
method: methodName,
args: this.#fromSandboxValues(
methodArgs,
methodContext,
methodInfo.parameters,
),
},
});
this.#debug('Result', result);
return this.#toSandbox(
result,
methodInfo.returns ?? 'void',
`returned by callback method ${methodName}`,
);
},
});
}
}
#findInvokeTarget(objref: api.ObjRef, methodName: string, args: any[]) {
const { instance, fqn, interfaces } = this.#objects.findObject(objref);
const ti = this.#typeInfoForMethod(methodName, fqn, interfaces);
this.#validateMethodArguments(ti, args);
// always first look up the method in the prototype. this practically bypasses
// any methods overridden by derived classes (which are by definition native
// methods). this serves to allow native call to invoke "super.method()" when
// overriding the method.
// if we didn't find the method on the prototype, it could be a literal object
// that implements an interface, so we look if we have the method on the object
// itself. if we do, we invoke it.
//
//--------------------------------------------------------------
//