@ms-atlas/datastudio 0.1.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of @ms-atlas/datastudio might be problematic. Click here for more details.

Files changed (39) hide show
  1. package/ExternalLibraries/Monaco/vs/loader.js +2166 -0
  2. package/ExternalLibraries/URI.min.js +1901 -0
  3. package/ExternalLibraries/crossroads.min.js +453 -0
  4. package/ExternalLibraries/css.js +165 -0
  5. package/ExternalLibraries/d3.min.js +10857 -0
  6. package/ExternalLibraries/es6-promise.min.js +363 -0
  7. package/ExternalLibraries/hammer.js +2224 -0
  8. package/ExternalLibraries/hull.js +444 -0
  9. package/ExternalLibraries/i18n.min.js +115 -0
  10. package/ExternalLibraries/jquery-ui-timepicker-addon.min.css +76 -0
  11. package/ExternalLibraries/jquery-ui-timepicker-addon.min.js +1918 -0
  12. package/ExternalLibraries/jquery-ui.js +17201 -0
  13. package/ExternalLibraries/jquery-ui.min.css +1454 -0
  14. package/ExternalLibraries/jquery.history.js +2173 -0
  15. package/ExternalLibraries/jquery.min.js +5168 -0
  16. package/ExternalLibraries/jquery.mockjax.min.js +445 -0
  17. package/ExternalLibraries/jquery.modal.js +173 -0
  18. package/ExternalLibraries/jstree.js +10086 -0
  19. package/ExternalLibraries/jstree.style.css +1048 -0
  20. package/ExternalLibraries/jwt-decode.min.js +142 -0
  21. package/ExternalLibraries/knockout-latest.debug.js +7375 -0
  22. package/ExternalLibraries/knockout.mapping.min.js +534 -0
  23. package/ExternalLibraries/moment.js +3389 -0
  24. package/ExternalLibraries/q.js +1974 -0
  25. package/ExternalLibraries/require.js +2230 -0
  26. package/ExternalLibraries/signals.min.js +179 -0
  27. package/ExternalLibraries/text.js +445 -0
  28. package/ExternalLibraries/uuid.js +274 -0
  29. package/app-main.js +1 -0
  30. package/datastudio.application.mainpage.js +1502 -0
  31. package/datastudio.application.shared.js +626 -0
  32. package/datastudio.bootstrapper.js +517 -0
  33. package/fonts.css +14 -0
  34. package/nls/resx.js +1 -0
  35. package/nls/root/resx.js +22 -0
  36. package/package.json +22 -0
  37. package/scripts/application/sourceMapper.js +15 -0
  38. package/scripts/libs/adal/adal.js +720 -0
  39. package/stylesheets/main.css +8879 -0
@@ -0,0 +1,1974 @@
1
+ // vim:ts=4:sts=4:sw=4:
2
+ /*!
3
+ *
4
+ * Copyright 2009-2012 Kris Kowal under the terms of the MIT
5
+ * license found at http://github.com/kriskowal/q/raw/master/LICENSE
6
+ *
7
+ * With parts by Tyler Close
8
+ * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found
9
+ * at http://www.opensource.org/licenses/mit-license.html
10
+ * Forked at ref_send.js version: 2009-05-11
11
+ *
12
+ * With parts by Mark Miller
13
+ * Copyright (C) 2011 Google Inc.
14
+ *
15
+ * Licensed under the Apache License, Version 2.0 (the "License");
16
+ * you may not use this file except in compliance with the License.
17
+ * You may obtain a copy of the License at
18
+ *
19
+ * http://www.apache.org/licenses/LICENSE-2.0
20
+ *
21
+ * Unless required by applicable law or agreed to in writing, software
22
+ * distributed under the License is distributed on an "AS IS" BASIS,
23
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
+ * See the License for the specific language governing permissions and
25
+ * limitations under the License.
26
+ *
27
+ */
28
+
29
+ (function (definition) {
30
+ // Turn off strict mode for this function so we can assign to global.Q
31
+ /* jshint strict: false */
32
+
33
+ // This file will function properly as a <script> tag, or a module
34
+ // using CommonJS and NodeJS or RequireJS module formats. In
35
+ // Common/Node/RequireJS, the module exports the Q API and when
36
+ // executed as a simple <script>, it creates a Q global instead.
37
+
38
+ // Montage Require
39
+ if (typeof bootstrap === "function") {
40
+ bootstrap("promise", definition);
41
+
42
+ // CommonJS
43
+ } else if (typeof exports === "object") {
44
+ module.exports = definition();
45
+
46
+ // RequireJS
47
+ } else if (typeof define === "function" && define.amd) {
48
+ define(definition);
49
+
50
+ // SES (Secure EcmaScript)
51
+ } else if (typeof ses !== "undefined") {
52
+ if (!ses.ok()) {
53
+ return;
54
+ } else {
55
+ ses.makeQ = definition;
56
+ }
57
+
58
+ // <script>
59
+ } else {
60
+ Q = definition();
61
+ }
62
+ })(function () {
63
+ var hasStacks = false;
64
+ try {
65
+ throw new Error();
66
+ } catch (e) {
67
+ hasStacks = !!e.stack;
68
+ }
69
+
70
+ // All code after this point will be filtered from stack traces reported
71
+ // by Q.
72
+ var qStartingLine = captureLine();
73
+ var qFileName;
74
+
75
+ // shims
76
+
77
+ // used for fallback in "allResolved"
78
+ var noop = function () {};
79
+
80
+ // Use the fastest possible means to execute a task in a future turn
81
+ // of the event loop.
82
+ var nextTick = (function () {
83
+ // linked list of tasks (single, with head node)
84
+ var head = { task: void 0, next: null };
85
+ var tail = head;
86
+ var flushing = false;
87
+ var requestTick = void 0;
88
+ var isNodeJS = false;
89
+
90
+ function flush() {
91
+ /* jshint loopfunc: true */
92
+
93
+ while (head.next) {
94
+ head = head.next;
95
+ var task = head.task;
96
+ head.task = void 0;
97
+ var domain = head.domain;
98
+
99
+ if (domain) {
100
+ head.domain = void 0;
101
+ domain.enter();
102
+ }
103
+
104
+ try {
105
+ task();
106
+ } catch (e) {
107
+ if (isNodeJS) {
108
+ // In node, uncaught exceptions are considered fatal errors.
109
+ // Re-throw them synchronously to interrupt flushing!
110
+
111
+ // Ensure continuation if the uncaught exception is suppressed
112
+ // listening "uncaughtException" events (as domains does).
113
+ // Continue in next event to avoid tick recursion.
114
+ if (domain) {
115
+ domain.exit();
116
+ }
117
+ setTimeout(flush, 0);
118
+ if (domain) {
119
+ domain.enter();
120
+ }
121
+
122
+ throw e;
123
+ } else {
124
+ // In browsers, uncaught exceptions are not fatal.
125
+ // Re-throw them asynchronously to avoid slow-downs.
126
+ setTimeout(function () {
127
+ throw e;
128
+ }, 0);
129
+ }
130
+ }
131
+
132
+ if (domain) {
133
+ domain.exit();
134
+ }
135
+ }
136
+
137
+ flushing = false;
138
+ }
139
+
140
+ nextTick = function (task) {
141
+ tail = tail.next = {
142
+ task: task,
143
+ domain: isNodeJS && process.domain,
144
+ next: null,
145
+ };
146
+
147
+ if (!flushing) {
148
+ flushing = true;
149
+ requestTick();
150
+ }
151
+ };
152
+
153
+ if (typeof process !== "undefined" && process.nextTick) {
154
+ // Node.js before 0.9. Note that some fake-Node environments, like the
155
+ // Mocha test runner, introduce a `process` global without a `nextTick`.
156
+ isNodeJS = true;
157
+
158
+ requestTick = function () {
159
+ process.nextTick(flush);
160
+ };
161
+ } else if (typeof setImmediate === "function") {
162
+ // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
163
+ if (typeof window !== "undefined") {
164
+ requestTick = setImmediate.bind(window, flush);
165
+ } else {
166
+ requestTick = function () {
167
+ setImmediate(flush);
168
+ };
169
+ }
170
+ } else if (typeof MessageChannel !== "undefined") {
171
+ // modern browsers
172
+ // http://www.nonblocking.io/2011/06/windownexttick.html
173
+ var channel = new MessageChannel();
174
+ // At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create
175
+ // working message ports the first time a page loads.
176
+ channel.port1.onmessage = function () {
177
+ requestTick = requestPortTick;
178
+ channel.port1.onmessage = flush;
179
+ flush();
180
+ };
181
+ var requestPortTick = function () {
182
+ // Opera requires us to provide a message payload, regardless of
183
+ // whether we use it.
184
+ channel.port2.postMessage(0);
185
+ };
186
+ requestTick = function () {
187
+ setTimeout(flush, 0);
188
+ requestPortTick();
189
+ };
190
+ } else {
191
+ // old browsers
192
+ requestTick = function () {
193
+ setTimeout(flush, 0);
194
+ };
195
+ }
196
+
197
+ return nextTick;
198
+ })();
199
+
200
+ // Attempt to make generics safe in the face of downstream
201
+ // modifications.
202
+ // There is no situation where this is necessary.
203
+ // If you need a security guarantee, these primordials need to be
204
+ // deeply frozen anyway, and if you don’t need a security guarantee,
205
+ // this is just plain paranoid.
206
+ // However, this **might** have the nice side-effect of reducing the size of
207
+ // the minified code by reducing x.call() to merely x()
208
+ // See Mark Miller’s explanation of what this does.
209
+ // http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming
210
+ var call = Function.call;
211
+ function uncurryThis(f) {
212
+ return function () {
213
+ return call.apply(f, arguments);
214
+ };
215
+ }
216
+ // This is equivalent, but slower:
217
+ // uncurryThis = Function_bind.bind(Function_bind.call);
218
+ // http://jsperf.com/uncurrythis
219
+
220
+ var array_slice = uncurryThis(Array.prototype.slice);
221
+
222
+ var array_reduce = uncurryThis(
223
+ Array.prototype.reduce ||
224
+ function (callback, basis) {
225
+ var index = 0,
226
+ length = this.length;
227
+ // concerning the initial value, if one is not provided
228
+ if (arguments.length === 1) {
229
+ // seek to the first value in the array, accounting
230
+ // for the possibility that is is a sparse array
231
+ do {
232
+ if (index in this) {
233
+ basis = this[index++];
234
+ break;
235
+ }
236
+ if (++index >= length) {
237
+ throw new TypeError();
238
+ }
239
+ } while (1);
240
+ }
241
+ // reduce
242
+ for (; index < length; index++) {
243
+ // account for the possibility that the array is sparse
244
+ if (index in this) {
245
+ basis = callback(basis, this[index], index);
246
+ }
247
+ }
248
+ return basis;
249
+ }
250
+ );
251
+
252
+ var array_indexOf = uncurryThis(
253
+ Array.prototype.indexOf ||
254
+ function (value) {
255
+ // not a very good shim, but good enough for our one use of it
256
+ for (var i = 0; i < this.length; i++) {
257
+ if (this[i] === value) {
258
+ return i;
259
+ }
260
+ }
261
+ return -1;
262
+ }
263
+ );
264
+
265
+ var array_map = uncurryThis(
266
+ Array.prototype.map ||
267
+ function (callback, thisp) {
268
+ var self = this;
269
+ var collect = [];
270
+ array_reduce(
271
+ self,
272
+ function (undefined, value, index) {
273
+ collect.push(callback.call(thisp, value, index, self));
274
+ },
275
+ void 0
276
+ );
277
+ return collect;
278
+ }
279
+ );
280
+
281
+ var object_create =
282
+ Object.create ||
283
+ function (prototype) {
284
+ function Type() {}
285
+ Type.prototype = prototype;
286
+ return new Type();
287
+ };
288
+
289
+ var object_hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty);
290
+
291
+ var object_keys =
292
+ Object.keys ||
293
+ function (object) {
294
+ var keys = [];
295
+ for (var key in object) {
296
+ if (object_hasOwnProperty(object, key)) {
297
+ keys.push(key);
298
+ }
299
+ }
300
+ return keys;
301
+ };
302
+
303
+ var object_toString = uncurryThis(Object.prototype.toString);
304
+
305
+ function isObject(value) {
306
+ return value === Object(value);
307
+ }
308
+
309
+ // generator related shims
310
+
311
+ // FIXME: Remove this function once ES6 generators are in SpiderMonkey.
312
+ function isStopIteration(exception) {
313
+ return (
314
+ object_toString(exception) === "[object StopIteration]" ||
315
+ exception instanceof QReturnValue
316
+ );
317
+ }
318
+
319
+ // FIXME: Remove this helper and Q.return once ES6 generators are in
320
+ // SpiderMonkey.
321
+ var QReturnValue;
322
+ if (typeof ReturnValue !== "undefined") {
323
+ QReturnValue = ReturnValue;
324
+ } else {
325
+ QReturnValue = function (value) {
326
+ this.value = value;
327
+ };
328
+ }
329
+
330
+ // long stack traces
331
+
332
+ var STACK_JUMP_SEPARATOR = "From previous event:";
333
+
334
+ function makeStackTraceLong(error, promise) {
335
+ // If possible, transform the error stack trace by removing Node and Q
336
+ // cruft, then concatenating with the stack trace of `promise`. See #57.
337
+ if (
338
+ hasStacks &&
339
+ promise.stack &&
340
+ typeof error === "object" &&
341
+ error !== null &&
342
+ error.stack &&
343
+ error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
344
+ ) {
345
+ var stacks = [];
346
+ for (var p = promise; !!p; p = p.source) {
347
+ if (p.stack) {
348
+ stacks.unshift(p.stack);
349
+ }
350
+ }
351
+ stacks.unshift(error.stack);
352
+
353
+ var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
354
+ error.stack = filterStackString(concatedStacks);
355
+ }
356
+ }
357
+
358
+ function filterStackString(stackString) {
359
+ var lines = stackString.split("\n");
360
+ var desiredLines = [];
361
+ for (var i = 0; i < lines.length; ++i) {
362
+ var line = lines[i];
363
+
364
+ if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
365
+ desiredLines.push(line);
366
+ }
367
+ }
368
+ return desiredLines.join("\n");
369
+ }
370
+
371
+ function isNodeFrame(stackLine) {
372
+ return (
373
+ stackLine.indexOf("(module.js:") !== -1 ||
374
+ stackLine.indexOf("(node.js:") !== -1
375
+ );
376
+ }
377
+
378
+ function getFileNameAndLineNumber(stackLine) {
379
+ // Named functions: "at functionName (filename:lineNumber:columnNumber)"
380
+ // In IE10 function name can have spaces ("Anonymous function") O_o
381
+ var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
382
+ if (attempt1) {
383
+ return [attempt1[1], Number(attempt1[2])];
384
+ }
385
+
386
+ // Anonymous functions: "at filename:lineNumber:columnNumber"
387
+ var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
388
+ if (attempt2) {
389
+ return [attempt2[1], Number(attempt2[2])];
390
+ }
391
+
392
+ // Firefox style: "function@filename:lineNumber or @filename:lineNumber"
393
+ var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
394
+ if (attempt3) {
395
+ return [attempt3[1], Number(attempt3[2])];
396
+ }
397
+ }
398
+
399
+ function isInternalFrame(stackLine) {
400
+ var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
401
+
402
+ if (!fileNameAndLineNumber) {
403
+ return false;
404
+ }
405
+
406
+ var fileName = fileNameAndLineNumber[0];
407
+ var lineNumber = fileNameAndLineNumber[1];
408
+
409
+ return (
410
+ fileName === qFileName &&
411
+ lineNumber >= qStartingLine &&
412
+ lineNumber <= qEndingLine
413
+ );
414
+ }
415
+
416
+ // discover own file name and line number range for filtering stack
417
+ // traces
418
+ function captureLine() {
419
+ if (!hasStacks) {
420
+ return;
421
+ }
422
+
423
+ try {
424
+ throw new Error();
425
+ } catch (e) {
426
+ var lines = e.stack.split("\n");
427
+ var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
428
+ var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
429
+ if (!fileNameAndLineNumber) {
430
+ return;
431
+ }
432
+
433
+ qFileName = fileNameAndLineNumber[0];
434
+ return fileNameAndLineNumber[1];
435
+ }
436
+ }
437
+
438
+ function deprecate(callback, name, alternative) {
439
+ return function () {
440
+ if (
441
+ typeof console !== "undefined" &&
442
+ typeof console.warn === "function"
443
+ ) {
444
+ console.warn(
445
+ name + " is deprecated, use " + alternative + " instead.",
446
+ new Error("").stack
447
+ );
448
+ }
449
+ return callback.apply(callback, arguments);
450
+ };
451
+ }
452
+
453
+ // end of shims
454
+ // beginning of real work
455
+
456
+ /**
457
+ * Constructs a promise for an immediate reference, passes promises through, or
458
+ * coerces promises from different systems.
459
+ * @param value immediate reference or promise
460
+ */
461
+ function Q(value) {
462
+ // If the object is already a Promise, return it directly. This enables
463
+ // the resolve function to both be used to created references from objects,
464
+ // but to tolerably coerce non-promises to promises.
465
+ if (isPromise(value)) {
466
+ return value;
467
+ }
468
+
469
+ // assimilate thenables
470
+ if (isPromiseAlike(value)) {
471
+ return coerce(value);
472
+ } else {
473
+ return fulfill(value);
474
+ }
475
+ }
476
+ Q.resolve = Q;
477
+
478
+ /**
479
+ * Performs a task in a future turn of the event loop.
480
+ * @param {Function} task
481
+ */
482
+ Q.nextTick = nextTick;
483
+
484
+ /**
485
+ * Controls whether or not long stack traces will be on
486
+ */
487
+ Q.longStackSupport = false;
488
+
489
+ /**
490
+ * Constructs a {promise, resolve, reject} object.
491
+ *
492
+ * `resolve` is a callback to invoke with a more resolved value for the
493
+ * promise. To fulfill the promise, invoke `resolve` with any value that is
494
+ * not a thenable. To reject the promise, invoke `resolve` with a rejected
495
+ * thenable, or invoke `reject` with the reason directly. To resolve the
496
+ * promise to another thenable, thus putting it in the same state, invoke
497
+ * `resolve` with that other thenable.
498
+ */
499
+ Q.defer = defer;
500
+ function defer() {
501
+ // if "messages" is an "Array", that indicates that the promise has not yet
502
+ // been resolved. If it is "undefined", it has been resolved. Each
503
+ // element of the messages array is itself an array of complete arguments to
504
+ // forward to the resolved promise. We coerce the resolution value to a
505
+ // promise using the `resolve` function because it handles both fully
506
+ // non-thenable values and other thenables gracefully.
507
+ var messages = [],
508
+ progressListeners = [],
509
+ resolvedPromise;
510
+
511
+ var deferred = object_create(defer.prototype);
512
+ var promise = object_create(Promise.prototype);
513
+
514
+ promise.promiseDispatch = function (resolve, op, operands) {
515
+ var args = array_slice(arguments);
516
+ if (messages) {
517
+ messages.push(args);
518
+ if (op === "when" && operands[1]) {
519
+ // progress operand
520
+ progressListeners.push(operands[1]);
521
+ }
522
+ } else {
523
+ nextTick(function () {
524
+ resolvedPromise.promiseDispatch.apply(resolvedPromise, args);
525
+ });
526
+ }
527
+ };
528
+
529
+ // XXX deprecated
530
+ promise.valueOf = function () {
531
+ if (messages) {
532
+ return promise;
533
+ }
534
+ var nearerValue = nearer(resolvedPromise);
535
+ if (isPromise(nearerValue)) {
536
+ resolvedPromise = nearerValue; // shorten chain
537
+ }
538
+ return nearerValue;
539
+ };
540
+
541
+ promise.inspect = function () {
542
+ if (!resolvedPromise) {
543
+ return { state: "pending" };
544
+ }
545
+ return resolvedPromise.inspect();
546
+ };
547
+
548
+ if (Q.longStackSupport && hasStacks) {
549
+ try {
550
+ throw new Error();
551
+ } catch (e) {
552
+ // NOTE: don't try to use `Error.captureStackTrace` or transfer the
553
+ // accessor around; that causes memory leaks as per GH-111. Just
554
+ // reify the stack trace as a string ASAP.
555
+ //
556
+ // At the same time, cut off the first line; it's always just
557
+ // "[object Promise]\n", as per the `toString`.
558
+ promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
559
+ }
560
+ }
561
+
562
+ // NOTE: we do the checks for `resolvedPromise` in each method, instead of
563
+ // consolidating them into `become`, since otherwise we'd create new
564
+ // promises with the lines `become(whatever(value))`. See e.g. GH-252.
565
+
566
+ function become(newPromise) {
567
+ resolvedPromise = newPromise;
568
+ promise.source = newPromise;
569
+
570
+ array_reduce(
571
+ messages,
572
+ function (undefined, message) {
573
+ nextTick(function () {
574
+ newPromise.promiseDispatch.apply(newPromise, message);
575
+ });
576
+ },
577
+ void 0
578
+ );
579
+
580
+ messages = void 0;
581
+ progressListeners = void 0;
582
+ }
583
+
584
+ deferred.promise = promise;
585
+ deferred.resolve = function (value) {
586
+ if (resolvedPromise) {
587
+ return;
588
+ }
589
+
590
+ become(Q(value));
591
+ };
592
+
593
+ deferred.fulfill = function (value) {
594
+ if (resolvedPromise) {
595
+ return;
596
+ }
597
+
598
+ become(fulfill(value));
599
+ };
600
+ deferred.reject = function (reason) {
601
+ if (resolvedPromise) {
602
+ return;
603
+ }
604
+
605
+ become(reject(reason));
606
+ };
607
+ deferred.notify = function (progress) {
608
+ if (resolvedPromise) {
609
+ return;
610
+ }
611
+
612
+ array_reduce(
613
+ progressListeners,
614
+ function (undefined, progressListener) {
615
+ nextTick(function () {
616
+ progressListener(progress);
617
+ });
618
+ },
619
+ void 0
620
+ );
621
+ };
622
+
623
+ return deferred;
624
+ }
625
+
626
+ /**
627
+ * Creates a Node-style callback that will resolve or reject the deferred
628
+ * promise.
629
+ * @returns a nodeback
630
+ */
631
+ defer.prototype.makeNodeResolver = function () {
632
+ var self = this;
633
+ return function (error, value) {
634
+ if (error) {
635
+ self.reject(error);
636
+ } else if (arguments.length > 2) {
637
+ self.resolve(array_slice(arguments, 1));
638
+ } else {
639
+ self.resolve(value);
640
+ }
641
+ };
642
+ };
643
+
644
+ /**
645
+ * @param resolver {Function} a function that returns nothing and accepts
646
+ * the resolve, reject, and notify functions for a deferred.
647
+ * @returns a promise that may be resolved with the given resolve and reject
648
+ * functions, or rejected by a thrown exception in resolver
649
+ */
650
+ Q.Promise = promise; // ES6
651
+ Q.promise = promise;
652
+ function promise(resolver) {
653
+ if (typeof resolver !== "function") {
654
+ throw new TypeError("resolver must be a function.");
655
+ }
656
+ var deferred = defer();
657
+ try {
658
+ resolver(deferred.resolve, deferred.reject, deferred.notify);
659
+ } catch (reason) {
660
+ deferred.reject(reason);
661
+ }
662
+ return deferred.promise;
663
+ }
664
+
665
+ promise.race = race; // ES6
666
+ promise.all = all; // ES6
667
+ promise.reject = reject; // ES6
668
+ promise.resolve = Q; // ES6
669
+
670
+ // XXX experimental. This method is a way to denote that a local value is
671
+ // serializable and should be immediately dispatched to a remote upon request,
672
+ // instead of passing a reference.
673
+ Q.passByCopy = function (object) {
674
+ //freeze(object);
675
+ //passByCopies.set(object, true);
676
+ return object;
677
+ };
678
+
679
+ Promise.prototype.passByCopy = function () {
680
+ //freeze(object);
681
+ //passByCopies.set(object, true);
682
+ return this;
683
+ };
684
+
685
+ /**
686
+ * If two promises eventually fulfill to the same value, promises that value,
687
+ * but otherwise rejects.
688
+ * @param x {Any*}
689
+ * @param y {Any*}
690
+ * @returns {Any*} a promise for x and y if they are the same, but a rejection
691
+ * otherwise.
692
+ *
693
+ */
694
+ Q.join = function (x, y) {
695
+ return Q(x).join(y);
696
+ };
697
+
698
+ Promise.prototype.join = function (that) {
699
+ return Q([this, that]).spread(function (x, y) {
700
+ if (x === y) {
701
+ // TODO: "===" should be Object.is or equiv
702
+ return x;
703
+ } else {
704
+ throw new Error("Can't join: not the same: " + x + " " + y);
705
+ }
706
+ });
707
+ };
708
+
709
+ /**
710
+ * Returns a promise for the first of an array of promises to become fulfilled.
711
+ * @param answers {Array[Any*]} promises to race
712
+ * @returns {Any*} the first promise to be fulfilled
713
+ */
714
+ Q.race = race;
715
+ function race(answerPs) {
716
+ return promise(function (resolve, reject) {
717
+ // Switch to this once we can assume at least ES5
718
+ // answerPs.forEach(function(answerP) {
719
+ // Q(answerP).then(resolve, reject);
720
+ // });
721
+ // Use this in the meantime
722
+ for (var i = 0, len = answerPs.length; i < len; i++) {
723
+ Q(answerPs[i]).then(resolve, reject);
724
+ }
725
+ });
726
+ }
727
+
728
+ Promise.prototype.race = function () {
729
+ return this.then(Q.race);
730
+ };
731
+
732
+ /**
733
+ * Constructs a Promise with a promise descriptor object and optional fallback
734
+ * function. The descriptor contains methods like when(rejected), get(name),
735
+ * set(name, value), post(name, args), and delete(name), which all
736
+ * return either a value, a promise for a value, or a rejection. The fallback
737
+ * accepts the operation name, a resolver, and any further arguments that would
738
+ * have been forwarded to the appropriate method above had a method been
739
+ * provided with the proper name. The API makes no guarantees about the nature
740
+ * of the returned object, apart from that it is usable whereever promises are
741
+ * bought and sold.
742
+ */
743
+ Q.makePromise = Promise;
744
+ function Promise(descriptor, fallback, inspect) {
745
+ if (fallback === void 0) {
746
+ fallback = function (op) {
747
+ return reject(new Error("Promise does not support operation: " + op));
748
+ };
749
+ }
750
+ if (inspect === void 0) {
751
+ inspect = function () {
752
+ return { state: "unknown" };
753
+ };
754
+ }
755
+
756
+ var promise = object_create(Promise.prototype);
757
+
758
+ promise.promiseDispatch = function (resolve, op, args) {
759
+ var result;
760
+ try {
761
+ if (descriptor[op]) {
762
+ result = descriptor[op].apply(promise, args);
763
+ } else {
764
+ result = fallback.call(promise, op, args);
765
+ }
766
+ } catch (exception) {
767
+ result = reject(exception);
768
+ }
769
+ if (resolve) {
770
+ resolve(result);
771
+ }
772
+ };
773
+
774
+ promise.inspect = inspect;
775
+
776
+ // XXX deprecated `valueOf` and `exception` support
777
+ if (inspect) {
778
+ var inspected = inspect();
779
+ if (inspected.state === "rejected") {
780
+ promise.exception = inspected.reason;
781
+ }
782
+
783
+ promise.valueOf = function () {
784
+ var inspected = inspect();
785
+ if (inspected.state === "pending" || inspected.state === "rejected") {
786
+ return promise;
787
+ }
788
+ return inspected.value;
789
+ };
790
+ }
791
+
792
+ return promise;
793
+ }
794
+
795
+ Promise.prototype.toString = function () {
796
+ return "[object Promise]";
797
+ };
798
+
799
+ Promise.prototype.then = function (fulfilled, rejected, progressed) {
800
+ var self = this;
801
+ var deferred = defer();
802
+ var done = false; // ensure the untrusted promise makes at most a
803
+ // single call to one of the callbacks
804
+
805
+ function _fulfilled(value) {
806
+ try {
807
+ return typeof fulfilled === "function" ? fulfilled(value) : value;
808
+ } catch (exception) {
809
+ return reject(exception);
810
+ }
811
+ }
812
+
813
+ function _rejected(exception) {
814
+ if (typeof rejected === "function") {
815
+ makeStackTraceLong(exception, self);
816
+ try {
817
+ return rejected(exception);
818
+ } catch (newException) {
819
+ return reject(newException);
820
+ }
821
+ }
822
+ return reject(exception);
823
+ }
824
+
825
+ function _progressed(value) {
826
+ return typeof progressed === "function" ? progressed(value) : value;
827
+ }
828
+
829
+ nextTick(function () {
830
+ self.promiseDispatch(
831
+ function (value) {
832
+ if (done) {
833
+ return;
834
+ }
835
+ done = true;
836
+
837
+ deferred.resolve(_fulfilled(value));
838
+ },
839
+ "when",
840
+ [
841
+ function (exception) {
842
+ if (done) {
843
+ return;
844
+ }
845
+ done = true;
846
+
847
+ deferred.resolve(_rejected(exception));
848
+ },
849
+ ]
850
+ );
851
+ });
852
+
853
+ // Progress propagator need to be attached in the current tick.
854
+ self.promiseDispatch(void 0, "when", [
855
+ void 0,
856
+ function (value) {
857
+ var newValue;
858
+ var threw = false;
859
+ try {
860
+ newValue = _progressed(value);
861
+ } catch (e) {
862
+ threw = true;
863
+ if (Q.onerror) {
864
+ Q.onerror(e);
865
+ } else {
866
+ throw e;
867
+ }
868
+ }
869
+
870
+ if (!threw) {
871
+ deferred.notify(newValue);
872
+ }
873
+ },
874
+ ]);
875
+
876
+ return deferred.promise;
877
+ };
878
+
879
+ /**
880
+ * Registers an observer on a promise.
881
+ *
882
+ * Guarantees:
883
+ *
884
+ * 1. that fulfilled and rejected will be called only once.
885
+ * 2. that either the fulfilled callback or the rejected callback will be
886
+ * called, but not both.
887
+ * 3. that fulfilled and rejected will not be called in this turn.
888
+ *
889
+ * @param value promise or immediate reference to observe
890
+ * @param fulfilled function to be called with the fulfilled value
891
+ * @param rejected function to be called with the rejection exception
892
+ * @param progressed function to be called on any progress notifications
893
+ * @return promise for the return value from the invoked callback
894
+ */
895
+ Q.when = when;
896
+ function when(value, fulfilled, rejected, progressed) {
897
+ return Q(value).then(fulfilled, rejected, progressed);
898
+ }
899
+
900
+ Promise.prototype.thenResolve = function (value) {
901
+ return this.then(function () {
902
+ return value;
903
+ });
904
+ };
905
+
906
+ Q.thenResolve = function (promise, value) {
907
+ return Q(promise).thenResolve(value);
908
+ };
909
+
910
+ Promise.prototype.thenReject = function (reason) {
911
+ return this.then(function () {
912
+ throw reason;
913
+ });
914
+ };
915
+
916
+ Q.thenReject = function (promise, reason) {
917
+ return Q(promise).thenReject(reason);
918
+ };
919
+
920
+ /**
921
+ * If an object is not a promise, it is as "near" as possible.
922
+ * If a promise is rejected, it is as "near" as possible too.
923
+ * If it’s a fulfilled promise, the fulfillment value is nearer.
924
+ * If it’s a deferred promise and the deferred has been resolved, the
925
+ * resolution is "nearer".
926
+ * @param object
927
+ * @returns most resolved (nearest) form of the object
928
+ */
929
+
930
+ // XXX should we re-do this?
931
+ Q.nearer = nearer;
932
+ function nearer(value) {
933
+ if (isPromise(value)) {
934
+ var inspected = value.inspect();
935
+ if (inspected.state === "fulfilled") {
936
+ return inspected.value;
937
+ }
938
+ }
939
+ return value;
940
+ }
941
+
942
+ /**
943
+ * @returns whether the given object is a promise.
944
+ * Otherwise it is a fulfilled value.
945
+ */
946
+ Q.isPromise = isPromise;
947
+ function isPromise(object) {
948
+ return (
949
+ isObject(object) &&
950
+ typeof object.promiseDispatch === "function" &&
951
+ typeof object.inspect === "function"
952
+ );
953
+ }
954
+
955
+ Q.isPromiseAlike = isPromiseAlike;
956
+ function isPromiseAlike(object) {
957
+ return isObject(object) && typeof object.then === "function";
958
+ }
959
+
960
+ /**
961
+ * @returns whether the given object is a pending promise, meaning not
962
+ * fulfilled or rejected.
963
+ */
964
+ Q.isPending = isPending;
965
+ function isPending(object) {
966
+ return isPromise(object) && object.inspect().state === "pending";
967
+ }
968
+
969
+ Promise.prototype.isPending = function () {
970
+ return this.inspect().state === "pending";
971
+ };
972
+
973
+ /**
974
+ * @returns whether the given object is a value or fulfilled
975
+ * promise.
976
+ */
977
+ Q.isFulfilled = isFulfilled;
978
+ function isFulfilled(object) {
979
+ return !isPromise(object) || object.inspect().state === "fulfilled";
980
+ }
981
+
982
+ Promise.prototype.isFulfilled = function () {
983
+ return this.inspect().state === "fulfilled";
984
+ };
985
+
986
+ /**
987
+ * @returns whether the given object is a rejected promise.
988
+ */
989
+ Q.isRejected = isRejected;
990
+ function isRejected(object) {
991
+ return isPromise(object) && object.inspect().state === "rejected";
992
+ }
993
+
994
+ Promise.prototype.isRejected = function () {
995
+ return this.inspect().state === "rejected";
996
+ };
997
+
998
+ //// BEGIN UNHANDLED REJECTION TRACKING
999
+
1000
+ // This promise library consumes exceptions thrown in handlers so they can be
1001
+ // handled by a subsequent promise. The exceptions get added to this array when
1002
+ // they are created, and removed when they are handled. Note that in ES6 or
1003
+ // shimmed environments, this would naturally be a `Set`.
1004
+ var unhandledReasons = [];
1005
+ var unhandledRejections = [];
1006
+ var trackUnhandledRejections = true;
1007
+
1008
+ function resetUnhandledRejections() {
1009
+ unhandledReasons.length = 0;
1010
+ unhandledRejections.length = 0;
1011
+
1012
+ if (!trackUnhandledRejections) {
1013
+ trackUnhandledRejections = true;
1014
+ }
1015
+ }
1016
+
1017
+ function trackRejection(promise, reason) {
1018
+ if (!trackUnhandledRejections) {
1019
+ return;
1020
+ }
1021
+
1022
+ unhandledRejections.push(promise);
1023
+ if (reason && typeof reason.stack !== "undefined") {
1024
+ unhandledReasons.push(reason.stack);
1025
+ } else {
1026
+ unhandledReasons.push("(no stack) " + reason);
1027
+ }
1028
+ }
1029
+
1030
+ function untrackRejection(promise) {
1031
+ if (!trackUnhandledRejections) {
1032
+ return;
1033
+ }
1034
+
1035
+ var at = array_indexOf(unhandledRejections, promise);
1036
+ if (at !== -1) {
1037
+ unhandledRejections.splice(at, 1);
1038
+ unhandledReasons.splice(at, 1);
1039
+ }
1040
+ }
1041
+
1042
+ Q.resetUnhandledRejections = resetUnhandledRejections;
1043
+
1044
+ Q.getUnhandledReasons = function () {
1045
+ // Make a copy so that consumers can't interfere with our internal state.
1046
+ return unhandledReasons.slice();
1047
+ };
1048
+
1049
+ Q.stopUnhandledRejectionTracking = function () {
1050
+ resetUnhandledRejections();
1051
+ trackUnhandledRejections = false;
1052
+ };
1053
+
1054
+ resetUnhandledRejections();
1055
+
1056
+ //// END UNHANDLED REJECTION TRACKING
1057
+
1058
+ /**
1059
+ * Constructs a rejected promise.
1060
+ * @param reason value describing the failure
1061
+ */
1062
+ Q.reject = reject;
1063
+ function reject(reason) {
1064
+ var rejection = Promise(
1065
+ {
1066
+ when: function (rejected) {
1067
+ // note that the error has been handled
1068
+ if (rejected) {
1069
+ untrackRejection(this);
1070
+ }
1071
+ return rejected ? rejected(reason) : this;
1072
+ },
1073
+ },
1074
+ function fallback() {
1075
+ return this;
1076
+ },
1077
+ function inspect() {
1078
+ return { state: "rejected", reason: reason };
1079
+ }
1080
+ );
1081
+
1082
+ // Note that the reason has not been handled.
1083
+ trackRejection(rejection, reason);
1084
+
1085
+ return rejection;
1086
+ }
1087
+
1088
+ /**
1089
+ * Constructs a fulfilled promise for an immediate reference.
1090
+ * @param value immediate reference
1091
+ */
1092
+ Q.fulfill = fulfill;
1093
+ function fulfill(value) {
1094
+ return Promise(
1095
+ {
1096
+ when: function () {
1097
+ return value;
1098
+ },
1099
+ get: function (name) {
1100
+ return value[name];
1101
+ },
1102
+ set: function (name, rhs) {
1103
+ value[name] = rhs;
1104
+ },
1105
+ delete: function (name) {
1106
+ delete value[name];
1107
+ },
1108
+ post: function (name, args) {
1109
+ // Mark Miller proposes that post with no name should apply a
1110
+ // promised function.
1111
+ if (name === null || name === void 0) {
1112
+ return value.apply(void 0, args);
1113
+ } else {
1114
+ return value[name].apply(value, args);
1115
+ }
1116
+ },
1117
+ apply: function (thisp, args) {
1118
+ return value.apply(thisp, args);
1119
+ },
1120
+ keys: function () {
1121
+ return object_keys(value);
1122
+ },
1123
+ },
1124
+ void 0,
1125
+ function inspect() {
1126
+ return { state: "fulfilled", value: value };
1127
+ }
1128
+ );
1129
+ }
1130
+
1131
+ /**
1132
+ * Converts thenables to Q promises.
1133
+ * @param promise thenable promise
1134
+ * @returns a Q promise
1135
+ */
1136
+ function coerce(promise) {
1137
+ var deferred = defer();
1138
+ nextTick(function () {
1139
+ try {
1140
+ promise.then(deferred.resolve, deferred.reject, deferred.notify);
1141
+ } catch (exception) {
1142
+ deferred.reject(exception);
1143
+ }
1144
+ });
1145
+ return deferred.promise;
1146
+ }
1147
+
1148
+ /**
1149
+ * Annotates an object such that it will never be
1150
+ * transferred away from this process over any promise
1151
+ * communication channel.
1152
+ * @param object
1153
+ * @returns promise a wrapping of that object that
1154
+ * additionally responds to the "isDef" message
1155
+ * without a rejection.
1156
+ */
1157
+ Q.master = master;
1158
+ function master(object) {
1159
+ return Promise(
1160
+ {
1161
+ isDef: function () {},
1162
+ },
1163
+ function fallback(op, args) {
1164
+ return dispatch(object, op, args);
1165
+ },
1166
+ function () {
1167
+ return Q(object).inspect();
1168
+ }
1169
+ );
1170
+ }
1171
+
1172
+ /**
1173
+ * Spreads the values of a promised array of arguments into the
1174
+ * fulfillment callback.
1175
+ * @param fulfilled callback that receives variadic arguments from the
1176
+ * promised array
1177
+ * @param rejected callback that receives the exception if the promise
1178
+ * is rejected.
1179
+ * @returns a promise for the return value or thrown exception of
1180
+ * either callback.
1181
+ */
1182
+ Q.spread = spread;
1183
+ function spread(value, fulfilled, rejected) {
1184
+ return Q(value).spread(fulfilled, rejected);
1185
+ }
1186
+
1187
+ Promise.prototype.spread = function (fulfilled, rejected) {
1188
+ return this.all().then(function (array) {
1189
+ return fulfilled.apply(void 0, array);
1190
+ }, rejected);
1191
+ };
1192
+
1193
+ /**
1194
+ * The async function is a decorator for generator functions, turning
1195
+ * them into asynchronous generators. Although generators are only part
1196
+ * of the newest ECMAScript 6 drafts, this code does not cause syntax
1197
+ * errors in older engines. This code should continue to work and will
1198
+ * in fact improve over time as the language improves.
1199
+ *
1200
+ * ES6 generators are currently part of V8 version 3.19 with the
1201
+ * --harmony-generators runtime flag enabled. SpiderMonkey has had them
1202
+ * for longer, but under an older Python-inspired form. This function
1203
+ * works on both kinds of generators.
1204
+ *
1205
+ * Decorates a generator function such that:
1206
+ * - it may yield promises
1207
+ * - execution will continue when that promise is fulfilled
1208
+ * - the value of the yield expression will be the fulfilled value
1209
+ * - it returns a promise for the return value (when the generator
1210
+ * stops iterating)
1211
+ * - the decorated function returns a promise for the return value
1212
+ * of the generator or the first rejected promise among those
1213
+ * yielded.
1214
+ * - if an error is thrown in the generator, it propagates through
1215
+ * every following yield until it is caught, or until it escapes
1216
+ * the generator function altogether, and is translated into a
1217
+ * rejection for the promise returned by the decorated generator.
1218
+ */
1219
+ Q.async = async;
1220
+ function async(makeGenerator) {
1221
+ return function () {
1222
+ // when verb is "send", arg is a value
1223
+ // when verb is "throw", arg is an exception
1224
+ function continuer(verb, arg) {
1225
+ var result;
1226
+
1227
+ // Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only
1228
+ // engine that has a deployed base of browsers that support generators.
1229
+ // However, SM's generators use the Python-inspired semantics of
1230
+ // outdated ES6 drafts. We would like to support ES6, but we'd also
1231
+ // like to make it possible to use generators in deployed browsers, so
1232
+ // we also support Python-style generators. At some point we can remove
1233
+ // this block.
1234
+
1235
+ if (typeof StopIteration === "undefined") {
1236
+ // ES6 Generators
1237
+ try {
1238
+ result = generator[verb](arg);
1239
+ } catch (exception) {
1240
+ return reject(exception);
1241
+ }
1242
+ if (result.done) {
1243
+ return result.value;
1244
+ } else {
1245
+ return when(result.value, callback, errback);
1246
+ }
1247
+ } else {
1248
+ // SpiderMonkey Generators
1249
+ // FIXME: Remove this case when SM does ES6 generators.
1250
+ try {
1251
+ result = generator[verb](arg);
1252
+ } catch (exception) {
1253
+ if (isStopIteration(exception)) {
1254
+ return exception.value;
1255
+ } else {
1256
+ return reject(exception);
1257
+ }
1258
+ }
1259
+ return when(result, callback, errback);
1260
+ }
1261
+ }
1262
+ var generator = makeGenerator.apply(this, arguments);
1263
+ var callback = continuer.bind(continuer, "next");
1264
+ var errback = continuer.bind(continuer, "throw");
1265
+ return callback();
1266
+ };
1267
+ }
1268
+
1269
+ /**
1270
+ * The spawn function is a small wrapper around async that immediately
1271
+ * calls the generator and also ends the promise chain, so that any
1272
+ * unhandled errors are thrown instead of forwarded to the error
1273
+ * handler. This is useful because it's extremely common to run
1274
+ * generators at the top-level to work with libraries.
1275
+ */
1276
+ Q.spawn = spawn;
1277
+ function spawn(makeGenerator) {
1278
+ Q.done(Q.async(makeGenerator)());
1279
+ }
1280
+
1281
+ // FIXME: Remove this interface once ES6 generators are in SpiderMonkey.
1282
+ /**
1283
+ * Throws a ReturnValue exception to stop an asynchronous generator.
1284
+ *
1285
+ * This interface is a stop-gap measure to support generator return
1286
+ * values in older Firefox/SpiderMonkey. In browsers that support ES6
1287
+ * generators like Chromium 29, just use "return" in your generator
1288
+ * functions.
1289
+ *
1290
+ * @param value the return value for the surrounding generator
1291
+ * @throws ReturnValue exception with the value.
1292
+ * @example
1293
+ * // ES6 style
1294
+ * Q.async(function* () {
1295
+ * var foo = yield getFooPromise();
1296
+ * var bar = yield getBarPromise();
1297
+ * return foo + bar;
1298
+ * })
1299
+ * // Older SpiderMonkey style
1300
+ * Q.async(function () {
1301
+ * var foo = yield getFooPromise();
1302
+ * var bar = yield getBarPromise();
1303
+ * Q.return(foo + bar);
1304
+ * })
1305
+ */
1306
+ Q["return"] = _return;
1307
+ function _return(value) {
1308
+ throw new QReturnValue(value);
1309
+ }
1310
+
1311
+ /**
1312
+ * The promised function decorator ensures that any promise arguments
1313
+ * are settled and passed as values (`this` is also settled and passed
1314
+ * as a value). It will also ensure that the result of a function is
1315
+ * always a promise.
1316
+ *
1317
+ * @example
1318
+ * var add = Q.promised(function (a, b) {
1319
+ * return a + b;
1320
+ * });
1321
+ * add(Q(a), Q(B));
1322
+ *
1323
+ * @param {function} callback The function to decorate
1324
+ * @returns {function} a function that has been decorated.
1325
+ */
1326
+ Q.promised = promised;
1327
+ function promised(callback) {
1328
+ return function () {
1329
+ return spread([this, all(arguments)], function (self, args) {
1330
+ return callback.apply(self, args);
1331
+ });
1332
+ };
1333
+ }
1334
+
1335
+ /**
1336
+ * sends a message to a value in a future turn
1337
+ * @param object* the recipient
1338
+ * @param op the name of the message operation, e.g., "when",
1339
+ * @param args further arguments to be forwarded to the operation
1340
+ * @returns result {Promise} a promise for the result of the operation
1341
+ */
1342
+ Q.dispatch = dispatch;
1343
+ function dispatch(object, op, args) {
1344
+ return Q(object).dispatch(op, args);
1345
+ }
1346
+
1347
+ Promise.prototype.dispatch = function (op, args) {
1348
+ var self = this;
1349
+ var deferred = defer();
1350
+ nextTick(function () {
1351
+ self.promiseDispatch(deferred.resolve, op, args);
1352
+ });
1353
+ return deferred.promise;
1354
+ };
1355
+
1356
+ /**
1357
+ * Gets the value of a property in a future turn.
1358
+ * @param object promise or immediate reference for target object
1359
+ * @param name name of property to get
1360
+ * @return promise for the property value
1361
+ */
1362
+ Q.get = function (object, key) {
1363
+ return Q(object).dispatch("get", [key]);
1364
+ };
1365
+
1366
+ Promise.prototype.get = function (key) {
1367
+ return this.dispatch("get", [key]);
1368
+ };
1369
+
1370
+ /**
1371
+ * Sets the value of a property in a future turn.
1372
+ * @param object promise or immediate reference for object object
1373
+ * @param name name of property to set
1374
+ * @param value new value of property
1375
+ * @return promise for the return value
1376
+ */
1377
+ Q.set = function (object, key, value) {
1378
+ return Q(object).dispatch("set", [key, value]);
1379
+ };
1380
+
1381
+ Promise.prototype.set = function (key, value) {
1382
+ return this.dispatch("set", [key, value]);
1383
+ };
1384
+
1385
+ /**
1386
+ * Deletes a property in a future turn.
1387
+ * @param object promise or immediate reference for target object
1388
+ * @param name name of property to delete
1389
+ * @return promise for the return value
1390
+ */
1391
+ Q.del = // XXX legacy
1392
+ Q["delete"] = function (object, key) {
1393
+ return Q(object).dispatch("delete", [key]);
1394
+ };
1395
+
1396
+ Promise.prototype.del = // XXX legacy
1397
+ Promise.prototype["delete"] = function (key) {
1398
+ return this.dispatch("delete", [key]);
1399
+ };
1400
+
1401
+ /**
1402
+ * Invokes a method in a future turn.
1403
+ * @param object promise or immediate reference for target object
1404
+ * @param name name of method to invoke
1405
+ * @param value a value to post, typically an array of
1406
+ * invocation arguments for promises that
1407
+ * are ultimately backed with `resolve` values,
1408
+ * as opposed to those backed with URLs
1409
+ * wherein the posted value can be any
1410
+ * JSON serializable object.
1411
+ * @return promise for the return value
1412
+ */
1413
+ // bound locally because it is used by other methods
1414
+ Q.mapply = // XXX As proposed by "Redsandro"
1415
+ Q.post = function (object, name, args) {
1416
+ return Q(object).dispatch("post", [name, args]);
1417
+ };
1418
+
1419
+ Promise.prototype.mapply = // XXX As proposed by "Redsandro"
1420
+ Promise.prototype.post = function (name, args) {
1421
+ return this.dispatch("post", [name, args]);
1422
+ };
1423
+
1424
+ /**
1425
+ * Invokes a method in a future turn.
1426
+ * @param object promise or immediate reference for target object
1427
+ * @param name name of method to invoke
1428
+ * @param ...args array of invocation arguments
1429
+ * @return promise for the return value
1430
+ */
1431
+ Q.send = // XXX Mark Miller's proposed parlance
1432
+ Q.mcall = // XXX As proposed by "Redsandro"
1433
+ Q.invoke =
1434
+ function (object, name /*...args*/) {
1435
+ return Q(object).dispatch("post", [name, array_slice(arguments, 2)]);
1436
+ };
1437
+
1438
+ Promise.prototype.send = // XXX Mark Miller's proposed parlance
1439
+ Promise.prototype.mcall = // XXX As proposed by "Redsandro"
1440
+ Promise.prototype.invoke =
1441
+ function (name /*...args*/) {
1442
+ return this.dispatch("post", [name, array_slice(arguments, 1)]);
1443
+ };
1444
+
1445
+ /**
1446
+ * Applies the promised function in a future turn.
1447
+ * @param object promise or immediate reference for target function
1448
+ * @param args array of application arguments
1449
+ */
1450
+ Q.fapply = function (object, args) {
1451
+ return Q(object).dispatch("apply", [void 0, args]);
1452
+ };
1453
+
1454
+ Promise.prototype.fapply = function (args) {
1455
+ return this.dispatch("apply", [void 0, args]);
1456
+ };
1457
+
1458
+ /**
1459
+ * Calls the promised function in a future turn.
1460
+ * @param object promise or immediate reference for target function
1461
+ * @param ...args array of application arguments
1462
+ */
1463
+ Q["try"] = Q.fcall = function (object /* ...args*/) {
1464
+ return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]);
1465
+ };
1466
+
1467
+ Promise.prototype.fcall = function (/*...args*/) {
1468
+ return this.dispatch("apply", [void 0, array_slice(arguments)]);
1469
+ };
1470
+
1471
+ /**
1472
+ * Binds the promised function, transforming return values into a fulfilled
1473
+ * promise and thrown errors into a rejected one.
1474
+ * @param object promise or immediate reference for target function
1475
+ * @param ...args array of application arguments
1476
+ */
1477
+ Q.fbind = function (object /*...args*/) {
1478
+ var promise = Q(object);
1479
+ var args = array_slice(arguments, 1);
1480
+ return function fbound() {
1481
+ return promise.dispatch("apply", [
1482
+ this,
1483
+ args.concat(array_slice(arguments)),
1484
+ ]);
1485
+ };
1486
+ };
1487
+ Promise.prototype.fbind = function (/*...args*/) {
1488
+ var promise = this;
1489
+ var args = array_slice(arguments);
1490
+ return function fbound() {
1491
+ return promise.dispatch("apply", [
1492
+ this,
1493
+ args.concat(array_slice(arguments)),
1494
+ ]);
1495
+ };
1496
+ };
1497
+
1498
+ /**
1499
+ * Requests the names of the owned properties of a promised
1500
+ * object in a future turn.
1501
+ * @param object promise or immediate reference for target object
1502
+ * @return promise for the keys of the eventually settled object
1503
+ */
1504
+ Q.keys = function (object) {
1505
+ return Q(object).dispatch("keys", []);
1506
+ };
1507
+
1508
+ Promise.prototype.keys = function () {
1509
+ return this.dispatch("keys", []);
1510
+ };
1511
+
1512
+ /**
1513
+ * Turns an array of promises into a promise for an array. If any of
1514
+ * the promises gets rejected, the whole array is rejected immediately.
1515
+ * @param {Array*} an array (or promise for an array) of values (or
1516
+ * promises for values)
1517
+ * @returns a promise for an array of the corresponding values
1518
+ */
1519
+ // By Mark Miller
1520
+ // http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled
1521
+ Q.all = all;
1522
+ function all(promises) {
1523
+ return when(promises, function (promises) {
1524
+ var countDown = 0;
1525
+ var deferred = defer();
1526
+ array_reduce(
1527
+ promises,
1528
+ function (undefined, promise, index) {
1529
+ var snapshot;
1530
+ if (
1531
+ isPromise(promise) &&
1532
+ (snapshot = promise.inspect()).state === "fulfilled"
1533
+ ) {
1534
+ promises[index] = snapshot.value;
1535
+ } else {
1536
+ ++countDown;
1537
+ when(
1538
+ promise,
1539
+ function (value) {
1540
+ promises[index] = value;
1541
+ if (--countDown === 0) {
1542
+ deferred.resolve(promises);
1543
+ }
1544
+ },
1545
+ deferred.reject,
1546
+ function (progress) {
1547
+ deferred.notify({ index: index, value: progress });
1548
+ }
1549
+ );
1550
+ }
1551
+ },
1552
+ void 0
1553
+ );
1554
+ if (countDown === 0) {
1555
+ deferred.resolve(promises);
1556
+ }
1557
+ return deferred.promise;
1558
+ });
1559
+ }
1560
+
1561
+ Promise.prototype.all = function () {
1562
+ return all(this);
1563
+ };
1564
+
1565
+ /**
1566
+ * Waits for all promises to be settled, either fulfilled or
1567
+ * rejected. This is distinct from `all` since that would stop
1568
+ * waiting at the first rejection. The promise returned by
1569
+ * `allResolved` will never be rejected.
1570
+ * @param promises a promise for an array (or an array) of promises
1571
+ * (or values)
1572
+ * @return a promise for an array of promises
1573
+ */
1574
+ Q.allResolved = deprecate(allResolved, "allResolved", "allSettled");
1575
+ function allResolved(promises) {
1576
+ return when(promises, function (promises) {
1577
+ promises = array_map(promises, Q);
1578
+ return when(
1579
+ all(
1580
+ array_map(promises, function (promise) {
1581
+ return when(promise, noop, noop);
1582
+ })
1583
+ ),
1584
+ function () {
1585
+ return promises;
1586
+ }
1587
+ );
1588
+ });
1589
+ }
1590
+
1591
+ Promise.prototype.allResolved = function () {
1592
+ return allResolved(this);
1593
+ };
1594
+
1595
+ /**
1596
+ * @see Promise#allSettled
1597
+ */
1598
+ Q.allSettled = allSettled;
1599
+ function allSettled(promises) {
1600
+ return Q(promises).allSettled();
1601
+ }
1602
+
1603
+ /**
1604
+ * Turns an array of promises into a promise for an array of their states (as
1605
+ * returned by `inspect`) when they have all settled.
1606
+ * @param {Array[Any*]} values an array (or promise for an array) of values (or
1607
+ * promises for values)
1608
+ * @returns {Array[State]} an array of states for the respective values.
1609
+ */
1610
+ Promise.prototype.allSettled = function () {
1611
+ return this.then(function (promises) {
1612
+ return all(
1613
+ array_map(promises, function (promise) {
1614
+ promise = Q(promise);
1615
+ function regardless() {
1616
+ return promise.inspect();
1617
+ }
1618
+ return promise.then(regardless, regardless);
1619
+ })
1620
+ );
1621
+ });
1622
+ };
1623
+
1624
+ /**
1625
+ * Captures the failure of a promise, giving an oportunity to recover
1626
+ * with a callback. If the given promise is fulfilled, the returned
1627
+ * promise is fulfilled.
1628
+ * @param {Any*} promise for something
1629
+ * @param {Function} callback to fulfill the returned promise if the
1630
+ * given promise is rejected
1631
+ * @returns a promise for the return value of the callback
1632
+ */
1633
+ Q.fail = // XXX legacy
1634
+ Q["catch"] = function (object, rejected) {
1635
+ return Q(object).then(void 0, rejected);
1636
+ };
1637
+
1638
+ Promise.prototype.fail = // XXX legacy
1639
+ Promise.prototype["catch"] = function (rejected) {
1640
+ return this.then(void 0, rejected);
1641
+ };
1642
+
1643
+ /**
1644
+ * Attaches a listener that can respond to progress notifications from a
1645
+ * promise's originating deferred. This listener receives the exact arguments
1646
+ * passed to ``deferred.notify``.
1647
+ * @param {Any*} promise for something
1648
+ * @param {Function} callback to receive any progress notifications
1649
+ * @returns the given promise, unchanged
1650
+ */
1651
+ Q.progress = progress;
1652
+ function progress(object, progressed) {
1653
+ return Q(object).then(void 0, void 0, progressed);
1654
+ }
1655
+
1656
+ Promise.prototype.progress = function (progressed) {
1657
+ return this.then(void 0, void 0, progressed);
1658
+ };
1659
+
1660
+ /**
1661
+ * Provides an opportunity to observe the settling of a promise,
1662
+ * regardless of whether the promise is fulfilled or rejected. Forwards
1663
+ * the resolution to the returned promise when the callback is done.
1664
+ * The callback can return a promise to defer completion.
1665
+ * @param {Any*} promise
1666
+ * @param {Function} callback to observe the resolution of the given
1667
+ * promise, takes no arguments.
1668
+ * @returns a promise for the resolution of the given promise when
1669
+ * ``fin`` is done.
1670
+ */
1671
+ Q.fin = // XXX legacy
1672
+ Q["finally"] = function (object, callback) {
1673
+ return Q(object)["finally"](callback);
1674
+ };
1675
+
1676
+ Promise.prototype.fin = // XXX legacy
1677
+ Promise.prototype["finally"] = function (callback) {
1678
+ callback = Q(callback);
1679
+ return this.then(
1680
+ function (value) {
1681
+ return callback.fcall().then(function () {
1682
+ return value;
1683
+ });
1684
+ },
1685
+ function (reason) {
1686
+ // TODO attempt to recycle the rejection with "this".
1687
+ return callback.fcall().then(function () {
1688
+ throw reason;
1689
+ });
1690
+ }
1691
+ );
1692
+ };
1693
+
1694
+ /**
1695
+ * Terminates a chain of promises, forcing rejections to be
1696
+ * thrown as exceptions.
1697
+ * @param {Any*} promise at the end of a chain of promises
1698
+ * @returns nothing
1699
+ */
1700
+ Q.done = function (object, fulfilled, rejected, progress) {
1701
+ return Q(object).done(fulfilled, rejected, progress);
1702
+ };
1703
+
1704
+ Promise.prototype.done = function (fulfilled, rejected, progress) {
1705
+ var onUnhandledError = function (error) {
1706
+ // forward to a future turn so that ``when``
1707
+ // does not catch it and turn it into a rejection.
1708
+ nextTick(function () {
1709
+ makeStackTraceLong(error, promise);
1710
+ if (Q.onerror) {
1711
+ Q.onerror(error);
1712
+ } else {
1713
+ throw error;
1714
+ }
1715
+ });
1716
+ };
1717
+
1718
+ // Avoid unnecessary `nextTick`ing via an unnecessary `when`.
1719
+ var promise =
1720
+ fulfilled || rejected || progress
1721
+ ? this.then(fulfilled, rejected, progress)
1722
+ : this;
1723
+
1724
+ if (typeof process === "object" && process && process.domain) {
1725
+ onUnhandledError = process.domain.bind(onUnhandledError);
1726
+ }
1727
+
1728
+ promise.then(void 0, onUnhandledError);
1729
+ };
1730
+
1731
+ /**
1732
+ * Causes a promise to be rejected if it does not get fulfilled before
1733
+ * some milliseconds time out.
1734
+ * @param {Any*} promise
1735
+ * @param {Number} milliseconds timeout
1736
+ * @param {String} custom error message (optional)
1737
+ * @returns a promise for the resolution of the given promise if it is
1738
+ * fulfilled before the timeout, otherwise rejected.
1739
+ */
1740
+ Q.timeout = function (object, ms, message) {
1741
+ return Q(object).timeout(ms, message);
1742
+ };
1743
+
1744
+ Promise.prototype.timeout = function (ms, message) {
1745
+ var deferred = defer();
1746
+ var timeoutId = setTimeout(function () {
1747
+ deferred.reject(new Error(message || "Timed out after " + ms + " ms"));
1748
+ }, ms);
1749
+
1750
+ this.then(
1751
+ function (value) {
1752
+ clearTimeout(timeoutId);
1753
+ deferred.resolve(value);
1754
+ },
1755
+ function (exception) {
1756
+ clearTimeout(timeoutId);
1757
+ deferred.reject(exception);
1758
+ },
1759
+ deferred.notify
1760
+ );
1761
+
1762
+ return deferred.promise;
1763
+ };
1764
+
1765
+ /**
1766
+ * Returns a promise for the given value (or promised value), some
1767
+ * milliseconds after it resolved. Passes rejections immediately.
1768
+ * @param {Any*} promise
1769
+ * @param {Number} milliseconds
1770
+ * @returns a promise for the resolution of the given promise after milliseconds
1771
+ * time has elapsed since the resolution of the given promise.
1772
+ * If the given promise rejects, that is passed immediately.
1773
+ */
1774
+ Q.delay = function (object, timeout) {
1775
+ if (timeout === void 0) {
1776
+ timeout = object;
1777
+ object = void 0;
1778
+ }
1779
+ return Q(object).delay(timeout);
1780
+ };
1781
+
1782
+ Promise.prototype.delay = function (timeout) {
1783
+ return this.then(function (value) {
1784
+ var deferred = defer();
1785
+ setTimeout(function () {
1786
+ deferred.resolve(value);
1787
+ }, timeout);
1788
+ return deferred.promise;
1789
+ });
1790
+ };
1791
+
1792
+ /**
1793
+ * Passes a continuation to a Node function, which is called with the given
1794
+ * arguments provided as an array, and returns a promise.
1795
+ *
1796
+ * Q.nfapply(FS.readFile, [__filename])
1797
+ * .then(function (content) {
1798
+ * })
1799
+ *
1800
+ */
1801
+ Q.nfapply = function (callback, args) {
1802
+ return Q(callback).nfapply(args);
1803
+ };
1804
+
1805
+ Promise.prototype.nfapply = function (args) {
1806
+ var deferred = defer();
1807
+ var nodeArgs = array_slice(args);
1808
+ nodeArgs.push(deferred.makeNodeResolver());
1809
+ this.fapply(nodeArgs).fail(deferred.reject);
1810
+ return deferred.promise;
1811
+ };
1812
+
1813
+ /**
1814
+ * Passes a continuation to a Node function, which is called with the given
1815
+ * arguments provided individually, and returns a promise.
1816
+ * @example
1817
+ * Q.nfcall(FS.readFile, __filename)
1818
+ * .then(function (content) {
1819
+ * })
1820
+ *
1821
+ */
1822
+ Q.nfcall = function (callback /*...args*/) {
1823
+ var args = array_slice(arguments, 1);
1824
+ return Q(callback).nfapply(args);
1825
+ };
1826
+
1827
+ Promise.prototype.nfcall = function (/*...args*/) {
1828
+ var nodeArgs = array_slice(arguments);
1829
+ var deferred = defer();
1830
+ nodeArgs.push(deferred.makeNodeResolver());
1831
+ this.fapply(nodeArgs).fail(deferred.reject);
1832
+ return deferred.promise;
1833
+ };
1834
+
1835
+ /**
1836
+ * Wraps a NodeJS continuation passing function and returns an equivalent
1837
+ * version that returns a promise.
1838
+ * @example
1839
+ * Q.nfbind(FS.readFile, __filename)("utf-8")
1840
+ * .then(console.log)
1841
+ * .done()
1842
+ */
1843
+ Q.nfbind = Q.denodeify = function (callback /*...args*/) {
1844
+ var baseArgs = array_slice(arguments, 1);
1845
+ return function () {
1846
+ var nodeArgs = baseArgs.concat(array_slice(arguments));
1847
+ var deferred = defer();
1848
+ nodeArgs.push(deferred.makeNodeResolver());
1849
+ Q(callback).fapply(nodeArgs).fail(deferred.reject);
1850
+ return deferred.promise;
1851
+ };
1852
+ };
1853
+
1854
+ Promise.prototype.nfbind = Promise.prototype.denodeify =
1855
+ function (/*...args*/) {
1856
+ var args = array_slice(arguments);
1857
+ args.unshift(this);
1858
+ return Q.denodeify.apply(void 0, args);
1859
+ };
1860
+
1861
+ Q.nbind = function (callback, thisp /*...args*/) {
1862
+ var baseArgs = array_slice(arguments, 2);
1863
+ return function () {
1864
+ var nodeArgs = baseArgs.concat(array_slice(arguments));
1865
+ var deferred = defer();
1866
+ nodeArgs.push(deferred.makeNodeResolver());
1867
+ function bound() {
1868
+ return callback.apply(thisp, arguments);
1869
+ }
1870
+ Q(bound).fapply(nodeArgs).fail(deferred.reject);
1871
+ return deferred.promise;
1872
+ };
1873
+ };
1874
+
1875
+ Promise.prototype.nbind = function (/*thisp, ...args*/) {
1876
+ var args = array_slice(arguments, 0);
1877
+ args.unshift(this);
1878
+ return Q.nbind.apply(void 0, args);
1879
+ };
1880
+
1881
+ /**
1882
+ * Calls a method of a Node-style object that accepts a Node-style
1883
+ * callback with a given array of arguments, plus a provided callback.
1884
+ * @param object an object that has the named method
1885
+ * @param {String} name name of the method of object
1886
+ * @param {Array} args arguments to pass to the method; the callback
1887
+ * will be provided by Q and appended to these arguments.
1888
+ * @returns a promise for the value or error
1889
+ */
1890
+ Q.nmapply = // XXX As proposed by "Redsandro"
1891
+ Q.npost = function (object, name, args) {
1892
+ return Q(object).npost(name, args);
1893
+ };
1894
+
1895
+ Promise.prototype.nmapply = // XXX As proposed by "Redsandro"
1896
+ Promise.prototype.npost = function (name, args) {
1897
+ var nodeArgs = array_slice(args || []);
1898
+ var deferred = defer();
1899
+ nodeArgs.push(deferred.makeNodeResolver());
1900
+ this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
1901
+ return deferred.promise;
1902
+ };
1903
+
1904
+ /**
1905
+ * Calls a method of a Node-style object that accepts a Node-style
1906
+ * callback, forwarding the given variadic arguments, plus a provided
1907
+ * callback argument.
1908
+ * @param object an object that has the named method
1909
+ * @param {String} name name of the method of object
1910
+ * @param ...args arguments to pass to the method; the callback will
1911
+ * be provided by Q and appended to these arguments.
1912
+ * @returns a promise for the value or error
1913
+ */
1914
+ Q.nsend = // XXX Based on Mark Miller's proposed "send"
1915
+ Q.nmcall = // XXX Based on "Redsandro's" proposal
1916
+ Q.ninvoke =
1917
+ function (object, name /*...args*/) {
1918
+ var nodeArgs = array_slice(arguments, 2);
1919
+ var deferred = defer();
1920
+ nodeArgs.push(deferred.makeNodeResolver());
1921
+ Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject);
1922
+ return deferred.promise;
1923
+ };
1924
+
1925
+ Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send"
1926
+ Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal
1927
+ Promise.prototype.ninvoke =
1928
+ function (name /*...args*/) {
1929
+ var nodeArgs = array_slice(arguments, 1);
1930
+ var deferred = defer();
1931
+ nodeArgs.push(deferred.makeNodeResolver());
1932
+ this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);
1933
+ return deferred.promise;
1934
+ };
1935
+
1936
+ /**
1937
+ * If a function would like to support both Node continuation-passing-style and
1938
+ * promise-returning-style, it can end its internal promise chain with
1939
+ * `nodeify(nodeback)`, forwarding the optional nodeback argument. If the user
1940
+ * elects to use a nodeback, the result will be sent there. If they do not
1941
+ * pass a nodeback, they will receive the result promise.
1942
+ * @param object a result (or a promise for a result)
1943
+ * @param {Function} nodeback a Node.js-style callback
1944
+ * @returns either the promise or nothing
1945
+ */
1946
+ Q.nodeify = nodeify;
1947
+ function nodeify(object, nodeback) {
1948
+ return Q(object).nodeify(nodeback);
1949
+ }
1950
+
1951
+ Promise.prototype.nodeify = function (nodeback) {
1952
+ if (nodeback) {
1953
+ this.then(
1954
+ function (value) {
1955
+ nextTick(function () {
1956
+ nodeback(null, value);
1957
+ });
1958
+ },
1959
+ function (error) {
1960
+ nextTick(function () {
1961
+ nodeback(error);
1962
+ });
1963
+ }
1964
+ );
1965
+ } else {
1966
+ return this;
1967
+ }
1968
+ };
1969
+
1970
+ // All code before this point will be filtered from stack traces.
1971
+ var qEndingLine = captureLine();
1972
+
1973
+ return Q;
1974
+ });