@difizen/libro-kernel 0.0.2-alpha.0

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.
Files changed (188) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/es/basemanager.d.ts +94 -0
  4. package/es/basemanager.d.ts.map +1 -0
  5. package/es/basemanager.js +110 -0
  6. package/es/contents/contents-drive.d.ts +189 -0
  7. package/es/contents/contents-drive.d.ts.map +1 -0
  8. package/es/contents/contents-drive.js +792 -0
  9. package/es/contents/contents-manager.d.ts +229 -0
  10. package/es/contents/contents-manager.d.ts.map +1 -0
  11. package/es/contents/contents-manager.js +551 -0
  12. package/es/contents/contents-module.d.ts +3 -0
  13. package/es/contents/contents-module.d.ts.map +1 -0
  14. package/es/contents/contents-module.js +4 -0
  15. package/es/contents/contents-protocol.d.ts +487 -0
  16. package/es/contents/contents-protocol.d.ts.map +1 -0
  17. package/es/contents/contents-protocol.js +1 -0
  18. package/es/contents/index.d.ts +6 -0
  19. package/es/contents/index.d.ts.map +1 -0
  20. package/es/contents/index.js +5 -0
  21. package/es/contents/validate.d.ts +10 -0
  22. package/es/contents/validate.d.ts.map +1 -0
  23. package/es/contents/validate.js +22 -0
  24. package/es/index.d.ts +10 -0
  25. package/es/index.d.ts.map +1 -0
  26. package/es/index.js +9 -0
  27. package/es/index.less +0 -0
  28. package/es/kernel/comm.d.ts +92 -0
  29. package/es/kernel/comm.d.ts.map +1 -0
  30. package/es/kernel/comm.js +216 -0
  31. package/es/kernel/future.d.ts +178 -0
  32. package/es/kernel/future.d.ts.map +1 -0
  33. package/es/kernel/future.js +587 -0
  34. package/es/kernel/index.d.ts +8 -0
  35. package/es/kernel/index.d.ts.map +1 -0
  36. package/es/kernel/index.js +8 -0
  37. package/es/kernel/kernel-connection.d.ts +550 -0
  38. package/es/kernel/kernel-connection.d.ts.map +1 -0
  39. package/es/kernel/kernel-connection.js +1957 -0
  40. package/es/kernel/kernel-module.d.ts +3 -0
  41. package/es/kernel/kernel-module.d.ts.map +1 -0
  42. package/es/kernel/kernel-module.js +32 -0
  43. package/es/kernel/libro-kernel-manager.d.ts +69 -0
  44. package/es/kernel/libro-kernel-manager.d.ts.map +1 -0
  45. package/es/kernel/libro-kernel-manager.js +349 -0
  46. package/es/kernel/libro-kernel-protocol.d.ts +675 -0
  47. package/es/kernel/libro-kernel-protocol.d.ts.map +1 -0
  48. package/es/kernel/libro-kernel-protocol.js +60 -0
  49. package/es/kernel/libro-kernel-utils.d.ts +95 -0
  50. package/es/kernel/libro-kernel-utils.d.ts.map +1 -0
  51. package/es/kernel/libro-kernel-utils.js +130 -0
  52. package/es/kernel/libro-kernel.d.ts +14 -0
  53. package/es/kernel/libro-kernel.d.ts.map +1 -0
  54. package/es/kernel/libro-kernel.js +54 -0
  55. package/es/kernel/messages.d.ts +845 -0
  56. package/es/kernel/messages.d.ts.map +1 -0
  57. package/es/kernel/messages.js +457 -0
  58. package/es/kernel/restapi.d.ts +78 -0
  59. package/es/kernel/restapi.d.ts.map +1 -0
  60. package/es/kernel/restapi.js +367 -0
  61. package/es/kernel/serialize.d.ts +10 -0
  62. package/es/kernel/serialize.d.ts.map +1 -0
  63. package/es/kernel/serialize.js +214 -0
  64. package/es/kernel/validate.d.ts +15 -0
  65. package/es/kernel/validate.d.ts.map +1 -0
  66. package/es/kernel/validate.js +125 -0
  67. package/es/kernelspec/index.d.ts +5 -0
  68. package/es/kernelspec/index.d.ts.map +1 -0
  69. package/es/kernelspec/index.js +4 -0
  70. package/es/kernelspec/kernelspec-module.d.ts +3 -0
  71. package/es/kernelspec/kernelspec-module.d.ts.map +1 -0
  72. package/es/kernelspec/kernelspec-module.js +4 -0
  73. package/es/kernelspec/kernelspec.d.ts +33 -0
  74. package/es/kernelspec/kernelspec.d.ts.map +1 -0
  75. package/es/kernelspec/kernelspec.js +1 -0
  76. package/es/kernelspec/manager.d.ts +81 -0
  77. package/es/kernelspec/manager.d.ts.map +1 -0
  78. package/es/kernelspec/manager.js +248 -0
  79. package/es/kernelspec/restapi.d.ts +71 -0
  80. package/es/kernelspec/restapi.d.ts.map +1 -0
  81. package/es/kernelspec/restapi.js +107 -0
  82. package/es/kernelspec/validate.d.ts +10 -0
  83. package/es/kernelspec/validate.d.ts.map +1 -0
  84. package/es/kernelspec/validate.js +69 -0
  85. package/es/libro-kernel-connection-manager.d.ts +19 -0
  86. package/es/libro-kernel-connection-manager.d.ts.map +1 -0
  87. package/es/libro-kernel-connection-manager.js +142 -0
  88. package/es/module.d.ts +3 -0
  89. package/es/module.d.ts.map +1 -0
  90. package/es/module.js +9 -0
  91. package/es/page-config.d.ts +36 -0
  92. package/es/page-config.d.ts.map +1 -0
  93. package/es/page-config.js +129 -0
  94. package/es/protocol.d.ts +13 -0
  95. package/es/protocol.d.ts.map +1 -0
  96. package/es/protocol.js +8 -0
  97. package/es/server/connection-error.d.ts +36 -0
  98. package/es/server/connection-error.d.ts.map +1 -0
  99. package/es/server/connection-error.js +109 -0
  100. package/es/server/index.d.ts +6 -0
  101. package/es/server/index.d.ts.map +1 -0
  102. package/es/server/index.js +5 -0
  103. package/es/server/server-connection-protocol.d.ts +49 -0
  104. package/es/server/server-connection-protocol.d.ts.map +1 -0
  105. package/es/server/server-connection-protocol.js +0 -0
  106. package/es/server/server-connection.d.ts +25 -0
  107. package/es/server/server-connection.d.ts.map +1 -0
  108. package/es/server/server-connection.js +159 -0
  109. package/es/server/server-manager.d.ts +22 -0
  110. package/es/server/server-manager.d.ts.map +1 -0
  111. package/es/server/server-manager.js +163 -0
  112. package/es/server/server-module.d.ts +3 -0
  113. package/es/server/server-module.d.ts.map +1 -0
  114. package/es/server/server-module.js +4 -0
  115. package/es/session/index.d.ts +5 -0
  116. package/es/session/index.d.ts.map +1 -0
  117. package/es/session/index.js +4 -0
  118. package/es/session/libro-session-manager.d.ts +71 -0
  119. package/es/session/libro-session-manager.d.ts.map +1 -0
  120. package/es/session/libro-session-manager.js +539 -0
  121. package/es/session/libro-session-protocol.d.ts +50 -0
  122. package/es/session/libro-session-protocol.d.ts.map +1 -0
  123. package/es/session/libro-session-protocol.js +21 -0
  124. package/es/session/libro-session.d.ts +12 -0
  125. package/es/session/libro-session.d.ts.map +1 -0
  126. package/es/session/libro-session.js +19 -0
  127. package/es/session/restapi.d.ts +28 -0
  128. package/es/session/restapi.d.ts.map +1 -0
  129. package/es/session/restapi.js +214 -0
  130. package/es/session/session-module.d.ts +3 -0
  131. package/es/session/session-module.d.ts.map +1 -0
  132. package/es/session/session-module.js +18 -0
  133. package/es/session/validate.d.ts +14 -0
  134. package/es/session/validate.d.ts.map +1 -0
  135. package/es/session/validate.js +37 -0
  136. package/es/utils.d.ts +4 -0
  137. package/es/utils.d.ts.map +1 -0
  138. package/es/utils.js +29 -0
  139. package/es/validate-property.d.ts +2 -0
  140. package/es/validate-property.d.ts.map +1 -0
  141. package/es/validate-property.js +35 -0
  142. package/package.json +62 -0
  143. package/src/basemanager.ts +133 -0
  144. package/src/contents/contents-drive.ts +495 -0
  145. package/src/contents/contents-manager.ts +465 -0
  146. package/src/contents/contents-module.ts +6 -0
  147. package/src/contents/contents-protocol.ts +604 -0
  148. package/src/contents/index.ts +5 -0
  149. package/src/contents/validate.ts +29 -0
  150. package/src/index.tsx +9 -0
  151. package/src/kernel/comm.ts +220 -0
  152. package/src/kernel/future.ts +474 -0
  153. package/src/kernel/index.ts +7 -0
  154. package/src/kernel/kernel-connection.ts +1770 -0
  155. package/src/kernel/kernel-module.ts +50 -0
  156. package/src/kernel/libro-kernel-manager.ts +199 -0
  157. package/src/kernel/libro-kernel-protocol.ts +858 -0
  158. package/src/kernel/libro-kernel-utils.ts +152 -0
  159. package/src/kernel/libro-kernel.ts +39 -0
  160. package/src/kernel/messages.ts +1104 -0
  161. package/src/kernel/restapi.ts +183 -0
  162. package/src/kernel/serialize.ts +262 -0
  163. package/src/kernel/validate.ts +101 -0
  164. package/src/kernelspec/index.ts +5 -0
  165. package/src/kernelspec/kernelspec-module.ts +9 -0
  166. package/src/kernelspec/kernelspec.ts +37 -0
  167. package/src/kernelspec/manager.ts +173 -0
  168. package/src/kernelspec/restapi.ts +104 -0
  169. package/src/kernelspec/validate.ts +80 -0
  170. package/src/libro-kernel-connection-manager.ts +73 -0
  171. package/src/module.ts +19 -0
  172. package/src/page-config.ts +106 -0
  173. package/src/protocol.ts +24 -0
  174. package/src/server/connection-error.ts +60 -0
  175. package/src/server/index.ts +5 -0
  176. package/src/server/server-connection-protocol.ts +57 -0
  177. package/src/server/server-connection.ts +144 -0
  178. package/src/server/server-manager.ts +76 -0
  179. package/src/server/server-module.ts +9 -0
  180. package/src/session/index.ts +4 -0
  181. package/src/session/libro-session-manager.ts +377 -0
  182. package/src/session/libro-session-protocol.ts +61 -0
  183. package/src/session/libro-session.ts +33 -0
  184. package/src/session/restapi.ts +126 -0
  185. package/src/session/session-module.ts +26 -0
  186. package/src/session/validate.ts +39 -0
  187. package/src/utils.ts +28 -0
  188. package/src/validate-property.ts +38 -0
@@ -0,0 +1,1957 @@
1
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
2
+ var _dec, _dec2, _dec3, _dec4, _dec5, _class, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4;
3
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
4
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
5
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
7
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
8
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
9
+ function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }
10
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
11
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
12
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
13
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
14
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
15
+ function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; }
16
+ function _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that ' + 'transform-class-properties is enabled and runs after the decorators transform.'); }
17
+ import { deepCopy, URL } from '@difizen/libro-common';
18
+ import { prop } from '@difizen/mana-app';
19
+ import { Deferred, Emitter } from '@difizen/mana-app';
20
+ import { inject, transient } from '@difizen/mana-app';
21
+ import { v4 } from 'uuid';
22
+ import { KernelSpecRestAPI } from "../kernelspec/index.js";
23
+ import { NetworkError, ServerConnection } from "../server/index.js";
24
+ import { CommHandler } from "./comm.js";
25
+ import { KernelControlFutureHandler, KernelShellFutureHandler } from "./future.js";
26
+ import { KernelConnectionOptions, LibroKernelConnectionFactory } from "./libro-kernel-protocol.js";
27
+ import { isDisplayDataMsg, isExecuteResultMsg, isInfoRequestMsg, isUpdateDisplayDataMsg } from "./libro-kernel-utils.js";
28
+ import * as KernelMessage from "./messages.js";
29
+ import * as restapi from "./restapi.js";
30
+ import { KernelRestAPI } from "./restapi.js";
31
+ import { deserialize, serialize } from "./serialize.js";
32
+ import * as validate from "./validate.js";
33
+
34
+ // 以下 三个 没必要follow jupyter lab
35
+
36
+ // Stub for requirejs.
37
+ /**
38
+ * A protected namespace for the Kernel.
39
+ */
40
+ var Private;
41
+ (function (_Private) {
42
+ function logKernelStatus(kernel) {
43
+ switch (kernel.status) {
44
+ case 'idle':
45
+ case 'busy':
46
+ case 'unknown':
47
+ return;
48
+ default:
49
+ // eslint-disable-next-line no-console
50
+ console.debug("Kernel: ".concat(kernel.status, " (").concat(kernel.id, ")"));
51
+ break;
52
+ }
53
+ }
54
+ _Private.logKernelStatus = logKernelStatus;
55
+ function handleShellMessage(_x10, _x11) {
56
+ return _handleShellMessage.apply(this, arguments);
57
+ }
58
+ function _handleShellMessage() {
59
+ _handleShellMessage = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14(kernel, msg) {
60
+ var future;
61
+ return _regeneratorRuntime().wrap(function _callee14$(_context14) {
62
+ while (1) switch (_context14.prev = _context14.next) {
63
+ case 0:
64
+ future = kernel.sendShellMessage(msg, true);
65
+ return _context14.abrupt("return", future.done);
66
+ case 2:
67
+ case "end":
68
+ return _context14.stop();
69
+ }
70
+ }, _callee14);
71
+ }));
72
+ return _handleShellMessage.apply(this, arguments);
73
+ }
74
+ _Private.handleShellMessage = handleShellMessage;
75
+ function loadObject(name, moduleName, registry) {
76
+ return new Promise(function (resolve, reject) {
77
+ // Try loading the module using require.js
78
+ if (moduleName) {
79
+ if (typeof requirejs === 'undefined') {
80
+ throw new Error('requirejs not found');
81
+ }
82
+ requirejs([moduleName], function (mod) {
83
+ if (mod[name] === void 0) {
84
+ var _msg = "Object '".concat(name, "' not found in module '").concat(moduleName, "'");
85
+ reject(new Error(_msg));
86
+ } else {
87
+ resolve(mod[name]);
88
+ }
89
+ }, reject);
90
+ } else {
91
+ if (registry !== null && registry !== void 0 && registry[name]) {
92
+ resolve(registry[name]);
93
+ } else {
94
+ reject(new Error("Object '".concat(name, "' not found in registry")));
95
+ }
96
+ }
97
+ });
98
+ }
99
+ _Private.loadObject = loadObject;
100
+ function getRandomIntInclusive(min, max) {
101
+ var _min = Math.ceil(min);
102
+ var _max = Math.floor(max);
103
+ return Math.floor(Math.random() * (_max - _min + 1)) + _min;
104
+ }
105
+ _Private.getRandomIntInclusive = getRandomIntInclusive;
106
+ })(Private || (Private = {}));
107
+ var KERNEL_INFO_TIMEOUT = 3000;
108
+ var RESTARTING_KERNEL_SESSION = '_RESTARTING_';
109
+ var STARTING_KERNEL_SESSION = '';
110
+
111
+ /**
112
+ * Implementation of the Kernel object.
113
+ *
114
+ * #### Notes
115
+ * Messages from the server are handled in the order they were received and
116
+ * asynchronously. Any message handler can return a promise, and message
117
+ * handling will pause until the promise is fulfilled.
118
+ */
119
+ export var KernelConnection = (_dec = transient(), _dec2 = inject(KernelSpecRestAPI), _dec3 = inject(KernelRestAPI), _dec4 = inject(LibroKernelConnectionFactory), _dec5 = prop(), _dec(_class = (_class2 = /*#__PURE__*/function () {
120
+ /**
121
+ * Construct a kernel object.
122
+ */
123
+ function KernelConnection(options, serverConnection) {
124
+ var _this = this,
125
+ _options$clientId,
126
+ _options$username,
127
+ _options$handleComms;
128
+ _classCallCheck(this, KernelConnection);
129
+ _initializerDefineProperty(this, "kernelSpecRestAPI", _descriptor, this);
130
+ _initializerDefineProperty(this, "kernelRestAPI", _descriptor2, this);
131
+ _initializerDefineProperty(this, "libroKernelConnectionFactory", _descriptor3, this);
132
+ /**
133
+ * Forcefully clear the socket state.
134
+ *
135
+ * #### Notes
136
+ * This will clear all socket state without calling any handlers and will
137
+ * not update the connection status. If you call this method, you are
138
+ * responsible for updating the connection status as needed and recreating
139
+ * the socket if you plan to reconnect.
140
+ */
141
+ this._clearSocket = function () {
142
+ if (_this._ws !== null) {
143
+ // Clear the websocket event handlers and the socket itself.
144
+ _this._ws.onopen = _this._noOp;
145
+ _this._ws.onclose = _this._noOp;
146
+ _this._ws.onerror = _this._noOp;
147
+ _this._ws.onmessage = _this._noOp;
148
+ _this._ws.close();
149
+ _this._ws = null;
150
+ }
151
+ };
152
+ /**
153
+ * Create the kernel websocket connection and add socket status handlers.
154
+ */
155
+ this._createSocket = function () {
156
+ var useProtocols = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
157
+ _this._errorIfDisposed();
158
+
159
+ // Make sure the socket is clear
160
+ _this._clearSocket();
161
+
162
+ // Update the connection status to reflect opening a new connection.
163
+ _this._updateConnectionStatus('connecting');
164
+ var settings = _this.serverSettings;
165
+ var partialUrl = URL.join(settings.wsUrl, restapi.KERNEL_SERVICE_URL, encodeURIComponent(_this._id));
166
+
167
+ // Strip any authentication from the display string.
168
+ // eslint-disable-next-line no-useless-escape
169
+ var display = partialUrl.replace(/^((?:\w+:)?\/\/)(?:[^@\/]+@)/, '$1');
170
+ // eslint-disable-next-line no-console
171
+ console.debug("Starting WebSocket: ".concat(display));
172
+ var url = URL.join(partialUrl, 'channels?session_id=' + encodeURIComponent(_this._clientId));
173
+
174
+ // If token authentication is in use.
175
+ var token = settings.token;
176
+ if (settings.appendToken && token !== '') {
177
+ url = url + "&token=".concat(encodeURIComponent(token));
178
+ }
179
+
180
+ // Try opening the websocket with our list of subprotocols.
181
+ // If the server doesn't handle subprotocols,
182
+ // the accepted protocol will be ''.
183
+ // But we cannot send '' as a subprotocol, so if connection fails,
184
+ // reconnect without subprotocols.
185
+ var supportedProtocols = useProtocols ? _this._supportedProtocols : [];
186
+ _this._ws = new settings.WebSocket(url, supportedProtocols);
187
+
188
+ // Ensure incoming binary messages are not Blobs
189
+ _this._ws.binaryType = 'arraybuffer';
190
+ var alreadyCalledOnclose = false;
191
+ var getKernelModel = /*#__PURE__*/function () {
192
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(evt) {
193
+ var model, _err$response, _err$response2, timeout;
194
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
195
+ while (1) switch (_context.prev = _context.next) {
196
+ case 0:
197
+ if (!_this._isDisposed) {
198
+ _context.next = 2;
199
+ break;
200
+ }
201
+ return _context.abrupt("return");
202
+ case 2:
203
+ _this._reason = '';
204
+ _this._model = undefined;
205
+ _context.prev = 4;
206
+ _context.next = 7;
207
+ return _this.kernelRestAPI.getKernelModel(_this._id, settings);
208
+ case 7:
209
+ model = _context.sent;
210
+ _this._model = model;
211
+ if ((model === null || model === void 0 ? void 0 : model.execution_state) === 'dead') {
212
+ _this._updateStatus('dead');
213
+ } else {
214
+ _this._onWSClose(evt);
215
+ }
216
+ _context.next = 15;
217
+ break;
218
+ case 12:
219
+ _context.prev = 12;
220
+ _context.t0 = _context["catch"](4);
221
+ // Try again, if there is a network failure
222
+ // Handle network errors, as well as cases where we are on a
223
+ // JupyterHub and the server is not running. JupyterHub returns a
224
+ // 503 (<2.0) or 424 (>2.0) in that case.
225
+ if (_context.t0 instanceof NetworkError || ((_err$response = _context.t0.response) === null || _err$response === void 0 ? void 0 : _err$response.status) === 503 || ((_err$response2 = _context.t0.response) === null || _err$response2 === void 0 ? void 0 : _err$response2.status) === 424) {
226
+ timeout = Private.getRandomIntInclusive(10, 30) * 1e3;
227
+ setTimeout(getKernelModel, timeout, evt);
228
+ } else {
229
+ _this._reason = 'Kernel died unexpectedly';
230
+ _this._updateStatus('dead');
231
+ }
232
+ case 15:
233
+ return _context.abrupt("return");
234
+ case 16:
235
+ case "end":
236
+ return _context.stop();
237
+ }
238
+ }, _callee, null, [[4, 12]]);
239
+ }));
240
+ return function getKernelModel(_x) {
241
+ return _ref.apply(this, arguments);
242
+ };
243
+ }();
244
+ var earlyClose = /*#__PURE__*/function () {
245
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(evt) {
246
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
247
+ while (1) switch (_context2.prev = _context2.next) {
248
+ case 0:
249
+ if (!alreadyCalledOnclose) {
250
+ _context2.next = 2;
251
+ break;
252
+ }
253
+ return _context2.abrupt("return");
254
+ case 2:
255
+ alreadyCalledOnclose = true;
256
+ _context2.next = 5;
257
+ return getKernelModel(evt);
258
+ case 5:
259
+ return _context2.abrupt("return");
260
+ case 6:
261
+ case "end":
262
+ return _context2.stop();
263
+ }
264
+ }, _callee2);
265
+ }));
266
+ return function earlyClose(_x2) {
267
+ return _ref2.apply(this, arguments);
268
+ };
269
+ }();
270
+ _this._ws.onmessage = _this._onWSMessage;
271
+ _this._ws.onopen = _this._onWSOpen;
272
+ _this._ws.onclose = earlyClose;
273
+ _this._ws.onerror = earlyClose;
274
+ };
275
+ // Make websocket callbacks arrow functions so they bind `this`.
276
+ /**
277
+ * Handle a websocket open event.
278
+ */
279
+ this._onWSOpen = function () {
280
+ if (_this._ws.protocol !== '' && !_this._supportedProtocols.includes(_this._ws.protocol)) {
281
+ console.warn('Server selected unknown kernel wire protocol:', _this._ws.protocol);
282
+ _this._updateStatus('dead');
283
+ throw new Error("Unknown kernel wire protocol: ".concat(_this._ws.protocol));
284
+ }
285
+ // Remember the kernel wire protocol selected by the server.
286
+ _this._selectedProtocol = _this._ws.protocol;
287
+ _this._ws.onclose = _this._onWSClose;
288
+ _this._ws.onerror = _this._onWSClose;
289
+ _this._updateConnectionStatus('connected');
290
+ };
291
+ /**
292
+ * Handle a websocket message, validating and routing appropriately.
293
+ */
294
+ this._onWSMessage = function (evt) {
295
+ // Notify immediately if there is an error with the message.
296
+ var msg;
297
+ try {
298
+ msg = deserialize(evt.data, _this._ws.protocol);
299
+ validate.validateMessage(msg);
300
+ } catch (error) {
301
+ error.message = "Kernel message validation error: ".concat(error.message);
302
+ // We throw the error so that it bubbles up to the top, and displays the right stack.
303
+ throw error;
304
+ }
305
+
306
+ // Update the current kernel session id
307
+ _this._kernelSession = msg.header.session;
308
+
309
+ // Handle the message asynchronously, in the order received.
310
+ _this._msgChain = _this._msgChain.then(function () {
311
+ // Return so that any promises from handling a message are fulfilled
312
+ // before proceeding to the next message.
313
+ return _this._handleMessage(msg);
314
+ }).catch(function (error) {
315
+ // Log any errors in handling the message, thus resetting the _msgChain
316
+ // promise so we can process more messages.
317
+ // Ignore the "Canceled" errors that are thrown during kernel dispose.
318
+ if (error.message.startsWith('Canceled future for ')) {
319
+ console.error(error);
320
+ }
321
+ });
322
+
323
+ // Emit the message receive signal
324
+ _this.anyMessageEmitter.fire({
325
+ msg: msg,
326
+ direction: 'recv'
327
+ });
328
+ };
329
+ /**
330
+ * Handle a websocket close event.
331
+ */
332
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
333
+ this._onWSClose = function (_evt) {
334
+ if (!_this.isDisposed) {
335
+ _this._reconnect();
336
+ }
337
+ };
338
+ this._id = '';
339
+ this._name = '';
340
+ _initializerDefineProperty(this, "_status", _descriptor4, this);
341
+ this._connectionStatus = 'connecting';
342
+ this._kernelSession = '';
343
+ this._isDisposed = false;
344
+ /**
345
+ * Websocket to communicate with kernel.
346
+ */
347
+ this._ws = null;
348
+ this._username = '';
349
+ this._reconnectLimit = 7;
350
+ this._reconnectAttempt = 0;
351
+ this._reconnectTimeout = null;
352
+ this._supportedProtocols = Object.values(KernelMessage.supportedKernelWebSocketProtocols);
353
+ this._selectedProtocol = '';
354
+ this._futures = new Map();
355
+ this._comms = new Map();
356
+ this._targetRegistry = Object.create(null);
357
+ this._info = new Deferred();
358
+ this._pendingMessages = [];
359
+ this.statusChangedEmitter = new Emitter();
360
+ this.connectionStatusChangedEmitter = new Emitter();
361
+ this.onDisposedEmitter = new Emitter();
362
+ this.iopubMessageEmitter = new Emitter();
363
+ this.anyMessageEmitter = new Emitter();
364
+ this.pendingInputEmitter = new Emitter();
365
+ this.unhandledMessageEmitter = new Emitter();
366
+ this._displayIdToParentIds = new Map();
367
+ this._msgIdToDisplayIds = new Map();
368
+ this._msgChain = Promise.resolve();
369
+ this._hasPendingInput = false;
370
+ this._reason = '';
371
+ this._noOp = function () {
372
+ /* no-op */
373
+ };
374
+ this.serverSettings = _objectSpread(_objectSpread({}, serverConnection.settings), options.serverSettings);
375
+ this._name = options.model.name;
376
+ this._id = options.model.id;
377
+ this._clientId = (_options$clientId = options.clientId) !== null && _options$clientId !== void 0 ? _options$clientId : v4();
378
+ this._username = (_options$username = options.username) !== null && _options$username !== void 0 ? _options$username : '';
379
+ this.handleComms = (_options$handleComms = options.handleComms) !== null && _options$handleComms !== void 0 ? _options$handleComms : true;
380
+ this._createSocket();
381
+ }
382
+ KernelConnection = inject(ServerConnection)(KernelConnection, undefined, 1) || KernelConnection;
383
+ KernelConnection = inject(KernelConnectionOptions)(KernelConnection, undefined, 0) || KernelConnection;
384
+ _createClass(KernelConnection, [{
385
+ key: "send",
386
+ value: function send(msg) {
387
+ var _this$_ws;
388
+ (_this$_ws = this._ws) === null || _this$_ws === void 0 ? void 0 : _this$_ws.send(msg);
389
+ }
390
+ }, {
391
+ key: "onDisposed",
392
+ get: function get() {
393
+ return this.onDisposedEmitter.event;
394
+ }
395
+
396
+ /**
397
+ * The server settings for the kernel.
398
+ */
399
+
400
+ /**
401
+ * Handle comm messages
402
+ *
403
+ * #### Notes
404
+ * The comm message protocol currently has implicit assumptions that only
405
+ * one kernel connection is handling comm messages. This option allows a
406
+ * kernel connection to opt out of handling comms.
407
+ *
408
+ * See https://github.com/jupyter/jupyter_client/issues/263
409
+ */
410
+ }, {
411
+ key: "statusChanged",
412
+ get:
413
+ /**
414
+ * A signal emitted when the kernel status changes.
415
+ */
416
+ function get() {
417
+ return this.statusChangedEmitter.event;
418
+ }
419
+
420
+ /**
421
+ * A signal emitted when the kernel status changes.
422
+ */
423
+ }, {
424
+ key: "connectionStatusChanged",
425
+ get: function get() {
426
+ return this.connectionStatusChangedEmitter.event;
427
+ }
428
+
429
+ /**
430
+ * A signal emitted for iopub kernel messages.
431
+ *
432
+ * #### Notes
433
+ * This signal is emitted after the iopub message is handled asynchronously.
434
+ */
435
+ }, {
436
+ key: "iopubMessage",
437
+ get: function get() {
438
+ return this.iopubMessageEmitter.event;
439
+ }
440
+
441
+ /**
442
+ * A signal emitted for unhandled kernel message.
443
+ *
444
+ * #### Notes
445
+ * This signal is emitted for a message that was not handled. It is emitted
446
+ * during the asynchronous message handling code.
447
+ */
448
+ }, {
449
+ key: "unhandledMessage",
450
+ get: function get() {
451
+ return this.unhandledMessageEmitter.event;
452
+ }
453
+
454
+ /**
455
+ * The kernel model
456
+ */
457
+ }, {
458
+ key: "model",
459
+ get: function get() {
460
+ return this._model || {
461
+ id: this.id,
462
+ name: this.name,
463
+ reason: this._reason
464
+ };
465
+ }
466
+
467
+ /**
468
+ * A signal emitted for any kernel message.
469
+ *
470
+ * #### Notes
471
+ * This signal is emitted when a message is received, before it is handled
472
+ * asynchronously.
473
+ *
474
+ * This message is emitted when a message is queued for sending (either in
475
+ * the websocket buffer, or our own pending message buffer). The message may
476
+ * actually be sent across the wire at a later time.
477
+ *
478
+ * The message emitted in this signal should not be modified in any way.
479
+ */
480
+ }, {
481
+ key: "anyMessage",
482
+ get: function get() {
483
+ return this.anyMessageEmitter.event;
484
+ }
485
+
486
+ /**
487
+ * A signal emitted when a kernel has pending inputs from the user.
488
+ */
489
+ }, {
490
+ key: "pendingInput",
491
+ get: function get() {
492
+ return this.pendingInputEmitter.event;
493
+ }
494
+
495
+ /**
496
+ * The id of the server-side kernel.
497
+ */
498
+ }, {
499
+ key: "id",
500
+ get: function get() {
501
+ return this._id;
502
+ }
503
+
504
+ /**
505
+ * The name of the server-side kernel.
506
+ */
507
+ }, {
508
+ key: "name",
509
+ get: function get() {
510
+ return this._name;
511
+ }
512
+
513
+ /**
514
+ * The client username.
515
+ */
516
+ }, {
517
+ key: "username",
518
+ get: function get() {
519
+ return this._username;
520
+ }
521
+
522
+ /**
523
+ * The client unique id.
524
+ */
525
+ }, {
526
+ key: "clientId",
527
+ get: function get() {
528
+ return this._clientId;
529
+ }
530
+
531
+ /**
532
+ * The current status of the kernel.
533
+ */
534
+ }, {
535
+ key: "status",
536
+ get: function get() {
537
+ return this._status;
538
+ }
539
+
540
+ /**
541
+ * The current connection status of the kernel connection.
542
+ */
543
+ }, {
544
+ key: "connectionStatus",
545
+ get: function get() {
546
+ return this._connectionStatus;
547
+ }
548
+
549
+ /**
550
+ * Test whether the kernel has been disposed.
551
+ */
552
+ }, {
553
+ key: "isDisposed",
554
+ get: function get() {
555
+ return this._isDisposed;
556
+ }
557
+
558
+ /**
559
+ * The cached kernel info.
560
+ *
561
+ * @returns A promise that resolves to the kernel info.
562
+ */
563
+ }, {
564
+ key: "info",
565
+ get: function get() {
566
+ return this._info.promise;
567
+ }
568
+
569
+ /**
570
+ * The kernel spec.
571
+ *
572
+ * @returns A promise that resolves to the kernel spec.
573
+ */
574
+ }, {
575
+ key: "spec",
576
+ get: function get() {
577
+ var _this2 = this;
578
+ if (this._specPromise) {
579
+ return this._specPromise;
580
+ }
581
+ this._specPromise = this.kernelSpecRestAPI.getSpecs(this.serverSettings).then(function (specs) {
582
+ return specs.kernelspecs[_this2._name];
583
+ });
584
+ return this._specPromise;
585
+ }
586
+
587
+ /**
588
+ * Clone the current kernel with a new clientId.
589
+ */
590
+ }, {
591
+ key: "clone",
592
+ value: function clone() {
593
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
594
+ return this.libroKernelConnectionFactory(_objectSpread({
595
+ model: this.model,
596
+ username: this.username,
597
+ // handleComms defaults to false since that is safer
598
+ handleComms: false
599
+ }, options));
600
+ }
601
+
602
+ /**
603
+ * Dispose of the resources held by the kernel.
604
+ */
605
+ }, {
606
+ key: "dispose",
607
+ value: function dispose() {
608
+ if (this.isDisposed) {
609
+ return;
610
+ }
611
+ this.onDisposedEmitter.fire();
612
+ this._updateConnectionStatus('disconnected');
613
+ this._clearKernelState();
614
+ this._pendingMessages = [];
615
+ this._clearSocket();
616
+ this.connectionStatusChangedEmitter.dispose();
617
+ this.statusChangedEmitter.dispose();
618
+ this.onDisposedEmitter.dispose();
619
+ this.iopubMessageEmitter.dispose();
620
+ this.anyMessageEmitter.dispose();
621
+ this.pendingInputEmitter.dispose();
622
+ this.unhandledMessageEmitter.dispose();
623
+ this._isDisposed = true;
624
+ }
625
+
626
+ /**
627
+ * Send a shell message to the kernel.
628
+ *
629
+ * #### Notes
630
+ * Send a message to the kernel's shell channel, yielding a future object
631
+ * for accepting replies.
632
+ *
633
+ * If `expectReply` is given and `true`, the future is disposed when both a
634
+ * shell reply and an idle status message are received. If `expectReply`
635
+ * is not given or is `false`, the future is resolved when an idle status
636
+ * message is received.
637
+ * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.
638
+ * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.
639
+ *
640
+ * All replies are validated as valid kernel messages.
641
+ *
642
+ * If the kernel status is `dead`, this will throw an error.
643
+ */
644
+ }, {
645
+ key: "sendShellMessage",
646
+ value: function sendShellMessage(msg) {
647
+ var expectReply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
648
+ var disposeOnDone = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
649
+ return this._sendKernelShellControl(KernelShellFutureHandler, msg, expectReply, disposeOnDone);
650
+ }
651
+
652
+ /**
653
+ * Send a control message to the kernel.
654
+ *
655
+ * #### Notes
656
+ * Send a message to the kernel's control channel, yielding a future object
657
+ * for accepting replies.
658
+ *
659
+ * If `expectReply` is given and `true`, the future is disposed when both a
660
+ * control reply and an idle status message are received. If `expectReply`
661
+ * is not given or is `false`, the future is resolved when an idle status
662
+ * message is received.
663
+ * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.
664
+ * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.
665
+ *
666
+ * All replies are validated as valid kernel messages.
667
+ *
668
+ * If the kernel status is `dead`, this will throw an error.
669
+ */
670
+ }, {
671
+ key: "sendControlMessage",
672
+ value: function sendControlMessage(msg) {
673
+ var expectReply = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
674
+ var disposeOnDone = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
675
+ return this._sendKernelShellControl(KernelControlFutureHandler, msg, expectReply, disposeOnDone);
676
+ }
677
+ }, {
678
+ key: "_sendKernelShellControl",
679
+ value: function _sendKernelShellControl(ctor, msg) {
680
+ var _this3 = this;
681
+ var expectReply = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
682
+ var disposeOnDone = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
683
+ this._sendMessage(msg);
684
+ this.anyMessageEmitter.fire({
685
+ msg: msg,
686
+ direction: 'send'
687
+ });
688
+ var future = new ctor(function () {
689
+ var msgId = msg.header.msg_id;
690
+ _this3._futures.delete(msgId);
691
+ // Remove stored display id information.
692
+ var displayIds = _this3._msgIdToDisplayIds.get(msgId);
693
+ if (!displayIds) {
694
+ return;
695
+ }
696
+ displayIds.forEach(function (displayId) {
697
+ var msgIds = _this3._displayIdToParentIds.get(displayId);
698
+ if (msgIds) {
699
+ var idx = msgIds.indexOf(msgId);
700
+ if (idx === -1) {
701
+ return;
702
+ }
703
+ if (msgIds.length === 1) {
704
+ _this3._displayIdToParentIds.delete(displayId);
705
+ } else {
706
+ msgIds.splice(idx, 1);
707
+ _this3._displayIdToParentIds.set(displayId, msgIds);
708
+ }
709
+ }
710
+ });
711
+ _this3._msgIdToDisplayIds.delete(msgId);
712
+ }, msg, expectReply, disposeOnDone, this);
713
+ this._futures.set(msg.header.msg_id, future);
714
+ return future;
715
+ }
716
+
717
+ /**
718
+ * Send a message on the websocket.
719
+ *
720
+ * If queue is true, queue the message for later sending if we cannot send
721
+ * now. Otherwise throw an error.
722
+ *
723
+ * #### Notes
724
+ * As an exception to the queueing, if we are sending a kernel_info_request
725
+ * message while we think the kernel is restarting, we send the message
726
+ * immediately without queueing. This is so that we can trigger a message
727
+ * back, which will then clear the kernel restarting state.
728
+ */
729
+ }, {
730
+ key: "_sendMessage",
731
+ value: function _sendMessage(msg) {
732
+ var queue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
733
+ if (this.status === 'dead') {
734
+ throw new Error('Kernel is dead');
735
+ }
736
+
737
+ // If we have a kernel_info_request and we are starting or restarting, send the
738
+ // kernel_info_request immediately if we can, and if not throw an error so
739
+ // we can retry later. On restarting we do this because we must get at least one message
740
+ // from the kernel to reset the kernel session (thus clearing the restart
741
+ // status sentinel).
742
+ if ((this._kernelSession === STARTING_KERNEL_SESSION || this._kernelSession === RESTARTING_KERNEL_SESSION) && isInfoRequestMsg(msg)) {
743
+ if (this.connectionStatus === 'connected') {
744
+ this._ws.send(serialize(msg, this._ws.protocol));
745
+ return;
746
+ } else {
747
+ throw new Error('Could not send message: status is not connected');
748
+ }
749
+ }
750
+
751
+ // If there are pending messages, add to the queue so we keep messages in order
752
+ if (queue && this._pendingMessages.length > 0) {
753
+ this._pendingMessages.push(msg);
754
+ return;
755
+ }
756
+
757
+ // Send if the ws allows it, otherwise queue the message.
758
+ if (this.connectionStatus === 'connected' && this._kernelSession !== RESTARTING_KERNEL_SESSION) {
759
+ this._ws.send(serialize(msg, this._ws.protocol));
760
+ } else if (queue) {
761
+ this._pendingMessages.push(msg);
762
+ } else {
763
+ throw new Error('Could not send message');
764
+ }
765
+ }
766
+
767
+ /**
768
+ * Interrupt a kernel.
769
+ *
770
+ * #### Notes
771
+ * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels).
772
+ *
773
+ * The promise is fulfilled on a valid response and rejected otherwise.
774
+ *
775
+ * It is assumed that the API call does not mutate the kernel id or name.
776
+ *
777
+ * The promise will be rejected if the kernel status is `Dead` or if the
778
+ * request fails or the response is invalid.
779
+ */
780
+ }, {
781
+ key: "interrupt",
782
+ value: function () {
783
+ var _interrupt = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
784
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
785
+ while (1) switch (_context3.prev = _context3.next) {
786
+ case 0:
787
+ this.hasPendingInput = false;
788
+ if (!(this.status === 'dead')) {
789
+ _context3.next = 3;
790
+ break;
791
+ }
792
+ throw new Error('Kernel is dead');
793
+ case 3:
794
+ return _context3.abrupt("return", this.kernelRestAPI.interruptKernel(this.id, this.serverSettings));
795
+ case 4:
796
+ case "end":
797
+ return _context3.stop();
798
+ }
799
+ }, _callee3, this);
800
+ }));
801
+ function interrupt() {
802
+ return _interrupt.apply(this, arguments);
803
+ }
804
+ return interrupt;
805
+ }()
806
+ /**
807
+ * Request a kernel restart.
808
+ *
809
+ * #### Notes
810
+ * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels)
811
+ * and validates the response model.
812
+ *
813
+ * Any existing Future or Comm objects are cleared once the kernel has
814
+ * actually be restarted.
815
+ *
816
+ * The promise is fulfilled on a valid server response (after the kernel restarts)
817
+ * and rejected otherwise.
818
+ *
819
+ * It is assumed that the API call does not mutate the kernel id or name.
820
+ *
821
+ * The promise will be rejected if the request fails or the response is
822
+ * invalid.
823
+ */
824
+ }, {
825
+ key: "restart",
826
+ value: function () {
827
+ var _restart = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
828
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
829
+ while (1) switch (_context4.prev = _context4.next) {
830
+ case 0:
831
+ if (!(this.status === 'dead')) {
832
+ _context4.next = 2;
833
+ break;
834
+ }
835
+ throw new Error('Kernel is dead');
836
+ case 2:
837
+ this._updateStatus('restarting');
838
+ this._clearKernelState();
839
+ this._kernelSession = RESTARTING_KERNEL_SESSION;
840
+ _context4.next = 7;
841
+ return this.kernelRestAPI.restartKernel(this.id, this.serverSettings);
842
+ case 7:
843
+ _context4.next = 9;
844
+ return this.reconnect();
845
+ case 9:
846
+ this.hasPendingInput = false;
847
+ case 10:
848
+ case "end":
849
+ return _context4.stop();
850
+ }
851
+ }, _callee4, this);
852
+ }));
853
+ function restart() {
854
+ return _restart.apply(this, arguments);
855
+ }
856
+ return restart;
857
+ }()
858
+ /**
859
+ * Reconnect to a kernel.
860
+ *
861
+ * #### Notes
862
+ * This may try multiple times to reconnect to a kernel, and will sever any
863
+ * existing connection.
864
+ */
865
+ }, {
866
+ key: "reconnect",
867
+ value: function reconnect() {
868
+ this._errorIfDisposed();
869
+ var result = new Deferred();
870
+ var toDispose = undefined;
871
+
872
+ // Set up a listener for the connection status changing, which accepts or
873
+ // rejects after the retries are done.
874
+ var fulfill = function fulfill(status) {
875
+ if (status === 'connected') {
876
+ result.resolve();
877
+ if (toDispose) {
878
+ toDispose.dispose();
879
+ toDispose = undefined;
880
+ }
881
+ } else if (status === 'disconnected') {
882
+ result.reject(new Error('Kernel connection disconnected'));
883
+ if (toDispose) {
884
+ toDispose.dispose();
885
+ toDispose = undefined;
886
+ }
887
+ }
888
+ };
889
+ toDispose = this.connectionStatusChanged(fulfill);
890
+
891
+ // Reset the reconnect limit so we start the connection attempts fresh
892
+ this._reconnectAttempt = 0;
893
+
894
+ // Start the reconnection process, which will also clear any existing
895
+ // connection.
896
+ this._reconnect();
897
+
898
+ // Return the promise that should resolve on connection or reject if the
899
+ // retries don't work.
900
+ return result.promise;
901
+ }
902
+
903
+ /**
904
+ * Shutdown a kernel.
905
+ *
906
+ * #### Notes
907
+ * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/kernels).
908
+ *
909
+ * The promise is fulfilled on a valid response and rejected otherwise.
910
+ *
911
+ * On a valid response, disposes this kernel connection.
912
+ *
913
+ * If the kernel is already `dead`, disposes this kernel connection without
914
+ * a server request.
915
+ */
916
+ }, {
917
+ key: "shutdown",
918
+ value: function () {
919
+ var _shutdown = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
920
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
921
+ while (1) switch (_context5.prev = _context5.next) {
922
+ case 0:
923
+ if (!(this.status !== 'dead')) {
924
+ _context5.next = 3;
925
+ break;
926
+ }
927
+ _context5.next = 3;
928
+ return this.kernelRestAPI.shutdownKernel(this.id, this.serverSettings);
929
+ case 3:
930
+ this.handleShutdown();
931
+ case 4:
932
+ case "end":
933
+ return _context5.stop();
934
+ }
935
+ }, _callee5, this);
936
+ }));
937
+ function shutdown() {
938
+ return _shutdown.apply(this, arguments);
939
+ }
940
+ return shutdown;
941
+ }()
942
+ /**
943
+ * Handles a kernel shutdown.
944
+ *
945
+ * #### Notes
946
+ * This method should be called if we know from outside information that a
947
+ * kernel is dead (for example, we cannot find the kernel model on the
948
+ * server).
949
+ */
950
+ }, {
951
+ key: "handleShutdown",
952
+ value: function handleShutdown() {
953
+ this._updateStatus('dead');
954
+ this.dispose();
955
+ }
956
+
957
+ /**
958
+ * Send a `kernel_info_request` message.
959
+ *
960
+ * #### Notes
961
+ * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).
962
+ *
963
+ * Fulfills with the `kernel_info_response` content when the shell reply is
964
+ * received and validated.
965
+ */
966
+ }, {
967
+ key: "requestKernelInfo",
968
+ value: function () {
969
+ var _requestKernelInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
970
+ var msg, reply;
971
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
972
+ while (1) switch (_context6.prev = _context6.next) {
973
+ case 0:
974
+ msg = KernelMessage.createMessage({
975
+ msgType: 'kernel_info_request',
976
+ channel: 'shell',
977
+ username: this._username,
978
+ session: this._clientId,
979
+ content: {}
980
+ });
981
+ _context6.prev = 1;
982
+ _context6.next = 4;
983
+ return Private.handleShellMessage(this, msg);
984
+ case 4:
985
+ reply = _context6.sent;
986
+ _context6.next = 14;
987
+ break;
988
+ case 7:
989
+ _context6.prev = 7;
990
+ _context6.t0 = _context6["catch"](1);
991
+ if (!this.isDisposed) {
992
+ _context6.next = 13;
993
+ break;
994
+ }
995
+ return _context6.abrupt("return");
996
+ case 13:
997
+ throw _context6.t0;
998
+ case 14:
999
+ this._errorIfDisposed();
1000
+ if (reply) {
1001
+ _context6.next = 17;
1002
+ break;
1003
+ }
1004
+ return _context6.abrupt("return");
1005
+ case 17:
1006
+ // Kernels sometimes do not include a status field on kernel_info_reply
1007
+ // messages, so set a default for now.
1008
+ // See https://github.com/jupyterlab/jupyterlab/issues/6760
1009
+ if (reply.content.status === undefined) {
1010
+ reply.content.status = 'ok';
1011
+ }
1012
+ if (!(reply.content.status !== 'ok')) {
1013
+ _context6.next = 21;
1014
+ break;
1015
+ }
1016
+ this._info.reject('Kernel info reply errored');
1017
+ return _context6.abrupt("return", reply);
1018
+ case 21:
1019
+ this._info.resolve(reply.content);
1020
+ this._kernelSession = reply.header.session;
1021
+ return _context6.abrupt("return", reply);
1022
+ case 24:
1023
+ case "end":
1024
+ return _context6.stop();
1025
+ }
1026
+ }, _callee6, this, [[1, 7]]);
1027
+ }));
1028
+ function requestKernelInfo() {
1029
+ return _requestKernelInfo.apply(this, arguments);
1030
+ }
1031
+ return requestKernelInfo;
1032
+ }()
1033
+ /**
1034
+ * Send a `complete_request` message.
1035
+ *
1036
+ * #### Notes
1037
+ * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).
1038
+ *
1039
+ * Fulfills with the `complete_reply` content when the shell reply is
1040
+ * received and validated.
1041
+ */
1042
+ }, {
1043
+ key: "requestComplete",
1044
+ value: function requestComplete(content) {
1045
+ var msg = KernelMessage.createMessage({
1046
+ msgType: 'complete_request',
1047
+ channel: 'shell',
1048
+ username: this._username,
1049
+ session: this._clientId,
1050
+ content: content
1051
+ });
1052
+ return Private.handleShellMessage(this, msg);
1053
+ }
1054
+
1055
+ /**
1056
+ * Send an `inspect_request` message.
1057
+ *
1058
+ * #### Notes
1059
+ * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).
1060
+ *
1061
+ * Fulfills with the `inspect_reply` content when the shell reply is
1062
+ * received and validated.
1063
+ */
1064
+ }, {
1065
+ key: "requestInspect",
1066
+ value: function requestInspect(content) {
1067
+ var msg = KernelMessage.createMessage({
1068
+ msgType: 'inspect_request',
1069
+ channel: 'shell',
1070
+ username: this._username,
1071
+ session: this._clientId,
1072
+ content: content
1073
+ });
1074
+ return Private.handleShellMessage(this, msg);
1075
+ }
1076
+
1077
+ /**
1078
+ * Send a `history_request` message.
1079
+ *
1080
+ * #### Notes
1081
+ * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).
1082
+ *
1083
+ * Fulfills with the `history_reply` content when the shell reply is
1084
+ * received and validated.
1085
+ */
1086
+ }, {
1087
+ key: "requestHistory",
1088
+ value: function requestHistory(content) {
1089
+ var msg = KernelMessage.createMessage({
1090
+ msgType: 'history_request',
1091
+ channel: 'shell',
1092
+ username: this._username,
1093
+ session: this._clientId,
1094
+ content: content
1095
+ });
1096
+ return Private.handleShellMessage(this, msg);
1097
+ }
1098
+
1099
+ /**
1100
+ * Send an `execute_request` message.
1101
+ *
1102
+ * #### Notes
1103
+ * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute).
1104
+ *
1105
+ * Future `onReply` is called with the `execute_reply` content when the
1106
+ * shell reply is received and validated. The future will resolve when
1107
+ * this message is received and the `idle` iopub status is received.
1108
+ * The future will also be disposed at this point unless `disposeOnDone`
1109
+ * is specified and `false`, in which case it is up to the caller to dispose
1110
+ * of the future.
1111
+ *
1112
+ * **See also:** [[IExecuteReply]]
1113
+ */
1114
+ }, {
1115
+ key: "requestExecute",
1116
+ value: function requestExecute(content) {
1117
+ var disposeOnDone = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1118
+ var metadata = arguments.length > 2 ? arguments[2] : undefined;
1119
+ var defaults = {
1120
+ silent: false,
1121
+ store_history: true,
1122
+ user_expressions: {},
1123
+ allow_stdin: true,
1124
+ stop_on_error: true
1125
+ };
1126
+ var msg = KernelMessage.createMessage({
1127
+ msgType: 'execute_request',
1128
+ channel: 'shell',
1129
+ username: this._username,
1130
+ session: this._clientId,
1131
+ content: _objectSpread(_objectSpread({}, defaults), content),
1132
+ metadata: metadata
1133
+ });
1134
+ return this.sendShellMessage(msg, true, disposeOnDone);
1135
+ }
1136
+
1137
+ /**
1138
+ * Send an experimental `debug_request` message.
1139
+ *
1140
+ * @hidden
1141
+ *
1142
+ * #### Notes
1143
+ * Debug messages are experimental messages that are not in the official
1144
+ * kernel message specification. As such, this function is *NOT* considered
1145
+ * part of the public API, and may change without notice.
1146
+ */
1147
+ }, {
1148
+ key: "requestDebug",
1149
+ value: function requestDebug(content) {
1150
+ var disposeOnDone = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1151
+ var msg = KernelMessage.createMessage({
1152
+ msgType: 'debug_request',
1153
+ channel: 'control',
1154
+ username: this._username,
1155
+ session: this._clientId,
1156
+ content: content
1157
+ });
1158
+ return this.sendControlMessage(msg, true, disposeOnDone);
1159
+ }
1160
+
1161
+ /**
1162
+ * Send an `is_complete_request` message.
1163
+ *
1164
+ * #### Notes
1165
+ * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).
1166
+ *
1167
+ * Fulfills with the `is_complete_response` content when the shell reply is
1168
+ * received and validated.
1169
+ */
1170
+ }, {
1171
+ key: "requestIsComplete",
1172
+ value: function requestIsComplete(content) {
1173
+ var msg = KernelMessage.createMessage({
1174
+ msgType: 'is_complete_request',
1175
+ channel: 'shell',
1176
+ username: this._username,
1177
+ session: this._clientId,
1178
+ content: content
1179
+ });
1180
+ return Private.handleShellMessage(this, msg);
1181
+ }
1182
+
1183
+ /**
1184
+ * Send a `comm_info_request` message.
1185
+ *
1186
+ * #### Notes
1187
+ * Fulfills with the `comm_info_reply` content when the shell reply is
1188
+ * received and validated.
1189
+ */
1190
+ }, {
1191
+ key: "requestCommInfo",
1192
+ value: function requestCommInfo(content) {
1193
+ var msg = KernelMessage.createMessage({
1194
+ msgType: 'comm_info_request',
1195
+ channel: 'shell',
1196
+ username: this._username,
1197
+ session: this._clientId,
1198
+ content: content
1199
+ });
1200
+ return Private.handleShellMessage(this, msg);
1201
+ }
1202
+
1203
+ /**
1204
+ * Send an `input_reply` message.
1205
+ *
1206
+ * #### Notes
1207
+ * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).
1208
+ */
1209
+ }, {
1210
+ key: "sendInputReply",
1211
+ value: function sendInputReply(content, parent_header) {
1212
+ var msg = KernelMessage.createMessage({
1213
+ msgType: 'input_reply',
1214
+ channel: 'stdin',
1215
+ username: this._username,
1216
+ session: this._clientId,
1217
+ content: content
1218
+ });
1219
+ msg.parent_header = parent_header;
1220
+ this._sendMessage(msg);
1221
+ this.anyMessageEmitter.fire({
1222
+ msg: msg,
1223
+ direction: 'send'
1224
+ });
1225
+ this.hasPendingInput = false;
1226
+ }
1227
+
1228
+ /**
1229
+ * Create a new comm.
1230
+ *
1231
+ * #### Notes
1232
+ * If a client-side comm already exists with the given commId, an error is thrown.
1233
+ * If the kernel does not handle comms, an error is thrown.
1234
+ */
1235
+ }, {
1236
+ key: "createComm",
1237
+ value: function createComm(targetName) {
1238
+ var _this4 = this;
1239
+ var commId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : v4();
1240
+ if (!this.handleComms) {
1241
+ throw new Error('Comms are disabled on this kernel connection');
1242
+ }
1243
+ if (this._comms.has(commId)) {
1244
+ throw new Error('Comm is already created');
1245
+ }
1246
+ var comm = new CommHandler(targetName, commId, this, function () {
1247
+ _this4._unregisterComm(commId);
1248
+ });
1249
+ this._comms.set(commId, comm);
1250
+ return comm;
1251
+ }
1252
+
1253
+ /**
1254
+ * Check if a comm exists.
1255
+ */
1256
+ }, {
1257
+ key: "hasComm",
1258
+ value: function hasComm(commId) {
1259
+ return this._comms.has(commId);
1260
+ }
1261
+
1262
+ /**
1263
+ * Register a comm target handler.
1264
+ *
1265
+ * @param targetName - The name of the comm target.
1266
+ *
1267
+ * @param callback - The callback invoked for a comm open message.
1268
+ *
1269
+ * @returns A disposable used to unregister the comm target.
1270
+ *
1271
+ * #### Notes
1272
+ * Only one comm target can be registered to a target name at a time, an
1273
+ * existing callback for the same target name will be overridden. A registered
1274
+ * comm target handler will take precedence over a comm which specifies a
1275
+ * `target_module`.
1276
+ *
1277
+ * If the callback returns a promise, kernel message processing will pause
1278
+ * until the returned promise is fulfilled.
1279
+ */
1280
+ }, {
1281
+ key: "registerCommTarget",
1282
+ value: function registerCommTarget(targetName, callback) {
1283
+ if (!this.handleComms) {
1284
+ return;
1285
+ }
1286
+ this._targetRegistry[targetName] = callback;
1287
+ }
1288
+
1289
+ /**
1290
+ * Remove a comm target handler.
1291
+ *
1292
+ * @param targetName - The name of the comm target to remove.
1293
+ *
1294
+ * @param callback - The callback to remove.
1295
+ *
1296
+ * #### Notes
1297
+ * The comm target is only removed if the callback argument matches.
1298
+ */
1299
+ }, {
1300
+ key: "removeCommTarget",
1301
+ value: function removeCommTarget(targetName, callback) {
1302
+ if (!this.handleComms) {
1303
+ return;
1304
+ }
1305
+ if (!this.isDisposed && this._targetRegistry[targetName] === callback) {
1306
+ delete this._targetRegistry[targetName];
1307
+ }
1308
+ }
1309
+
1310
+ /**
1311
+ * Register an IOPub message hook.
1312
+ *
1313
+ * @param msg_id - The parent_header message id the hook will intercept.
1314
+ *
1315
+ * @param hook - The callback invoked for the message.
1316
+ *
1317
+ * #### Notes
1318
+ * The IOPub hook system allows you to preempt the handlers for IOPub
1319
+ * messages that are responses to a given message id.
1320
+ *
1321
+ * The most recently registered hook is run first. A hook can return a
1322
+ * boolean or a promise to a boolean, in which case all kernel message
1323
+ * processing pauses until the promise is fulfilled. If a hook return value
1324
+ * resolves to false, any later hooks will not run and the function will
1325
+ * return a promise resolving to false. If a hook throws an error, the error
1326
+ * is logged to the console and the next hook is run. If a hook is
1327
+ * registered during the hook processing, it will not run until the next
1328
+ * message. If a hook is removed during the hook processing, it will be
1329
+ * deactivated immediately.
1330
+ *
1331
+ * See also [[IFuture.registerMessageHook]].
1332
+ */
1333
+ }, {
1334
+ key: "registerMessageHook",
1335
+ value: function registerMessageHook(msgId, hook) {
1336
+ var _this$_futures;
1337
+ var future = (_this$_futures = this._futures) === null || _this$_futures === void 0 ? void 0 : _this$_futures.get(msgId);
1338
+ if (future) {
1339
+ future.registerMessageHook(hook);
1340
+ }
1341
+ }
1342
+
1343
+ /**
1344
+ * Remove an IOPub message hook.
1345
+ *
1346
+ * @param msg_id - The parent_header message id the hook intercepted.
1347
+ *
1348
+ * @param hook - The callback invoked for the message.
1349
+ *
1350
+ */
1351
+ }, {
1352
+ key: "removeMessageHook",
1353
+ value: function removeMessageHook(msgId, hook) {
1354
+ var _this$_futures2;
1355
+ var future = (_this$_futures2 = this._futures) === null || _this$_futures2 === void 0 ? void 0 : _this$_futures2.get(msgId);
1356
+ if (future) {
1357
+ future.removeMessageHook(hook);
1358
+ }
1359
+ }
1360
+
1361
+ /**
1362
+ * Remove the input guard, if any.
1363
+ */
1364
+ }, {
1365
+ key: "removeInputGuard",
1366
+ value: function removeInputGuard() {
1367
+ this.hasPendingInput = false;
1368
+ }
1369
+
1370
+ /**
1371
+ * Handle a message with a display id.
1372
+ *
1373
+ * @returns Whether the message was handled.
1374
+ */
1375
+ }, {
1376
+ key: "_handleDisplayId",
1377
+ value: function () {
1378
+ var _handleDisplayId2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(displayId, msg) {
1379
+ var _this5 = this,
1380
+ _this$_displayIdToPar,
1381
+ _this$_msgIdToDisplay;
1382
+ var msgId, parentIds, updateMsg, displayIds;
1383
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
1384
+ while (1) switch (_context8.prev = _context8.next) {
1385
+ case 0:
1386
+ msgId = msg.parent_header.msg_id;
1387
+ parentIds = this._displayIdToParentIds.get(displayId);
1388
+ if (!parentIds) {
1389
+ _context8.next = 7;
1390
+ break;
1391
+ }
1392
+ // We've seen it before, update existing outputs with same display_id
1393
+ // by handling display_data as update_display_data.
1394
+ updateMsg = {
1395
+ header: deepCopy(msg.header),
1396
+ parent_header: deepCopy(msg.parent_header),
1397
+ metadata: deepCopy(msg.metadata),
1398
+ content: deepCopy(msg.content),
1399
+ channel: msg.channel,
1400
+ buffers: msg.buffers ? msg.buffers.slice() : []
1401
+ };
1402
+ updateMsg.header.msg_type = 'update_display_data';
1403
+ _context8.next = 7;
1404
+ return Promise.all(parentIds.map( /*#__PURE__*/function () {
1405
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(parentId) {
1406
+ var future;
1407
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1408
+ while (1) switch (_context7.prev = _context7.next) {
1409
+ case 0:
1410
+ future = _this5._futures && _this5._futures.get(parentId);
1411
+ if (!future) {
1412
+ _context7.next = 4;
1413
+ break;
1414
+ }
1415
+ _context7.next = 4;
1416
+ return future.handleMsg(updateMsg);
1417
+ case 4:
1418
+ case "end":
1419
+ return _context7.stop();
1420
+ }
1421
+ }, _callee7);
1422
+ }));
1423
+ return function (_x5) {
1424
+ return _ref3.apply(this, arguments);
1425
+ };
1426
+ }()));
1427
+ case 7:
1428
+ if (!(msg.header.msg_type === 'update_display_data')) {
1429
+ _context8.next = 9;
1430
+ break;
1431
+ }
1432
+ return _context8.abrupt("return", true);
1433
+ case 9:
1434
+ // Regular display_data with id, record it for future updating
1435
+ // in _displayIdToParentIds for future lookup.
1436
+ parentIds = (_this$_displayIdToPar = this._displayIdToParentIds.get(displayId)) !== null && _this$_displayIdToPar !== void 0 ? _this$_displayIdToPar : [];
1437
+ if (parentIds.indexOf(msgId) === -1) {
1438
+ parentIds.push(msgId);
1439
+ }
1440
+ this._displayIdToParentIds.set(displayId, parentIds);
1441
+
1442
+ // Add to our map of display ids for this message.
1443
+ displayIds = (_this$_msgIdToDisplay = this._msgIdToDisplayIds.get(msgId)) !== null && _this$_msgIdToDisplay !== void 0 ? _this$_msgIdToDisplay : [];
1444
+ if (displayIds.indexOf(msgId) === -1) {
1445
+ displayIds.push(msgId);
1446
+ }
1447
+ this._msgIdToDisplayIds.set(msgId, displayIds);
1448
+
1449
+ // Let the message propagate to the intended recipient.
1450
+ return _context8.abrupt("return", false);
1451
+ case 16:
1452
+ case "end":
1453
+ return _context8.stop();
1454
+ }
1455
+ }, _callee8, this);
1456
+ }));
1457
+ function _handleDisplayId(_x3, _x4) {
1458
+ return _handleDisplayId2.apply(this, arguments);
1459
+ }
1460
+ return _handleDisplayId;
1461
+ }()
1462
+ }, {
1463
+ key: "_updateStatus",
1464
+ value:
1465
+ /**
1466
+ * Handle status iopub messages from the kernel.
1467
+ */
1468
+ function _updateStatus(status) {
1469
+ if (this._status === status || this._status === 'dead') {
1470
+ return;
1471
+ }
1472
+ this._status = status;
1473
+ Private.logKernelStatus(this);
1474
+ this.statusChangedEmitter.fire(status);
1475
+ if (status === 'dead') {
1476
+ this.dispose();
1477
+ }
1478
+ }
1479
+
1480
+ /**
1481
+ * Send pending messages to the kernel.
1482
+ */
1483
+ }, {
1484
+ key: "_sendPending",
1485
+ value: function _sendPending() {
1486
+ // We check to make sure we are still connected each time. For
1487
+ // example, if a websocket buffer overflows, it may close, so we should
1488
+ // stop sending messages.
1489
+ while (this.connectionStatus === 'connected' && this._kernelSession !== RESTARTING_KERNEL_SESSION && this._pendingMessages.length > 0) {
1490
+ this._sendMessage(this._pendingMessages[0], false);
1491
+
1492
+ // We shift the message off the queue after the message is sent so that
1493
+ // if there is an exception, the message is still pending.
1494
+ this._pendingMessages.shift();
1495
+ }
1496
+ }
1497
+
1498
+ /**
1499
+ * Clear the internal state.
1500
+ */
1501
+ }, {
1502
+ key: "_clearKernelState",
1503
+ value: function _clearKernelState() {
1504
+ this._kernelSession = '';
1505
+ this._pendingMessages = [];
1506
+ this._futures.forEach(function (future) {
1507
+ future.dispose();
1508
+ });
1509
+ this._comms.forEach(function (comm) {
1510
+ comm.dispose();
1511
+ });
1512
+ this._msgChain = Promise.resolve();
1513
+ this._futures = new Map();
1514
+ this._comms = new Map();
1515
+ this._displayIdToParentIds.clear();
1516
+ this._msgIdToDisplayIds.clear();
1517
+ }
1518
+
1519
+ /**
1520
+ * Check to make sure it is okay to proceed to handle a message.
1521
+ *
1522
+ * #### Notes
1523
+ * Because we handle messages asynchronously, before a message is handled the
1524
+ * kernel might be disposed or restarted (and have a different session id).
1525
+ * This function throws an error in each of these cases. This is meant to be
1526
+ * called at the start of an asynchronous message handler to cancel message
1527
+ * processing if the message no longer is valid.
1528
+ */
1529
+ }, {
1530
+ key: "_assertCurrentMessage",
1531
+ value: function _assertCurrentMessage(msg) {
1532
+ this._errorIfDisposed();
1533
+ if (msg.header.session !== this._kernelSession) {
1534
+ throw new Error("Canceling handling of old message: ".concat(msg.header.msg_type));
1535
+ }
1536
+ }
1537
+
1538
+ /**
1539
+ * Handle a `comm_open` kernel message.
1540
+ */
1541
+ }, {
1542
+ key: "_handleCommOpen",
1543
+ value: function () {
1544
+ var _handleCommOpen2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(msg) {
1545
+ var _this6 = this;
1546
+ var content, comm, target;
1547
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
1548
+ while (1) switch (_context9.prev = _context9.next) {
1549
+ case 0:
1550
+ this._assertCurrentMessage(msg);
1551
+ content = msg.content;
1552
+ comm = new CommHandler(content.target_name, content.comm_id, this, function () {
1553
+ _this6._unregisterComm(content.comm_id);
1554
+ });
1555
+ this._comms.set(content.comm_id, comm);
1556
+ _context9.prev = 4;
1557
+ _context9.next = 7;
1558
+ return Private.loadObject(content.target_name, content.target_module, this._targetRegistry);
1559
+ case 7:
1560
+ target = _context9.sent;
1561
+ _context9.next = 10;
1562
+ return target(comm, msg);
1563
+ case 10:
1564
+ _context9.next = 17;
1565
+ break;
1566
+ case 12:
1567
+ _context9.prev = 12;
1568
+ _context9.t0 = _context9["catch"](4);
1569
+ // Close the comm asynchronously. We cannot block message processing on
1570
+ // kernel messages to wait for another kernel message.
1571
+ comm.close();
1572
+ console.error('Exception opening new comm');
1573
+ throw _context9.t0;
1574
+ case 17:
1575
+ case "end":
1576
+ return _context9.stop();
1577
+ }
1578
+ }, _callee9, this, [[4, 12]]);
1579
+ }));
1580
+ function _handleCommOpen(_x6) {
1581
+ return _handleCommOpen2.apply(this, arguments);
1582
+ }
1583
+ return _handleCommOpen;
1584
+ }()
1585
+ /**
1586
+ * Handle 'comm_close' kernel message.
1587
+ */
1588
+ }, {
1589
+ key: "_handleCommClose",
1590
+ value: function () {
1591
+ var _handleCommClose2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(msg) {
1592
+ var content, comm, onClose;
1593
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
1594
+ while (1) switch (_context10.prev = _context10.next) {
1595
+ case 0:
1596
+ this._assertCurrentMessage(msg);
1597
+ content = msg.content;
1598
+ comm = this._comms.get(content.comm_id);
1599
+ if (comm) {
1600
+ _context10.next = 6;
1601
+ break;
1602
+ }
1603
+ console.error('Comm not found for comm id ' + content.comm_id);
1604
+ return _context10.abrupt("return");
1605
+ case 6:
1606
+ this._unregisterComm(comm.commId);
1607
+ onClose = comm.onClose;
1608
+ if (!onClose) {
1609
+ _context10.next = 11;
1610
+ break;
1611
+ }
1612
+ _context10.next = 11;
1613
+ return onClose(msg);
1614
+ case 11:
1615
+ comm.dispose();
1616
+ case 12:
1617
+ case "end":
1618
+ return _context10.stop();
1619
+ }
1620
+ }, _callee10, this);
1621
+ }));
1622
+ function _handleCommClose(_x7) {
1623
+ return _handleCommClose2.apply(this, arguments);
1624
+ }
1625
+ return _handleCommClose;
1626
+ }()
1627
+ /**
1628
+ * Handle a 'comm_msg' kernel message.
1629
+ */
1630
+ }, {
1631
+ key: "_handleCommMsg",
1632
+ value: function () {
1633
+ var _handleCommMsg2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(msg) {
1634
+ var content, comm, onMsg;
1635
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
1636
+ while (1) switch (_context11.prev = _context11.next) {
1637
+ case 0:
1638
+ this._assertCurrentMessage(msg);
1639
+ content = msg.content;
1640
+ comm = this._comms.get(content.comm_id);
1641
+ if (comm) {
1642
+ _context11.next = 5;
1643
+ break;
1644
+ }
1645
+ return _context11.abrupt("return");
1646
+ case 5:
1647
+ onMsg = comm.onMsg;
1648
+ if (!onMsg) {
1649
+ _context11.next = 9;
1650
+ break;
1651
+ }
1652
+ _context11.next = 9;
1653
+ return onMsg(msg);
1654
+ case 9:
1655
+ case "end":
1656
+ return _context11.stop();
1657
+ }
1658
+ }, _callee11, this);
1659
+ }));
1660
+ function _handleCommMsg(_x8) {
1661
+ return _handleCommMsg2.apply(this, arguments);
1662
+ }
1663
+ return _handleCommMsg;
1664
+ }()
1665
+ /**
1666
+ * Unregister a comm instance.
1667
+ */
1668
+ }, {
1669
+ key: "_unregisterComm",
1670
+ value: function _unregisterComm(commId) {
1671
+ this._comms.delete(commId);
1672
+ }
1673
+ }, {
1674
+ key: "_updateConnectionStatus",
1675
+ value:
1676
+ /**
1677
+ * Handle connection status changes.
1678
+ */
1679
+ function _updateConnectionStatus(connectionStatus) {
1680
+ var _this7 = this;
1681
+ if (this._connectionStatus === connectionStatus) {
1682
+ return;
1683
+ }
1684
+ this._connectionStatus = connectionStatus;
1685
+
1686
+ // If we are not 'connecting', reset any reconnection attempts.
1687
+ if (connectionStatus !== 'connecting') {
1688
+ this._reconnectAttempt = 0;
1689
+ clearTimeout(this._reconnectTimeout);
1690
+ }
1691
+ if (this.status !== 'dead') {
1692
+ if (connectionStatus === 'connected') {
1693
+ var restarting = this._kernelSession === RESTARTING_KERNEL_SESSION;
1694
+
1695
+ // Send a kernel info request to make sure we send at least one
1696
+ // message to get kernel status back. Always request kernel info
1697
+ // first, to get kernel status back and ensure iopub is fully
1698
+ // established. If we are restarting, this message will skip the queue
1699
+ // and be sent immediately.
1700
+ var p = this.requestKernelInfo();
1701
+
1702
+ // Send any pending messages after the kernelInfo resolves, or after a
1703
+ // timeout as a failsafe.
1704
+
1705
+ var sendPendingCalled = false;
1706
+ var timeoutHandle = null;
1707
+ var sendPendingOnce = function sendPendingOnce() {
1708
+ if (sendPendingCalled) {
1709
+ return;
1710
+ }
1711
+ sendPendingCalled = true;
1712
+ if (restarting && _this7._kernelSession === RESTARTING_KERNEL_SESSION) {
1713
+ // We were restarting and a message didn't arrive to set the
1714
+ // session, but we just assume the restart succeeded and send any
1715
+ // pending messages.
1716
+
1717
+ // FIXME: it would be better to retry the kernel_info_request here
1718
+ _this7._kernelSession = '';
1719
+ }
1720
+ if (timeoutHandle) {
1721
+ clearTimeout(timeoutHandle);
1722
+ }
1723
+ if (_this7._pendingMessages.length > 0) {
1724
+ _this7._sendPending();
1725
+ }
1726
+ };
1727
+ void p.then(sendPendingOnce);
1728
+ // FIXME: if sent while zmq subscriptions are not established,
1729
+ // kernelInfo may not resolve, so use a timeout to ensure we don't hang forever.
1730
+ // It may be preferable to retry kernelInfo rather than give up after one timeout.
1731
+ timeoutHandle = setTimeout(sendPendingOnce, KERNEL_INFO_TIMEOUT);
1732
+ } else {
1733
+ // If the connection is down, then we do not know what is happening
1734
+ // with the kernel, so set the status to unknown.
1735
+ this._updateStatus('unknown');
1736
+ }
1737
+ }
1738
+
1739
+ // Notify others that the connection status changed.
1740
+ this.connectionStatusChangedEmitter.fire(connectionStatus);
1741
+ }
1742
+ }, {
1743
+ key: "_handleMessage",
1744
+ value: function () {
1745
+ var _handleMessage2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(msg) {
1746
+ var _this8 = this;
1747
+ var handled, _msg$content$transien, _transient, displayId, _this$_futures3, parentHeader, future, owned, executionState;
1748
+ return _regeneratorRuntime().wrap(function _callee13$(_context13) {
1749
+ while (1) switch (_context13.prev = _context13.next) {
1750
+ case 0:
1751
+ handled = false; // Check to see if we have a display_id we need to reroute.
1752
+ if (!(msg.parent_header && msg.channel === 'iopub' && (isDisplayDataMsg(msg) || isUpdateDisplayDataMsg(msg) || isExecuteResultMsg(msg)))) {
1753
+ _context13.next = 9;
1754
+ break;
1755
+ }
1756
+ // display_data messages may re-route based on their display_id.
1757
+ _transient = (_msg$content$transien = msg.content.transient) !== null && _msg$content$transien !== void 0 ? _msg$content$transien : {};
1758
+ displayId = _transient['display_id'];
1759
+ if (!displayId) {
1760
+ _context13.next = 9;
1761
+ break;
1762
+ }
1763
+ _context13.next = 7;
1764
+ return this._handleDisplayId(displayId, msg);
1765
+ case 7:
1766
+ handled = _context13.sent;
1767
+ // The await above may make this message out of date, so check again.
1768
+ this._assertCurrentMessage(msg);
1769
+ case 9:
1770
+ if (!(!handled && msg.parent_header)) {
1771
+ _context13.next = 20;
1772
+ break;
1773
+ }
1774
+ parentHeader = msg.parent_header;
1775
+ future = (_this$_futures3 = this._futures) === null || _this$_futures3 === void 0 ? void 0 : _this$_futures3.get(parentHeader.msg_id);
1776
+ if (!future) {
1777
+ _context13.next = 18;
1778
+ break;
1779
+ }
1780
+ _context13.next = 15;
1781
+ return future.handleMsg(msg);
1782
+ case 15:
1783
+ this._assertCurrentMessage(msg);
1784
+ _context13.next = 20;
1785
+ break;
1786
+ case 18:
1787
+ // If the message was sent by us and was not iopub, it is orphaned.
1788
+ owned = parentHeader.session === this.clientId;
1789
+ if (msg.channel !== 'iopub' && owned) {
1790
+ this.unhandledMessageEmitter.fire(msg);
1791
+ }
1792
+ case 20:
1793
+ if (!(msg.channel === 'iopub')) {
1794
+ _context13.next = 42;
1795
+ break;
1796
+ }
1797
+ _context13.t0 = msg.header.msg_type;
1798
+ _context13.next = _context13.t0 === 'status' ? 24 : _context13.t0 === 'comm_open' ? 28 : _context13.t0 === 'comm_msg' ? 32 : _context13.t0 === 'comm_close' ? 36 : 40;
1799
+ break;
1800
+ case 24:
1801
+ // Updating the status is synchronous, and we call no async user code
1802
+ executionState = msg.content.execution_state;
1803
+ if (executionState === 'restarting') {
1804
+ // The kernel has been auto-restarted by the server. After
1805
+ // processing for this message is completely done, we want to
1806
+ // handle this restart, so we don't await, but instead schedule
1807
+ // the work as a microtask (i.e., in a promise resolution). We
1808
+ // schedule this here so that it comes before any microtasks that
1809
+ // might be scheduled in the status signal emission below.
1810
+ void Promise.resolve().then( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
1811
+ return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1812
+ while (1) switch (_context12.prev = _context12.next) {
1813
+ case 0:
1814
+ _this8._updateStatus('autorestarting');
1815
+ _this8._clearKernelState();
1816
+
1817
+ // We must reconnect since the kernel connection information may have
1818
+ // changed, and the server only refreshes its zmq connection when a new
1819
+ // websocket is opened.
1820
+ _context12.next = 4;
1821
+ return _this8.reconnect();
1822
+ case 4:
1823
+ return _context12.abrupt("return");
1824
+ case 5:
1825
+ case "end":
1826
+ return _context12.stop();
1827
+ }
1828
+ }, _callee12);
1829
+ })));
1830
+ }
1831
+ this._updateStatus(executionState);
1832
+ return _context13.abrupt("break", 41);
1833
+ case 28:
1834
+ if (!this.handleComms) {
1835
+ _context13.next = 31;
1836
+ break;
1837
+ }
1838
+ _context13.next = 31;
1839
+ return this._handleCommOpen(msg);
1840
+ case 31:
1841
+ return _context13.abrupt("break", 41);
1842
+ case 32:
1843
+ if (!this.handleComms) {
1844
+ _context13.next = 35;
1845
+ break;
1846
+ }
1847
+ _context13.next = 35;
1848
+ return this._handleCommMsg(msg);
1849
+ case 35:
1850
+ return _context13.abrupt("break", 41);
1851
+ case 36:
1852
+ if (!this.handleComms) {
1853
+ _context13.next = 39;
1854
+ break;
1855
+ }
1856
+ _context13.next = 39;
1857
+ return this._handleCommClose(msg);
1858
+ case 39:
1859
+ return _context13.abrupt("break", 41);
1860
+ case 40:
1861
+ return _context13.abrupt("break", 41);
1862
+ case 41:
1863
+ // If the message was a status dead message, we might have disposed ourselves.
1864
+ if (!this.isDisposed) {
1865
+ this._assertCurrentMessage(msg);
1866
+ // the message wouldn't be emitted if we were disposed anyway.
1867
+ this.iopubMessageEmitter.fire(msg);
1868
+ }
1869
+ case 42:
1870
+ case "end":
1871
+ return _context13.stop();
1872
+ }
1873
+ }, _callee13, this);
1874
+ }));
1875
+ function _handleMessage(_x9) {
1876
+ return _handleMessage2.apply(this, arguments);
1877
+ }
1878
+ return _handleMessage;
1879
+ }()
1880
+ /**
1881
+ * Attempt a connection if we have not exhausted connection attempts.
1882
+ */
1883
+ }, {
1884
+ key: "_reconnect",
1885
+ value: function _reconnect() {
1886
+ this._errorIfDisposed();
1887
+
1888
+ // Clear any existing reconnection attempt
1889
+ clearTimeout(this._reconnectTimeout);
1890
+
1891
+ // Update the connection status and schedule a possible reconnection.
1892
+ if (this._reconnectAttempt < this._reconnectLimit) {
1893
+ this._updateConnectionStatus('connecting');
1894
+
1895
+ // The first reconnect attempt should happen immediately, and subsequent
1896
+ // attempts should pick a random number in a growing range so that we
1897
+ // don't overload the server with synchronized reconnection attempts
1898
+ // across multiple kernels.
1899
+ var timeout = Private.getRandomIntInclusive(0, 1e3 * (Math.pow(2, this._reconnectAttempt) - 1));
1900
+ console.warn("Connection lost, reconnecting in ".concat(Math.floor(timeout / 1000), " seconds."));
1901
+ // Try reconnection with subprotocols if the server had supported them.
1902
+ // Otherwise, try reconnection without subprotocols.
1903
+ var useProtocols = this._selectedProtocol !== '' ? true : false;
1904
+ this._reconnectTimeout = setTimeout(this._createSocket, timeout, useProtocols);
1905
+ this._reconnectAttempt += 1;
1906
+ } else {
1907
+ this._updateConnectionStatus('disconnected');
1908
+ }
1909
+
1910
+ // Clear the websocket event handlers and the socket itself.
1911
+ this._clearSocket();
1912
+ }
1913
+
1914
+ /**
1915
+ * Utility function to throw an error if this instance is disposed.
1916
+ */
1917
+ }, {
1918
+ key: "_errorIfDisposed",
1919
+ value: function _errorIfDisposed() {
1920
+ if (this.isDisposed) {
1921
+ throw new Error('Kernel connection is disposed');
1922
+ }
1923
+ }
1924
+ }, {
1925
+ key: "hasPendingInput",
1926
+ get: function get() {
1927
+ return this._hasPendingInput;
1928
+ },
1929
+ set: function set(value) {
1930
+ this._hasPendingInput = value;
1931
+ this.pendingInputEmitter.fire(value);
1932
+ }
1933
+ }]);
1934
+ return KernelConnection;
1935
+ }(), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "kernelSpecRestAPI", [_dec2], {
1936
+ configurable: true,
1937
+ enumerable: true,
1938
+ writable: true,
1939
+ initializer: null
1940
+ }), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "kernelRestAPI", [_dec3], {
1941
+ configurable: true,
1942
+ enumerable: true,
1943
+ writable: true,
1944
+ initializer: null
1945
+ }), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, "libroKernelConnectionFactory", [_dec4], {
1946
+ configurable: true,
1947
+ enumerable: true,
1948
+ writable: true,
1949
+ initializer: null
1950
+ }), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, "_status", [_dec5], {
1951
+ configurable: true,
1952
+ enumerable: true,
1953
+ writable: true,
1954
+ initializer: function initializer() {
1955
+ return 'unknown';
1956
+ }
1957
+ })), _class2)) || _class);