-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtensionCommon.jsm
2331 lines (2032 loc) · 66.6 KB
/
ExtensionCommon.jsm
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
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
/**
* This module contains utilities and base classes for logic which is
* common between the parent and child process, and in particular
* between ExtensionParent.jsm and ExtensionChild.jsm.
*/
/* exported ExtensionCommon */
this.EXPORTED_SYMBOLS = ["ExtensionCommon", "SchemaAPIManager"];
ChromeUtils.import("resource://gre/modules/Services.jsm");
ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
XPCOMUtils.defineLazyModuleGetters(this, {
AppConstants: "resource://gre/modules/AppConstants.jsm",
ConsoleAPI: "resource://gre/modules/Console.jsm",
MessageChannel: "resource://gre/modules/MessageChannel.jsm",
PrivateBrowsingUtils: "resource://gre/modules/PrivateBrowsingUtils.jsm",
Schemas: "resource://gre/modules/Schemas.jsm",
SchemaRoot: "resource://gre/modules/Schemas.jsm",
});
XPCOMUtils.defineLazyServiceGetter(this, "styleSheetService",
"@mozilla.org/content/style-sheet-service;1",
"nsIStyleSheetService");
ChromeUtils.import("resource://gre/modules/ExtensionUtils.jsm");
var {
DefaultMap,
DefaultWeakMap,
ExtensionError,
filterStack,
getInnerWindowID,
getUniqueId,
getWinUtils,
} = ExtensionUtils;
function getConsole() {
return new ConsoleAPI({
maxLogLevelPref: "extensions.webextensions.log.level",
prefix: "WebExtensions",
});
}
XPCOMUtils.defineLazyGetter(this, "console", getConsole);
XPCOMUtils.defineLazyPreferenceGetter(this, "DELAYED_BG_STARTUP",
"extensions.webextensions.background-delayed-startup");
// Run a function and report exceptions.
function runSafeSyncWithoutClone(f, ...args) {
try {
return f(...args);
} catch (e) {
dump(`Extension error: ${e} ${e.fileName} ${e.lineNumber}\n[[Exception stack\n${filterStack(e)}Current stack\n${filterStack(Error())}]]\n`);
Cu.reportError(e);
}
}
// Return true if the given value is an instance of the given
// native type.
function instanceOf(value, type) {
return (value && typeof value === "object" &&
ChromeUtils.getClassName(value) === type);
}
/**
* Convert any of several different representations of a date/time to a Date object.
* Accepts several formats:
* a Date object, an ISO8601 string, or a number of milliseconds since the epoch as
* either a number or a string.
*
* @param {Date|string|number} date
* The date to convert.
* @returns {Date}
* A Date object
*/
function normalizeTime(date) {
// Of all the formats we accept the "number of milliseconds since the epoch as a string"
// is an outlier, everything else can just be passed directly to the Date constructor.
return new Date((typeof date == "string" && /^\d+$/.test(date))
? parseInt(date, 10) : date);
}
function withHandlingUserInput(window, callable) {
let handle = getWinUtils(window).setHandlingUserInput(true);
try {
return callable();
} finally {
handle.destruct();
}
}
/**
* Defines a lazy getter for the given property on the given object. The
* first time the property is accessed, the return value of the getter
* is defined on the current `this` object with the given property name.
* Importantly, this means that a lazy getter defined on an object
* prototype will be invoked separately for each object instance that
* it's accessed on.
*
* @param {object} object
* The prototype object on which to define the getter.
* @param {string|symbol} prop
* The property name for which to define the getter.
* @param {function} getter
* The function to call in order to generate the final property
* value.
*/
function defineLazyGetter(object, prop, getter) {
let redefine = (obj, value) => {
Object.defineProperty(obj, prop, {
enumerable: true,
configurable: true,
writable: true,
value,
});
return value;
};
Object.defineProperty(object, prop, {
enumerable: true,
configurable: true,
get() {
return redefine(this, getter.call(this));
},
set(value) {
redefine(this, value);
},
});
}
function checkLoadURL(url, principal, options) {
let ssm = Services.scriptSecurityManager;
let flags = ssm.STANDARD;
if (!options.allowScript) {
flags |= ssm.DISALLOW_SCRIPT;
}
if (!options.allowInheritsPrincipal) {
flags |= ssm.DISALLOW_INHERIT_PRINCIPAL;
}
if (options.dontReportErrors) {
flags |= ssm.DONT_REPORT_ERRORS;
}
try {
ssm.checkLoadURIWithPrincipal(principal,
Services.io.newURI(url),
flags);
} catch (e) {
return false;
}
return true;
}
function makeWidgetId(id) {
id = id.toLowerCase();
// FIXME: This allows for collisions.
return id.replace(/[^a-z0-9_-]/g, "_");
}
/**
* A sentinel class to indicate that an array of values should be
* treated as an array when used as a promise resolution value, but as a
* spread expression (...args) when passed to a callback.
*/
class SpreadArgs extends Array {
constructor(args) {
super();
this.push(...args);
}
}
/**
* Like SpreadArgs, but also indicates that the array values already
* belong to the target compartment, and should not be cloned before
* being passed.
*
* The `unwrappedValues` property contains an Array object which belongs
* to the target compartment, and contains the same unwrapped values
* passed the NoCloneSpreadArgs constructor.
*/
class NoCloneSpreadArgs {
constructor(args) {
this.unwrappedValues = args;
}
[Symbol.iterator]() {
return this.unwrappedValues[Symbol.iterator]();
}
}
const LISTENERS = Symbol("listeners");
const ONCE_MAP = Symbol("onceMap");
class EventEmitter {
constructor() {
this[LISTENERS] = new Map();
this[ONCE_MAP] = new WeakMap();
}
/**
* Adds the given function as a listener for the given event.
*
* The listener function may optionally return a Promise which
* resolves when it has completed all operations which event
* dispatchers may need to block on.
*
* @param {string} event
* The name of the event to listen for.
* @param {function(string, ...any)} listener
* The listener to call when events are emitted.
*/
on(event, listener) {
let listeners = this[LISTENERS].get(event);
if (!listeners) {
listeners = new Set();
this[LISTENERS].set(event, listeners);
}
listeners.add(listener);
}
/**
* Removes the given function as a listener for the given event.
*
* @param {string} event
* The name of the event to stop listening for.
* @param {function(string, ...any)} listener
* The listener function to remove.
*/
off(event, listener) {
let set = this[LISTENERS].get(event);
if (set) {
set.delete(listener);
set.delete(this[ONCE_MAP].get(listener));
if (!set.size) {
this[LISTENERS].delete(event);
}
}
}
/**
* Adds the given function as a listener for the given event once.
*
* @param {string} event
* The name of the event to listen for.
* @param {function(string, ...any)} listener
* The listener to call when events are emitted.
*/
once(event, listener) {
let wrapper = (...args) => {
this.off(event, wrapper);
this[ONCE_MAP].delete(listener);
// @ts-ignore
return listener(...args);
};
this[ONCE_MAP].set(listener, wrapper);
this.on(event, wrapper);
}
/**
* Triggers all listeners for the given event. If any listeners return
* a value, returns a promise which resolves when all returned
* promises have resolved. Otherwise, returns undefined.
*
* @param {string} event
* The name of the event to emit.
* @param {...any} args
* Arbitrary arguments to pass to the listener functions, after
* the event name.
* @returns {Promise?}
*/
emit(event, ...args) {
let listeners = this[LISTENERS].get(event);
if (listeners) {
let promises = [];
for (let listener of listeners) {
try {
let result = listener(event, ...args);
if (result !== undefined) {
promises.push(result);
}
} catch (e) {
Cu.reportError(e);
}
}
if (promises.length) {
return Promise.all(promises);
}
}
}
}
/**
* Base class for WebExtension APIs. Each API creates a new class
* that inherits from this class, the derived class is instantiated
* once for each extension that uses the API.
*/
class ExtensionAPI extends EventEmitter {
constructor(extension) {
super();
this.extension = extension;
this.onShutdown = null;
extension.once("shutdown", () => {
if (this.onShutdown) {
this.onShutdown(extension.shutdownReason);
}
this.extension = null;
});
}
destroy() {
}
onManifestEntry(entry) {
}
getAPI(context) {
throw new Error("Not Implemented");
}
}
/**
* This class contains the information we have about an individual
* extension. It is never instantiated directly, instead subclasses
* for each type of process extend this class and add members that are
* relevant for that process.
* @abstract
*/
class BaseContext {
constructor(envType, extension) {
this.envType = envType;
this.onClose = new Set();
this.checkedLastError = false;
this._lastError = null;
this.contextId = getUniqueId();
this.unloaded = false;
this.extension = extension;
this.jsonSandbox = null;
this.active = true;
this.incognito = null;
this.messageManager = null;
this.docShell = null;
this.contentWindow = null;
this.innerWindowID = 0;
this.childManager = null;
this.viewType = null;
}
setContentWindow(contentWindow) {
let {document, docShell} = contentWindow;
this.innerWindowID = getInnerWindowID(contentWindow);
this.messageManager = docShell.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIContentFrameMessageManager);
if (this.incognito == null) {
this.incognito = PrivateBrowsingUtils.isContentWindowPrivate(contentWindow);
}
MessageChannel.setupMessageManagers([this.messageManager]);
let onPageShow = event => {
if (!event || event.target === document) {
this.docShell = docShell;
this.contentWindow = contentWindow;
this.active = true;
}
};
let onPageHide = event => {
if (!event || event.target === document) {
// Put this off until the next tick.
Promise.resolve().then(() => {
this.docShell = null;
this.contentWindow = null;
this.active = false;
});
}
};
onPageShow();
contentWindow.addEventListener("pagehide", onPageHide, true);
contentWindow.addEventListener("pageshow", onPageShow, true);
this.callOnClose({
close: () => {
onPageHide();
if (this.active) {
contentWindow.removeEventListener("pagehide", onPageHide, true);
contentWindow.removeEventListener("pageshow", onPageShow, true);
}
},
});
}
/** @returns {any} */
get cloneScope() {
throw new Error("Not implemented");
}
/** @returns {any} */
get principal() {
throw new Error("Not implemented");
}
runSafe(callback, ...args) {
return this.applySafe(callback, args);
}
runSafeWithoutClone(callback, ...args) {
return this.applySafeWithoutClone(callback, args);
}
applySafe(callback, args, caller) {
if (this.unloaded) {
Cu.reportError("context.runSafe called after context unloaded",
caller);
} else if (!this.active) {
Cu.reportError("context.runSafe called while context is inactive",
caller);
} else {
try {
let {cloneScope} = this;
args = args.map(arg => Cu.cloneInto(arg, cloneScope));
} catch (e) {
Cu.reportError(e);
dump(`runSafe failure: cloning into ${this.cloneScope}: ${e}\n\n${filterStack(Error())}`);
}
return this.applySafeWithoutClone(callback, args, caller);
}
}
applySafeWithoutClone(callback, args, caller) {
if (this.unloaded) {
Cu.reportError("context.runSafeWithoutClone called after context unloaded",
caller);
} else if (!this.active) {
Cu.reportError("context.runSafeWithoutClone called while context is inactive",
caller);
} else {
try {
return Reflect.apply(callback, null, args);
} catch (e) {
dump(`Extension error: ${e} ${e.fileName} ${e.lineNumber}\n[[Exception stack\n${filterStack(e)}Current stack\n${filterStack(Error())}]]\n`);
Cu.reportError(e);
}
}
}
checkLoadURL(url, options = {}) {
// As an optimization, f the URL starts with the extension's base URL,
// don't do any further checks. It's always allowed to load it.
if (url.startsWith(this.extension.baseURL)) {
return true;
}
return checkLoadURL(url, this.principal, options);
}
/**
* Safely call JSON.stringify() on an object that comes from an
* extension.
*
* @param {Array<any>} args Arguments for JSON.stringify()
* @returns {string} The stringified representation of obj
*/
jsonStringify(...args) {
if (!this.jsonSandbox) {
this.jsonSandbox = Cu.Sandbox(this.principal, {
sameZoneAs: this.cloneScope,
wantXrays: false,
});
}
return Cu.waiveXrays(this.jsonSandbox.JSON).stringify(...args);
}
callOnClose(obj) {
this.onClose.add(obj);
}
forgetOnClose(obj) {
this.onClose.delete(obj);
}
/**
* A wrapper around MessageChannel.sendMessage which adds the extension ID
* to the recipient object, and ensures replies are not processed after the
* context has been unloaded.
*
* @param {nsIMessageManager} target
* @param {string} messageName
* @param {object} data
* @param {object} [options]
* @param {object} [options.sender]
* @param {object} [options.recipient]
*
* @returns {Promise}
*/
sendMessage(target, messageName, data, options = {}) {
options.recipient = Object.assign({extensionId: this.extension.id}, options.recipient);
options.sender = options.sender || {};
options.sender.extensionId = this.extension.id;
options.sender.contextId = this.contextId;
return MessageChannel.sendMessage(target, messageName, data, options);
}
get lastError() {
this.checkedLastError = true;
return this._lastError;
}
set lastError(val) {
this.checkedLastError = false;
this._lastError = val;
}
/**
* Normalizes the given error object for use by the target scope. If
* the target is an error object which belongs to that scope, it is
* returned as-is. If it is an ordinary object with a `message`
* property, it is converted into an error belonging to the target
* scope. If it is an Error object which does *not* belong to the
* clone scope, it is reported, and converted to an unexpected
* exception error.
*
* @param {Error|object} error
* @param {SavedFrame?} [caller]
* @returns {Error}
*/
normalizeError(error, caller) {
if (error instanceof this.cloneScope.Error) {
return error;
}
let message, fileName;
if (error && typeof error === "object") {
const isPlain = ChromeUtils.getClassName(error) === "Object";
if (isPlain && error.mozWebExtLocation) {
caller = error.mozWebExtLocation;
}
if (isPlain && caller && (error.mozWebExtLocation || !error.fileName)) {
caller = Cu.cloneInto(caller, this.cloneScope);
return ChromeUtils.createError(error.message, caller);
}
if (isPlain ||
error instanceof ExtensionError ||
this.principal.subsumes(Cu.getObjectPrincipal(error))) {
message = error.message;
fileName = error.fileName;
}
}
if (!message) {
Cu.reportError(error);
message = "An unexpected error occurred";
}
return new this.cloneScope.Error(message, fileName);
}
/**
* Sets the value of `.lastError` to `error`, calls the given
* callback, and reports an error if the value has not been checked
* when the callback returns.
*
* @param {object} error An object with a `message` property. May
* optionally be an `Error` object belonging to the target scope.
* @param {SavedFrame?} caller
* The optional caller frame which triggered this callback, to be used
* in error reporting.
* @param {function} callback The callback to call.
* @returns {*} The return value of callback.
*/
withLastError(error, caller, callback) {
this.lastError = this.normalizeError(error);
try {
return callback();
} finally {
if (!this.checkedLastError) {
Cu.reportError(`Unchecked lastError value: ${this.lastError}`, caller);
}
this.lastError = null;
}
}
/**
* Captures the most recent stack frame which belongs to the extension.
*
* @returns {SavedFrame?}
*/
getCaller() {
return ChromeUtils.getCallerLocation(this.principal);
}
/**
* Wraps the given promise so it can be safely returned to extension
* code in this context.
*
* If `callback` is provided, however, it is used as a completion
* function for the promise, and no promise is returned. In this case,
* the callback is called when the promise resolves or rejects. In the
* latter case, `lastError` is set to the rejection value, and the
* callback function must check `browser.runtime.lastError` or
* `extension.runtime.lastError` in order to prevent it being reported
* to the console.
*
* @param {Promise} promise The promise with which to wrap the
* callback. May resolve to a `SpreadArgs` instance, in which case
* each element will be used as a separate argument.
*
* Unless the promise object belongs to the cloneScope global, its
* resolution value is cloned into cloneScope prior to calling the
* `callback` function or resolving the wrapped promise.
*
* @param {function} [callback] The callback function to wrap
*
* @returns {Promise|undefined} If callback is null, a promise object
* belonging to the target scope. Otherwise, undefined.
*/
wrapPromise(promise, callback = null) {
let caller = this.getCaller();
let applySafe = this.applySafe.bind(this);
if (Cu.getGlobalForObject(promise) === this.cloneScope) {
applySafe = this.applySafeWithoutClone.bind(this);
}
if (callback) {
promise.then(
args => {
if (this.unloaded) {
Cu.reportError(`Promise resolved after context unloaded\n`,
caller);
} else if (!this.active) {
Cu.reportError(`Promise resolved while context is inactive\n`,
caller);
} else if (args instanceof NoCloneSpreadArgs) {
this.applySafeWithoutClone(callback, args.unwrappedValues, caller);
} else if (args instanceof SpreadArgs) {
applySafe(callback, args, caller);
} else {
applySafe(callback, [args], caller);
}
},
error => {
this.withLastError(error, caller, () => {
if (this.unloaded) {
Cu.reportError(`Promise rejected after context unloaded\n`,
caller);
} else if (!this.active) {
Cu.reportError(`Promise rejected while context is inactive\n`,
caller);
} else {
this.applySafeWithoutClone(callback, [], caller);
}
});
});
} else {
return new this.cloneScope.Promise((resolve, reject) => {
promise.then(
value => {
if (this.unloaded) {
Cu.reportError(`Promise resolved after context unloaded\n`,
caller);
} else if (!this.active) {
Cu.reportError(`Promise resolved while context is inactive\n`,
caller);
} else if (value instanceof NoCloneSpreadArgs) {
let values = value.unwrappedValues;
this.applySafeWithoutClone(resolve, values.length == 1 ? [values[0]] : [values],
caller);
} else if (value instanceof SpreadArgs) {
applySafe(resolve, value.length == 1 ? value : [value],
caller);
} else {
applySafe(resolve, [value], caller);
}
},
value => {
if (this.unloaded) {
Cu.reportError(`Promise rejected after context unloaded: ${value && value.message}\n`,
caller);
} else if (!this.active) {
Cu.reportError(`Promise rejected while context is inactive: ${value && value.message}\n`,
caller);
} else {
this.applySafeWithoutClone(reject, [this.normalizeError(value, caller)],
caller);
}
});
});
}
}
unload() {
this.unloaded = true;
MessageChannel.abortResponses({
extensionId: this.extension.id,
contextId: this.contextId,
});
for (let obj of this.onClose) {
obj.close();
}
}
/**
* A simple proxy for unload(), for use with callOnClose().
*/
close() {
this.unload();
}
}
/**
* An object that runs the implementation of a schema API. Instantiations of
* this interfaces are used by Schemas.jsm.
*
* @interface
*/
class SchemaAPIInterface {
/**
* Calls this as a function that returns its return value.
*
* @abstract
* @param {Array} args The parameters for the function.
* @returns {*} The return value of the invoked function.
*/
callFunction(args) {
throw new Error("Not implemented");
}
/**
* Calls this as a function and ignores its return value.
*
* @abstract
* @param {Array} args The parameters for the function.
*/
callFunctionNoReturn(args) {
throw new Error("Not implemented");
}
/**
* Calls this as a function that completes asynchronously.
*
* @abstract
* @param {Array} args The parameters for the function.
* @param {function(*)} [callback] The callback to be called when the function
* completes.
* @param {boolean} [requireUserInput=false] If true, the function should
* fail if the browser is not currently handling user input.
* @returns {Promise|undefined} Must be void if `callback` is set, and a
* promise otherwise. The promise is resolved when the function completes.
*/
callAsyncFunction(args, callback, requireUserInput = false) {
throw new Error("Not implemented");
}
/**
* Retrieves the value of this as a property.
*
* @abstract
* @returns {*} The value of the property.
*/
getProperty() {
throw new Error("Not implemented");
}
/**
* Assigns the value to this as property.
*
* @abstract
* @param {string} value The new value of the property.
*/
setProperty(value) {
throw new Error("Not implemented");
}
/**
* Registers a `listener` to this as an event.
*
* @abstract
* @param {function} listener The callback to be called when the event fires.
* @param {Array} args Extra parameters for EventManager.addListener.
* @see EventManager.addListener
*/
addListener(listener, args) {
throw new Error("Not implemented");
}
/**
* Checks whether `listener` is listening to this as an event.
*
* @abstract
* @param {function} listener The event listener.
* @returns {boolean} Whether `listener` is registered with this as an event.
* @see EventManager.hasListener
*/
hasListener(listener) {
throw new Error("Not implemented");
}
/**
* Unregisters `listener` from this as an event.
*
* @abstract
* @param {function} listener The event listener.
* @see EventManager.removeListener
*/
removeListener(listener) {
throw new Error("Not implemented");
}
/**
* Revokes the implementation object, and prevents any further method
* calls from having external effects.
*
* @abstract
*/
revoke() {
throw new Error("Not implemented");
}
}
/**
* An object that runs a locally implemented API.
*/
class LocalAPIImplementation extends SchemaAPIInterface {
/**
* Constructs an implementation of the `name` method or property of `pathObj`.
*
* @param {object} pathObj The object containing the member with name `name`.
* @param {string} name The name of the implemented member.
* @param {BaseContext} context The context in which the schema is injected.
*/
constructor(pathObj, name, context) {
super();
this.pathObj = pathObj;
this.name = name;
this.context = context;
}
revoke() {
if (this.pathObj[this.name][Schemas.REVOKE]) {
this.pathObj[this.name][Schemas.REVOKE]();
}
this.pathObj = null;
this.name = null;
this.context = null;
}
callFunction(args) {
return this.pathObj[this.name](...args);
}
callFunctionNoReturn(args) {
this.pathObj[this.name](...args);
}
callAsyncFunction(args, callback, requireUserInput) {
let promise;
try {
if (requireUserInput) {
if (!getWinUtils(this.context.contentWindow).isHandlingUserInput) {
throw new ExtensionError(`${this.name} may only be called from a user input handler`);
}
}
promise = this.pathObj[this.name](...args) || Promise.resolve();
} catch (e) {
promise = Promise.reject(e);
}
return this.context.wrapPromise(promise, callback);
}
getProperty() {
return this.pathObj[this.name];
}
setProperty(value) {
this.pathObj[this.name] = value;
}
addListener(listener, args) {
try {
this.pathObj[this.name].addListener.call(null, listener, ...args);
} catch (e) {
throw this.context.normalizeError(e);
}
}
hasListener(listener) {
return this.pathObj[this.name].hasListener.call(null, listener);
}
removeListener(listener) {
this.pathObj[this.name].removeListener.call(null, listener);
}
}
// Recursively copy properties from source to dest.
function deepCopy(dest, source) {
for (let prop in source) {
let desc = Object.getOwnPropertyDescriptor(source, prop);
if (typeof(desc.value) == "object") {
if (!(prop in dest)) {
dest[prop] = {};
}
deepCopy(dest[prop], source[prop]);
} else {
Object.defineProperty(dest, prop, desc);
}
}
}
function getChild(map, key) {
let child = map.children.get(key);
if (!child) {
child = {
modules: new Set(),
children: new Map(),
};
map.children.set(key, child);
}
return child;
}
function getPath(map, path) {
for (let key of path) {
map = getChild(map, key);
}
return map;
}
function mergePaths(dest, source) {
for (let name of source.modules) {
dest.modules.add(name);
}
for (let [name, child] of source.children.entries()) {
mergePaths(getChild(dest, name),
child);
}
}
/**
* Manages loading and accessing a set of APIs for a specific extension
* context.
*/
class CanOfAPIs {
/**
* @param {BaseContext} context
* The context to manage APIs for.
* @param {SchemaAPIManager} apiManager
* The API manager holding the APIs to manage.
* @param {object} root
* The root object into which APIs will be injected.
*/
constructor(context, apiManager, root) {
this.context = context;
this.scopeName = context.envType;
this.apiManager = apiManager;
this.root = root;
this.apiPaths = new Map();
this.apis = new Map();
}
/**
* Synchronously loads and initializes an ExtensionAPI instance.
*
* @param {string} name
* The name of the API to load.
*/