-
Notifications
You must be signed in to change notification settings - Fork 1
/
VSS.SDK.js
1410 lines (1410 loc) · 59.2 KB
/
VSS.SDK.js
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
//dependencies=
// Copyright (C) Microsoft Corporation. All rights reserved.
///<reference path='../References/VSS-Common.d.ts' />
///<reference path='../References/VSS.SDK.Interfaces.d.ts' />
///<reference path='../References/SDK.Interfaces.d.ts' />
///<reference path='../References/VSS.SDK.Interfaces.d.ts' />
///<reference path='../References/VSS-Common.d.ts' />
/// This file is going to be embedded into the following typescript files in the build time:
/// - VSS/SDK/XDM.ts
/// - VSS/SDK/VSS.SDK.ts
/// This module is unlike other modules which doesn't use AMD loading.
var XDM;
(function (XDM) {
/**
* Create a new deferred object
*/
function createDeferred() {
return new XdmDeferred();
}
XDM.createDeferred = createDeferred;
var XdmDeferred = (function () {
function XdmDeferred() {
var _this = this;
this._resolveCallbacks = [];
this._rejectCallbacks = [];
this._isResolved = false;
this._isRejected = false;
this.resolve = function (result) {
_this._resolve(result);
};
this.reject = function (reason) {
_this._reject(reason);
};
this.promise = {};
this.promise.then = function (onFulfill, onReject) {
return _this._then(onFulfill, onReject);
};
}
XdmDeferred.prototype._then = function (onFulfill, onReject) {
var _this = this;
if ((!onFulfill && !onReject) ||
(this._isResolved && !onFulfill) ||
(this._isRejected && !onReject)) {
return this.promise;
}
var newDeferred = new XdmDeferred();
this._resolveCallbacks.push(function (value) {
_this._wrapCallback(onFulfill, value, newDeferred, false);
});
this._rejectCallbacks.push(function (reason) {
_this._wrapCallback(onReject, reason, newDeferred, true);
});
if (this._isResolved) {
this._resolve(this._resolvedValue);
}
else if (this._isRejected) {
this._reject(this._rejectValue);
}
return newDeferred.promise;
};
XdmDeferred.prototype._wrapCallback = function (callback, value, deferred, reject) {
if (!callback) {
if (reject) {
deferred.reject(value);
}
else {
deferred.resolve(value);
}
return;
}
var result;
try {
result = callback(value);
}
catch (ex) {
deferred.reject(ex);
return;
}
if (result === undefined) {
deferred.resolve(value);
}
else if (result && typeof result.then === "function") {
result.then(function (innerResult) {
deferred.resolve(innerResult);
}, function (innerReason) {
deferred.reject(innerReason);
});
}
else {
deferred.resolve(result);
}
};
XdmDeferred.prototype._resolve = function (result) {
if (!this._isRejected && !this._isResolved) {
this._isResolved = true;
this._resolvedValue = result;
}
if (this._isResolved && this._resolveCallbacks.length > 0) {
var resolveCallbacks = this._resolveCallbacks.splice(0);
// 2.2.4. #onFulfilled or onRejected must not be called until the execution context stack contains only platform code.
window.setTimeout(function () {
for (var i = 0, l = resolveCallbacks.length; i < l; i++) {
resolveCallbacks[i](result);
}
});
}
};
XdmDeferred.prototype._reject = function (reason) {
if (!this._isRejected && !this._isResolved) {
this._isRejected = true;
this._rejectValue = reason;
if (this._rejectCallbacks.length === 0 && window.console && window.console.warn) {
console.warn("Rejected XDM promise with no reject callbacks");
if (reason) {
console.warn(reason);
}
}
}
if (this._isRejected && this._rejectCallbacks.length > 0) {
var rejectCallbacks = this._rejectCallbacks.splice(0);
// 2.2.4. #onFulfilled or onRejected must not be called until the execution context stack contains only platform code.
window.setTimeout(function () {
for (var i = 0, l = rejectCallbacks.length; i < l; i++) {
rejectCallbacks[i](reason);
}
});
}
};
return XdmDeferred;
}());
var smallestRandom = parseInt("10000000000", 36);
var maxSafeInteger = Number.MAX_SAFE_INTEGER || 9007199254740991;
/**
* Create a new random 22-character fingerprint.
* @return string fingerprint
*/
function newFingerprint() {
// smallestRandom ensures we will get a 11-character result from the base-36 conversion.
return Math.floor((Math.random() * (maxSafeInteger - smallestRandom)) + smallestRandom).toString(36) +
Math.floor((Math.random() * (maxSafeInteger - smallestRandom)) + smallestRandom).toString(36);
}
/**
* Catalog of objects exposed for XDM
*/
var XDMObjectRegistry = (function () {
function XDMObjectRegistry() {
this._registeredObjects = {};
}
/**
* Register an object (instance or factory method) exposed by this frame to callers in a remote frame
*
* @param instanceId unique id of the registered object
* @param instance Either: (1) an object instance, or (2) a function that takes optional context data and returns an object instance.
*/
XDMObjectRegistry.prototype.register = function (instanceId, instance) {
this._registeredObjects[instanceId] = instance;
};
/**
* Unregister an object (instance or factory method) that was previously registered by this frame
*
* @param instanceId unique id of the registered object
*/
XDMObjectRegistry.prototype.unregister = function (instanceId) {
delete this._registeredObjects[instanceId];
};
/**
* Get an instance of an object registered with the given id
*
* @param instanceId unique id of the registered object
* @param contextData Optional context data to pass to a registered object's factory method
*/
XDMObjectRegistry.prototype.getInstance = function (instanceId, contextData) {
var instance = this._registeredObjects[instanceId];
if (!instance) {
return null;
}
if (typeof instance === "function") {
return instance(contextData);
}
else {
return instance;
}
};
return XDMObjectRegistry;
}());
XDM.XDMObjectRegistry = XDMObjectRegistry;
;
/**
* The registry of global XDM handlers
*/
XDM.globalObjectRegistry = new XDMObjectRegistry();
/**
* Represents a channel of communication between frames\document
* Stays "alive" across multiple funtion\method calls
*/
var XDMChannel = (function () {
function XDMChannel(postToWindow, targetOrigin) {
if (targetOrigin === void 0) { targetOrigin = null; }
this._nextMessageId = 1;
this._deferreds = {};
this._nextProxyFunctionId = 1;
this._proxyFunctions = {};
this._postToWindow = postToWindow;
this._targetOrigin = targetOrigin;
this._channelObjectRegistry = new XDMObjectRegistry();
this._channelId = XDMChannel._nextChannelId++;
if (!this._targetOrigin) {
this._handshakeToken = newFingerprint();
}
}
/**
* Get the object registry to handle messages from this specific channel.
* Upon receiving a message, this channel registry will be used first, then
* the global registry will be used if no handler is found here.
*/
XDMChannel.prototype.getObjectRegistry = function () {
return this._channelObjectRegistry;
};
/**
* Invoke a method via RPC. Lookup the registered object on the remote end of the channel and invoke the specified method.
*
* @param method Name of the method to invoke
* @param instanceId unique id of the registered object
* @param params Arguments to the method to invoke
* @param instanceContextData Optional context data to pass to a registered object's factory method
* @param serializationSettings Optional serialization settings
*/
XDMChannel.prototype.invokeRemoteMethod = function (methodName, instanceId, params, instanceContextData, serializationSettings) {
var message = {
id: this._nextMessageId++,
methodName: methodName,
instanceId: instanceId,
instanceContext: instanceContextData,
params: this._customSerializeObject(params, serializationSettings),
jsonrpc: "2.0",
serializationSettings: serializationSettings
};
if (!this._targetOrigin) {
message.handshakeToken = this._handshakeToken;
}
var deferred = createDeferred();
this._deferreds[message.id] = deferred;
this._sendRpcMessage(message);
return deferred.promise;
};
/**
* Get a proxied object that represents the object registered with the given instance id on the remote side of this channel.
*
* @param instanceId unique id of the registered object
* @param contextData Optional context data to pass to a registered object's factory method
*/
XDMChannel.prototype.getRemoteObjectProxy = function (instanceId, contextData) {
return this.invokeRemoteMethod(null, instanceId, null, contextData);
};
XDMChannel.prototype.invokeMethod = function (registeredInstance, rpcMessage) {
var _this = this;
if (!rpcMessage.methodName) {
// Null/empty method name indicates to return the registered object itself.
this._success(rpcMessage, registeredInstance, rpcMessage.handshakeToken);
return;
}
var method = registeredInstance[rpcMessage.methodName];
if (typeof method !== "function") {
this._error(rpcMessage, new Error("RPC method not found: " + rpcMessage.methodName), rpcMessage.handshakeToken);
return;
}
try {
// Call specified method. Add nested success and error call backs with closure
// so we can post back a response as a result or error as appropriate
var methodArgs = [];
if (rpcMessage.params) {
methodArgs = this._customDeserializeObject(rpcMessage.params);
}
var result = method.apply(registeredInstance, methodArgs);
if (result && result.then && typeof result.then === "function") {
result.then(function (asyncResult) {
_this._success(rpcMessage, asyncResult, rpcMessage.handshakeToken);
}, function (e) {
_this._error(rpcMessage, e, rpcMessage.handshakeToken);
});
}
else {
this._success(rpcMessage, result, rpcMessage.handshakeToken);
}
}
catch (exception) {
// send back as error if an exception is thrown
this._error(rpcMessage, exception, rpcMessage.handshakeToken);
}
};
XDMChannel.prototype.getRegisteredObject = function (instanceId, instanceContext) {
if (instanceId === "__proxyFunctions") {
// Special case for proxied functions of remote instances
return this._proxyFunctions;
}
// Look in the channel registry first
var registeredObject = this._channelObjectRegistry.getInstance(instanceId, instanceContext);
if (!registeredObject) {
// Look in the global registry as a fallback
registeredObject = XDM.globalObjectRegistry.getInstance(instanceId, instanceContext);
}
return registeredObject;
};
/**
* Handle a received message on this channel. Dispatch to the appropriate object found via object registry
*
* @param data Message data
* @param origin Origin of the frame that sent the message
* @return True if the message was handled by this channel. Otherwise false.
*/
XDMChannel.prototype.onMessage = function (data, origin) {
var _this = this;
var rpcMessage = data;
if (rpcMessage.instanceId) {
// Find the object that handles this requestNeed to find implementation
// Look in the channel registry first
var registeredObject = this.getRegisteredObject(rpcMessage.instanceId, rpcMessage.instanceContext);
if (!registeredObject) {
// If not found return false to indicate that the message was not handled
return false;
}
if (typeof registeredObject["then"] === "function") {
registeredObject.then(function (resolvedInstance) {
_this.invokeMethod(resolvedInstance, rpcMessage);
}, function (e) {
_this._error(rpcMessage, e, rpcMessage.handshakeToken);
});
}
else {
this.invokeMethod(registeredObject, rpcMessage);
}
}
else {
// response
// Responses look like this -
// {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"}
// {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found."}, "id": "5"}
var deferred = this._deferreds[rpcMessage.id];
if (!deferred) {
// Message not handled by this channel.
return false;
}
if (rpcMessage.error) {
deferred.reject(this._customDeserializeObject([rpcMessage.error])[0]);
}
else {
deferred.resolve(this._customDeserializeObject([rpcMessage.result])[0]);
}
delete this._deferreds[rpcMessage.id];
}
// Message handled by this channel
return true;
};
XDMChannel.prototype.owns = function (source, origin, data) {
/// Determines whether the current message belongs to this channel or not
var rpcMessage = data;
if (this._postToWindow === source) {
// For messages coming from sandboxed iframes the origin will be set to the string "null". This is
// how onprem works. If it is not a sandboxed iFrame we will get the origin as expected.
if (this._targetOrigin) {
if (origin) {
return origin.toLowerCase() === "null" || this._targetOrigin.toLowerCase().indexOf(origin.toLowerCase()) === 0;
}
else {
return false;
}
}
else {
if (rpcMessage.handshakeToken && rpcMessage.handshakeToken === this._handshakeToken) {
this._targetOrigin = origin;
return true;
}
}
}
return false;
};
XDMChannel.prototype.error = function (data, errorObj) {
var rpcMessage = data;
this._error(rpcMessage, errorObj, rpcMessage.handshakeToken);
};
XDMChannel.prototype._error = function (messageObj, errorObj, handshakeToken) {
// Post back a response as an error which look like this -
// {"id": "5", "error": {"code": -32601, "message": "Method not found."}, "jsonrpc": "2.0", }
var message = {
id: messageObj.id,
error: this._customSerializeObject([errorObj], messageObj.serializationSettings)[0],
jsonrpc: "2.0",
handshakeToken: handshakeToken
};
this._sendRpcMessage(message);
};
XDMChannel.prototype._success = function (messageObj, result, handshakeToken) {
// Post back response result which look like this -
// {"id": "9", "result": ["hello", 5], "jsonrpc": "2.0"}
var message = {
id: messageObj.id,
result: this._customSerializeObject([result], messageObj.serializationSettings)[0],
jsonrpc: "2.0",
handshakeToken: handshakeToken
};
this._sendRpcMessage(message);
};
XDMChannel.prototype._sendRpcMessage = function (message) {
var messageString = JSON.stringify(message);
this._postToWindow.postMessage(messageString, "*");
};
XDMChannel.prototype._shouldSkipSerialization = function (obj) {
for (var i = 0, l = XDMChannel.WINDOW_TYPES_TO_SKIP_SERIALIZATION.length; i < l; i++) {
var instanceType = XDMChannel.WINDOW_TYPES_TO_SKIP_SERIALIZATION[i];
if (window[instanceType] && obj instanceof window[instanceType]) {
return true;
}
}
if (window.jQuery) {
for (var i = 0, l = XDMChannel.JQUERY_TYPES_TO_SKIP_SERIALIZATION.length; i < l; i++) {
var instanceType = XDMChannel.JQUERY_TYPES_TO_SKIP_SERIALIZATION[i];
if (window.jQuery[instanceType] && obj instanceof window.jQuery[instanceType]) {
return true;
}
}
}
return false;
};
XDMChannel.prototype._customSerializeObject = function (obj, settings, parentObjects, nextCircularRefId, depth) {
var _this = this;
if (parentObjects === void 0) { parentObjects = null; }
if (nextCircularRefId === void 0) { nextCircularRefId = 1; }
if (depth === void 0) { depth = 1; }
if (!obj || depth > XDMChannel.MAX_XDM_DEPTH) {
return null;
}
if (this._shouldSkipSerialization(obj)) {
return null;
}
var serializeMember = function (parentObject, newObject, key) {
var item;
try {
item = parentObject[key];
}
catch (ex) {
// Cannot access this property. Skip its serialization.
}
var itemType = typeof item;
if (itemType === "undefined") {
return;
}
// Check for a circular reference by looking at parent objects
var parentItemIndex = -1;
if (itemType === "object") {
parentItemIndex = parentObjects.originalObjects.indexOf(item);
}
if (parentItemIndex >= 0) {
// Circular reference found. Add reference to parent
var parentItem = parentObjects.newObjects[parentItemIndex];
if (!parentItem.__circularReferenceId) {
parentItem.__circularReferenceId = nextCircularRefId++;
}
newObject[key] = {
__circularReference: parentItem.__circularReferenceId
};
}
else {
if (itemType === "function") {
var proxyFunctionId = _this._nextProxyFunctionId++;
newObject[key] = {
__proxyFunctionId: _this._registerProxyFunction(item, obj),
__channelId: _this._channelId
};
}
else if (itemType === "object") {
if (item && item instanceof Date) {
newObject[key] = {
__proxyDate: item.getTime()
};
}
else {
newObject[key] = _this._customSerializeObject(item, settings, parentObjects, nextCircularRefId, depth + 1);
}
}
else if (key !== "__proxyFunctionId") {
// Just add non object/function properties as-is. Don't include "__proxyFunctionId" to protect
// our proxy methods from being invoked from other messages.
newObject[key] = item;
}
}
};
var returnValue;
if (!parentObjects) {
parentObjects = {
newObjects: [],
originalObjects: []
};
}
parentObjects.originalObjects.push(obj);
if (obj instanceof Array) {
returnValue = [];
parentObjects.newObjects.push(returnValue);
for (var i = 0, l = obj.length; i < l; i++) {
serializeMember(obj, returnValue, i);
}
}
else {
returnValue = {};
parentObjects.newObjects.push(returnValue);
var keys = {};
try {
// We want to get both enumerable and non-enumerable properties
// including inherited enumerable properties. for..in grabs
// enumerable properties (including inherited properties) and
// getOwnPropertyNames includes non-enumerable properties.
// Merge these results together.
for (var key in obj) {
keys[key] = true;
}
var ownProperties = Object.getOwnPropertyNames(obj);
for (var i = 0, l = ownProperties.length; i < l; i++) {
keys[ownProperties[i]] = true;
}
}
catch (ex) {
// We may not be able to access the iterator of this object. Skip its serialization.
}
for (var key in keys) {
// Don't serialize properties that start with an underscore.
if ((key && key[0] !== "_") || (settings && settings.includeUnderscoreProperties)) {
serializeMember(obj, returnValue, key);
}
}
}
parentObjects.originalObjects.pop();
parentObjects.newObjects.pop();
return returnValue;
};
XDMChannel.prototype._registerProxyFunction = function (func, context) {
var proxyFunctionId = this._nextProxyFunctionId++;
this._proxyFunctions["proxy" + proxyFunctionId] = function () {
return func.apply(context, Array.prototype.slice.call(arguments, 0));
};
return proxyFunctionId;
};
XDMChannel.prototype._customDeserializeObject = function (obj, circularRefs) {
var _this = this;
var that = this;
if (!obj) {
return null;
}
if (!circularRefs) {
circularRefs = {};
}
var deserializeMember = function (parentObject, key) {
var item = parentObject[key];
var itemType = typeof item;
if (key === "__circularReferenceId" && itemType === 'number') {
circularRefs[item] = parentObject;
delete parentObject[key];
}
else if (itemType === "object" && item) {
if (item.__proxyFunctionId) {
parentObject[key] = function () {
return that.invokeRemoteMethod("proxy" + item.__proxyFunctionId, "__proxyFunctions", Array.prototype.slice.call(arguments, 0), null, { includeUnderscoreProperties: true });
};
}
else if (item.__proxyDate) {
parentObject[key] = new Date(item.__proxyDate);
}
else if (item.__circularReference) {
parentObject[key] = circularRefs[item.__circularReference];
}
else {
_this._customDeserializeObject(item, circularRefs);
}
}
};
if (obj instanceof Array) {
for (var i = 0, l = obj.length; i < l; i++) {
deserializeMember(obj, i);
}
}
else if (typeof obj === "object") {
for (var key in obj) {
deserializeMember(obj, key);
}
}
return obj;
};
return XDMChannel;
}());
XDMChannel._nextChannelId = 1;
XDMChannel.MAX_XDM_DEPTH = 100;
XDMChannel.WINDOW_TYPES_TO_SKIP_SERIALIZATION = [
"Node",
"Window",
"Event"
];
XDMChannel.JQUERY_TYPES_TO_SKIP_SERIALIZATION = [
"jQuery"
];
XDM.XDMChannel = XDMChannel;
/**
* Registry of XDM channels kept per target frame/window
*/
var XDMChannelManager = (function () {
function XDMChannelManager() {
this._channels = [];
this._subscribe(window);
}
XDMChannelManager.get = function () {
if (!this._default) {
this._default = new XDMChannelManager();
}
return this._default;
};
/**
* Add an XDM channel for the given target window/iframe
*
* @param window Target iframe window to communicate with
* @param targetOrigin Url of the target iframe (if known)
*/
XDMChannelManager.prototype.addChannel = function (window, targetOrigin) {
var channel = new XDMChannel(window, targetOrigin);
this._channels.push(channel);
return channel;
};
XDMChannelManager.prototype.removeChannel = function (channel) {
this._channels = this._channels.filter(function (c) { return c !== channel; });
};
XDMChannelManager.prototype._handleMessageReceived = function (event) {
// get channel and dispatch to it
var i, len, channel;
var rpcMessage;
if (typeof event.data === "string") {
try {
rpcMessage = JSON.parse(event.data);
}
catch (error) {
// The message is not a valid JSON string. Not one of our events.
}
}
if (rpcMessage) {
var handled = false;
var channelOwner;
for (i = 0, len = this._channels.length; i < len; i++) {
channel = this._channels[i];
if (channel.owns(event.source, event.origin, rpcMessage)) {
// keep a reference to the channel owner found.
channelOwner = channel;
handled = channel.onMessage(rpcMessage, event.origin) || handled;
}
}
if (!!channelOwner && !handled) {
if (window.console) {
console.error("No handler found on any channel for message: " + JSON.stringify(rpcMessage));
}
// for instance based proxies, send an error on the channel owning the message to resolve any control creation promises
// on the host frame.
if (rpcMessage.instanceId) {
channelOwner.error(rpcMessage, "The registered object " + rpcMessage.instanceId + " could not be found.");
}
}
}
};
XDMChannelManager.prototype._subscribe = function (windowObj) {
var _this = this;
if (windowObj.addEventListener) {
windowObj.addEventListener("message", function (event) {
_this._handleMessageReceived(event);
});
}
else {
// IE8
windowObj.attachEvent("onmessage", function (event) {
_this._handleMessageReceived(event);
});
}
};
return XDMChannelManager;
}());
XDM.XDMChannelManager = XDMChannelManager;
})(XDM || (XDM = {}));
var VSS;
(function (VSS) {
// W A R N I N G: if VssSDKVersion changes, the VSS WEB SDK demand resolver needs to be updated with the new version
VSS.VssSDKVersion = 2.0;
VSS.VssSDKRestVersion = "3.1";
var bodyElement;
var webContext;
var hostPageContext;
var extensionContext;
var initialConfiguration;
var initialContribution;
var initOptions;
var loaderConfigured = false;
var usingPlatformScripts;
var usingPlatformStyles;
var isReady = false;
var readyCallbacks;
var parentChannel = XDM.XDMChannelManager.get().addChannel(window.parent);
var shimmedLocalStorage;
var hostReadyForShimUpdates = false;
var Storage = (function () {
var changeCallback;
function invokeChangeCallback() {
if (changeCallback) {
changeCallback.call(this);
}
}
function Storage(changeCallback) {
}
Object.defineProperties(Storage.prototype, {
getItem: {
get: function () {
return function (key) {
var item = this["" + key];
return typeof item === "undefined" ? null : item;
};
}
},
setItem: {
get: function () {
return function (key, value) {
key = "" + key;
var existingValue = this[key];
var newValue = "" + value;
if (existingValue !== newValue) {
this[key] = newValue;
invokeChangeCallback();
}
};
}
},
removeItem: {
get: function () {
return function (key) {
key = "" + key;
if (typeof this[key] !== "undefined") {
delete this[key];
invokeChangeCallback();
}
};
}
},
clear: {
get: function () {
return function () {
var keys = Object.keys(this);
if (keys.length > 0) {
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
delete this[key];
}
invokeChangeCallback();
}
};
}
},
key: {
get: function () {
return function (index) {
return Object.keys(this)[index];
};
}
},
length: {
get: function () {
return Object.keys(this).length;
}
}
});
return Storage;
}());
function shimSandboxedProperties() {
var updateSettingsTimeout;
function updateShimmedStorageCallback() {
// Talk to the host frame on a 50 ms delay in order to batch storage/cookie updates
if (!updateSettingsTimeout) {
updateSettingsTimeout = setTimeout(function () {
updateSettingsTimeout = 0;
updateHostSandboxedStorage();
}, 50);
}
}
// Override document.cookie if it is not available
var hasCookieSupport = false;
try {
hasCookieSupport = typeof document.cookie === "string";
}
catch (ex) {
}
if (!hasCookieSupport) {
Object.defineProperty(Document.prototype, "cookie", {
get: function () {
return "";
},
set: function (value) {
}
});
}
// Override browser storage
var hasLocalStorage = false;
try {
hasLocalStorage = !!window.localStorage;
}
catch (ex) {
}
if (!hasLocalStorage) {
delete window.localStorage;
shimmedLocalStorage = new Storage(updateShimmedStorageCallback);
Object.defineProperty(window, "localStorage", { value: shimmedLocalStorage });
delete window.sessionStorage;
Object.defineProperty(window, "sessionStorage", { value: new Storage() });
}
}
if (!window["__vssNoSandboxShim"]) {
try {
shimSandboxedProperties();
}
catch (ex) {
if (window.console && window.console.warn) {
window.console.warn("Failed to shim support for sandboxed properties: " + ex.message + ". Set \"window.__vssNoSandboxShim = true\" in order to bypass the shim of sandboxed properties.");
}
}
}
/**
* Service Ids for core services (to be used in VSS.getService)
*/
var ServiceIds;
(function (ServiceIds) {
/**
* Service for showing dialogs in the host frame
* Use: <IHostDialogService>
*/
ServiceIds.Dialog = "ms.vss-web.dialog-service";
/**
* Service for interacting with the host frame's navigation (getting/updating the address/hash, reloading the page, etc.)
* Use: <IHostNavigationService>
*/
ServiceIds.Navigation = "ms.vss-web.navigation-service";
/**
* Service for interacting with extension data (setting/setting documents and collections)
* Use: <IExtensionDataService>
*/
ServiceIds.ExtensionData = "ms.vss-web.data-service";
})(ServiceIds = VSS.ServiceIds || (VSS.ServiceIds = {}));
/**
* Initiates the handshake with the host window.
*
* @param options Initialization options for the extension.
*/
function init(options) {
initOptions = options || {};
usingPlatformScripts = initOptions.usePlatformScripts;
usingPlatformStyles = initOptions.usePlatformStyles;
// Run this after current execution path is complete - allows objects to get initialized
window.setTimeout(function () {
var appHandshakeData = {
notifyLoadSucceeded: !initOptions.explicitNotifyLoaded,
extensionReusedCallback: initOptions.extensionReusedCallback,
vssSDKVersion: VSS.VssSDKVersion
};
parentChannel.invokeRemoteMethod("initialHandshake", "VSS.HostControl", [appHandshakeData]).then(function (handshakeData) {
hostPageContext = handshakeData.pageContext;
webContext = hostPageContext.webContext;
initialConfiguration = handshakeData.initialConfig || {};
initialContribution = handshakeData.contribution;
extensionContext = handshakeData.extensionContext;
if (handshakeData.sandboxedStorage) {
var updateNeeded = false;
if (shimmedLocalStorage) {
if (handshakeData.sandboxedStorage.localStorage) {
// Merge host data in with any values already set.
var newData = handshakeData.sandboxedStorage.localStorage;
// Check for any properties written prior to the initial handshake
for (var _i = 0, _a = Object.keys(shimmedLocalStorage); _i < _a.length; _i++) {
var key = _a[_i];
var value = shimmedLocalStorage.getItem(key);
if (value !== newData[key]) {
newData[key] = value;
updateNeeded = true;
}
}
// Update the stored values
for (var _b = 0, _c = Object.keys(newData); _b < _c.length; _b++) {
var key = _c[_b];
shimmedLocalStorage.setItem(key, newData[key]);
}
}
else if (shimmedLocalStorage.length > 0) {
updateNeeded = true;
}
}
hostReadyForShimUpdates = true;
if (updateNeeded) {
// Talk to host frame to issue update
updateHostSandboxedStorage();
}
}
if (usingPlatformScripts || usingPlatformStyles) {
setupAmdLoader();
}
else {
triggerReady();
}
});
}, 0);
}
VSS.init = init;
function updateHostSandboxedStorage() {
var storage = {
localStorage: JSON.stringify(shimmedLocalStorage || {})
};
parentChannel.invokeRemoteMethod("updateSandboxedStorage", "VSS.HostControl", [storage]);
}
/**
* Ensures that the AMD loader from the host is configured and fetches a script (AMD) module
* (and its dependencies). If no callback is supplied, this will still perform an asynchronous
* fetch of the module (unlike AMD require which returns synchronously). This method has no return value.
*
* Usage:
*
* VSS.require(["VSS/Controls", "VSS/Controls/Grids"], function(Controls, Grids) {
* ...
* });
*
* @param modules A single module path (string) or array of paths (string[])
* @param callback Method called once the modules have been loaded.
*/
function require(modules, callback) {
var modulesArray;
if (typeof modules === "string") {
modulesArray = [modules];
}
else {
modulesArray = modules;
}
if (!callback) {
// Generate an empty callback for require
callback = function () { };
}
if (loaderConfigured) {
// Loader already configured, just issue require
issueVssRequire(modulesArray, callback);
}
else {
if (!initOptions) {
init({ usePlatformScripts: true });
}
else if (!usingPlatformScripts) {
usingPlatformScripts = true;
if (isReady) {
// We are in the ready state, but previously not using the loader, so set it up now
// which will re-trigger ready
isReady = false;
setupAmdLoader();
}
}
ready(function () {
issueVssRequire(modulesArray, callback);
});
}
}
VSS.require = require;
function issueVssRequire(modules, callback) {
if (hostPageContext.diagnostics.bundlingEnabled) {
window.require(["VSS/Bundling"], function (VSS_Bundling) {
VSS_Bundling.requireModules(modules).spread(function () {
callback.apply(this, arguments);
});
});
}
else {
window.require(modules, callback);
}
}
/**
* Register a callback that gets called once the initial setup/handshake has completed.
* If the initial setup is already completed, the callback is invoked at the end of the current call stack.
*/
function ready(callback) {
if (isReady) {
window.setTimeout(callback, 0);
}
else {
if (!readyCallbacks) {
readyCallbacks = [];
}
readyCallbacks.push(callback);
}
}
VSS.ready = ready;
/**
* Notifies the host that the extension successfully loaded (stop showing the loading indicator)
*/
function notifyLoadSucceeded() {
parentChannel.invokeRemoteMethod("notifyLoadSucceeded", "VSS.HostControl");
}
VSS.notifyLoadSucceeded = notifyLoadSucceeded;
/**
* Notifies the host that the extension failed to load
*/
function notifyLoadFailed(e) {