@jupyterlite/pyodide-kernel 0.6.0-alpha.2 → 0.6.0-alpha.4

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../node_modules/@lumino/algorithm/src/array.ts", "../../../node_modules/@lumino/algorithm/src/chain.ts", "../../../node_modules/@lumino/algorithm/src/empty.ts", "../../../node_modules/@lumino/algorithm/src/enumerate.ts", "../../../node_modules/@lumino/algorithm/src/filter.ts", "../../../node_modules/@lumino/algorithm/src/find.ts", "../../../node_modules/@lumino/algorithm/src/iter.ts", "../../../node_modules/@lumino/algorithm/src/map.ts", "../../../node_modules/@lumino/algorithm/src/range.ts", "../../../node_modules/@lumino/algorithm/src/reduce.ts", "../../../node_modules/@lumino/algorithm/src/repeat.ts", "../../../node_modules/@lumino/algorithm/src/retro.ts", "../../../node_modules/@lumino/algorithm/src/sort.ts", "../../../node_modules/@lumino/algorithm/src/stride.ts", "../../../node_modules/@lumino/algorithm/src/string.ts", "../../../node_modules/@lumino/algorithm/src/take.ts", "../../../node_modules/@lumino/algorithm/src/zip.ts", "../../../node_modules/@lumino/coreutils/src/json.ts", "../../../node_modules/@lumino/coreutils/src/mime.ts", "../../../node_modules/@lumino/coreutils/src/plugins.ts", "../../../node_modules/@lumino/coreutils/src/promise.ts", "../../../node_modules/@lumino/coreutils/src/token.ts", "../../../node_modules/@lumino/coreutils/src/random.ts", "../../../node_modules/@lumino/coreutils/src/random.browser.ts", "../../../node_modules/@lumino/coreutils/src/uuid.ts", "../../../node_modules/@lumino/coreutils/src/uuid.browser.ts", "../../../node_modules/@lumino/signaling/src/index.ts", "../../../node_modules/@jupyterlab/coreutils/src/activitymonitor.ts", "../../../node_modules/@jupyterlab/coreutils/src/lru.ts", "../../../node_modules/@jupyterlab/coreutils/src/markdowncodeblocks.ts", "../../../node_modules/minimist/index.js", "../../../node_modules/path-browserify/index.js", "../../../node_modules/requires-port/index.js", "../../../node_modules/querystringify/index.js", "../../../node_modules/url-parse/index.js", "../../../node_modules/@jupyterlab/coreutils/src/url.ts", "../../../node_modules/@jupyterlab/coreutils/src/pageconfig.ts", "../../../node_modules/@jupyterlab/coreutils/src/path.ts", "../../../node_modules/@jupyterlab/coreutils/src/signal.ts", "../../../node_modules/@jupyterlab/coreutils/src/text.ts", "../../../node_modules/@jupyterlab/coreutils/src/time.ts", "../../../node_modules/@jupyterlab/coreutils/src/index.ts", "../../../node_modules/mime/Mime.js", "../../../node_modules/mime/types/standard.js", "../../../node_modules/mime/types/other.js", "../../../node_modules/mime/index.js", "../../../node_modules/@jupyterlite/contents/src/tokens.ts", "../../../node_modules/@jupyterlite/contents/src/contents.ts", "../../../node_modules/@jupyterlite/contents/src/emscripten.ts", "../../../node_modules/@jupyterlite/contents/src/drivefs.ts", "../../../node_modules/@jupyterlite/contents/src/drivecontents.ts", "../../../node_modules/@jupyterlite/contents/src/broadcast.ts", "../../../node_modules/@jupyterlite/contents/src/index.ts", "../../../node_modules/proxy-target/esm/types.js", "../../../node_modules/coincident/esm/channel.js", "../../../node_modules/proxy-target/esm/traps.js", "../../../node_modules/coincident/esm/bridge.js", "../../../node_modules/coincident/esm/index.js", "../src/coincident.worker.ts", "../src/worker.ts"],
4
- "sourcesContent": ["// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * The namespace for array-specific algorithms.\n */\nexport namespace ArrayExt {\n /**\n * Find the index of the first occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.firstIndexOf(data, 'red'); // -1\n * ArrayExt.firstIndexOf(data, 'one'); // 0\n * ArrayExt.firstIndexOf(data, 'one', 1); // 4\n * ArrayExt.firstIndexOf(data, 'two', 2); // -1\n * ArrayExt.firstIndexOf(data, 'two', 2, 1); // 1\n * ```\n */\n export function firstIndexOf<T>(\n array: ArrayLike<T>,\n value: T,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let span: number;\n if (stop < start) {\n span = stop + 1 + (n - start);\n } else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n\n /**\n * Find the index of the last occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.lastIndexOf(data, 'red'); // -1\n * ArrayExt.lastIndexOf(data, 'one'); // 4\n * ArrayExt.lastIndexOf(data, 'one', 1); // 0\n * ArrayExt.lastIndexOf(data, 'two', 0); // -1\n * ArrayExt.lastIndexOf(data, 'two', 0, 1); // 1\n * ```\n */\n export function lastIndexOf<T>(\n array: ArrayLike<T>,\n value: T,\n start = -1,\n stop = 0\n ): number {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let span: number;\n if (start < stop) {\n span = start + 1 + (n - stop);\n } else {\n span = start - stop + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start - i + n) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n\n /**\n * Find the index of the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstIndex(data, isEven); // 1\n * ArrayExt.findFirstIndex(data, isEven, 4); // 5\n * ArrayExt.findFirstIndex(data, isEven, 6); // -1\n * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1\n * ```\n */\n export function findFirstIndex<T>(\n array: ArrayLike<T>,\n fn: (value: T, index: number) => boolean,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let span: number;\n if (stop < start) {\n span = stop + 1 + (n - start);\n } else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n\n /**\n * Find the index of the last value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastIndex(data, isEven); // 5\n * ArrayExt.findLastIndex(data, isEven, 4); // 3\n * ArrayExt.findLastIndex(data, isEven, 0); // -1\n * ArrayExt.findLastIndex(data, isEven, 0, 1); // 5\n * ```\n */\n export function findLastIndex<T>(\n array: ArrayLike<T>,\n fn: (value: T, index: number) => boolean,\n start = -1,\n stop = 0\n ): number {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let d: number;\n if (start < stop) {\n d = start + 1 + (n - stop);\n } else {\n d = start - stop + 1;\n }\n for (let i = 0; i < d; ++i) {\n let j = (start - i + n) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n\n /**\n * Find the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstValue(data, isEven); // 2\n * ArrayExt.findFirstValue(data, isEven, 2); // 4\n * ArrayExt.findFirstValue(data, isEven, 6); // undefined\n * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2\n * ```\n */\n export function findFirstValue<T>(\n array: ArrayLike<T>,\n fn: (value: T, index: number) => boolean,\n start = 0,\n stop = -1\n ): T | undefined {\n let index = findFirstIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n\n /**\n * Find the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The last matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastValue(data, isEven); // 2\n * ArrayExt.findLastValue(data, isEven, 4); // 4\n * ArrayExt.findLastValue(data, isEven, 0); // undefined\n * ArrayExt.findLastValue(data, isEven, 0, 1); // 2\n * ```\n */\n export function findLastValue<T>(\n array: ArrayLike<T>,\n fn: (value: T, index: number) => boolean,\n start = -1,\n stop = 0\n ): T | undefined {\n let index = findLastIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n\n /**\n * Find the index of the first element which compares `>=` to a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>=` to the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.lowerBound(data, 0, numberCmp); // 0\n * ArrayExt.lowerBound(data, 6, numberCmp); // 3\n * ArrayExt.lowerBound(data, 7, numberCmp); // 3\n * ArrayExt.lowerBound(data, -1, numberCmp); // 0\n * ArrayExt.lowerBound(data, 10, numberCmp); // 6\n * ```\n */\n export function lowerBound<T, U>(\n array: ArrayLike<T>,\n value: U,\n fn: (element: T, value: U) => number,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) < 0) {\n begin = middle + 1;\n span -= half + 1;\n } else {\n span = half;\n }\n }\n return begin;\n }\n\n /**\n * Find the index of the first element which compares `>` than a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>` than the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.upperBound(data, 0, numberCmp); // 1\n * ArrayExt.upperBound(data, 6, numberCmp); // 3\n * ArrayExt.upperBound(data, 7, numberCmp); // 5\n * ArrayExt.upperBound(data, -1, numberCmp); // 0\n * ArrayExt.upperBound(data, 10, numberCmp); // 6\n * ```\n */\n export function upperBound<T, U>(\n array: ArrayLike<T>,\n value: U,\n fn: (element: T, value: U) => number,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) > 0) {\n span = half;\n } else {\n begin = middle + 1;\n span -= half + 1;\n }\n }\n return begin;\n }\n\n /**\n * Test whether two arrays are shallowly equal.\n *\n * @param a - The first array-like object to compare.\n *\n * @param b - The second array-like object to compare.\n *\n * @param fn - The comparison function to apply to the elements. It\n * should return `true` if the elements are \"equal\". The default\n * compares elements using strict `===` equality.\n *\n * @returns Whether the two arrays are shallowly equal.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * Modifying the length of the arrays while comparing.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let d1 = [0, 3, 4, 7, 7, 9];\n * let d2 = [0, 3, 4, 7, 7, 9];\n * let d3 = [42];\n * ArrayExt.shallowEqual(d1, d2); // true\n * ArrayExt.shallowEqual(d2, d3); // false\n * ```\n */\n export function shallowEqual<T>(\n a: ArrayLike<T>,\n b: ArrayLike<T>,\n fn?: (a: T, b: T) => boolean\n ): boolean {\n // Check for object identity first.\n if (a === b) {\n return true;\n }\n\n // Bail early if the lengths are different.\n if (a.length !== b.length) {\n return false;\n }\n\n // Compare each element for equality.\n for (let i = 0, n = a.length; i < n; ++i) {\n if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {\n return false;\n }\n }\n\n // The array are shallowly equal.\n return true;\n }\n\n /**\n * Create a slice of an array subject to an optional step.\n *\n * @param array - The array-like object of interest.\n *\n * @param options - The options for configuring the slice.\n *\n * @returns A new array with the specified values.\n *\n * @throws An exception if the slice `step` is `0`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start`, `stop`, or `step` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.slice(data); // [0, 3, 4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 2 }); // [4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 0, stop: 4 }); // [0, 3, 4, 7]\n * ArrayExt.slice(data, { step: 2 }); // [0, 4, 7]\n * ArrayExt.slice(data, { step: -1 }); // [9, 7, 7, 4, 3, 0]\n * ```\n */\n export function slice<T>(\n array: ArrayLike<T>,\n options: slice.IOptions = {}\n ): T[] {\n // Extract the options.\n let { start, stop, step } = options;\n\n // Set up the `step` value.\n if (step === undefined) {\n step = 1;\n }\n\n // Validate the step size.\n if (step === 0) {\n throw new Error('Slice `step` cannot be zero.');\n }\n\n // Look up the length of the array.\n let n = array.length;\n\n // Set up the `start` value.\n if (start === undefined) {\n start = step < 0 ? n - 1 : 0;\n } else if (start < 0) {\n start = Math.max(start + n, step < 0 ? -1 : 0);\n } else if (start >= n) {\n start = step < 0 ? n - 1 : n;\n }\n\n // Set up the `stop` value.\n if (stop === undefined) {\n stop = step < 0 ? -1 : n;\n } else if (stop < 0) {\n stop = Math.max(stop + n, step < 0 ? -1 : 0);\n } else if (stop >= n) {\n stop = step < 0 ? n - 1 : n;\n }\n\n // Compute the slice length.\n let length;\n if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {\n length = 0;\n } else if (step < 0) {\n length = Math.floor((stop - start + 1) / step + 1);\n } else {\n length = Math.floor((stop - start - 1) / step + 1);\n }\n\n // Compute the sliced result.\n let result: T[] = [];\n for (let i = 0; i < length; ++i) {\n result[i] = array[start + i * step];\n }\n\n // Return the result.\n return result;\n }\n\n /**\n * The namespace for the `slice` function statics.\n */\n export namespace slice {\n /**\n * The options for the `slice` function.\n */\n export interface IOptions {\n /**\n * The starting index of the slice, inclusive.\n *\n * Negative values are taken as an offset from the end\n * of the array.\n *\n * The default is `0` if `step > 0` else `n - 1`.\n */\n start?: number;\n\n /**\n * The stopping index of the slice, exclusive.\n *\n * Negative values are taken as an offset from the end\n * of the array.\n *\n * The default is `n` if `step > 0` else `-n - 1`.\n */\n stop?: number;\n\n /**\n * The step value for the slice.\n *\n * This must not be `0`.\n *\n * The default is `1`.\n */\n step?: number;\n }\n }\n\n /**\n * An array-like object which supports item assignment.\n */\n export type MutableArrayLike<T> = {\n readonly length: number;\n [index: number]: T;\n };\n\n /**\n * Move an element in an array from one index to another.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param fromIndex - The index of the element to move. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param toIndex - The target index of the element. Negative\n * values are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `fromIndex` or `toIndex` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.move(data, 1, 2); // [0, 2, 1, 3, 4]\n * ArrayExt.move(data, 4, 2); // [0, 2, 4, 1, 3]\n * ```\n */\n export function move<T>(\n array: MutableArrayLike<T>,\n fromIndex: number,\n toIndex: number\n ): void {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (fromIndex < 0) {\n fromIndex = Math.max(0, fromIndex + n);\n } else {\n fromIndex = Math.min(fromIndex, n - 1);\n }\n if (toIndex < 0) {\n toIndex = Math.max(0, toIndex + n);\n } else {\n toIndex = Math.min(toIndex, n - 1);\n }\n if (fromIndex === toIndex) {\n return;\n }\n let value = array[fromIndex];\n let d = fromIndex < toIndex ? 1 : -1;\n for (let i = fromIndex; i !== toIndex; i += d) {\n array[i] = array[i + d];\n }\n array[toIndex] = value;\n }\n\n /**\n * Reverse an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param start - The index of the first element in the range to be\n * reversed, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * reversed, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` index which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.reverse(data, 1, 3); // [0, 3, 2, 1, 4]\n * ArrayExt.reverse(data, 3); // [0, 3, 2, 4, 1]\n * ArrayExt.reverse(data); // [1, 4, 2, 3, 0]\n * ```\n */\n export function reverse<T>(\n array: MutableArrayLike<T>,\n start = 0,\n stop = -1\n ): void {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n while (start < stop) {\n let a = array[start];\n let b = array[stop];\n array[start++] = b;\n array[stop--] = a;\n }\n }\n\n /**\n * Rotate the elements of an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param delta - The amount of rotation to apply to the elements. A\n * positive value will rotate the elements to the left. A negative\n * value will rotate the elements to the right.\n *\n * @param start - The index of the first element in the range to be\n * rotated, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * rotated, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `delta`, `start`, or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.rotate(data, 2); // [2, 3, 4, 0, 1]\n * ArrayExt.rotate(data, -2); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 10); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 9); // [4, 0, 1, 2, 3]\n * ArrayExt.rotate(data, 2, 1, 3); // [4, 2, 0, 1, 3]\n * ```\n */\n export function rotate<T>(\n array: MutableArrayLike<T>,\n delta: number,\n start = 0,\n stop = -1\n ): void {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n if (start >= stop) {\n return;\n }\n let length = stop - start + 1;\n if (delta > 0) {\n delta = delta % length;\n } else if (delta < 0) {\n delta = ((delta % length) + length) % length;\n }\n if (delta === 0) {\n return;\n }\n let pivot = start + delta;\n reverse(array, start, pivot - 1);\n reverse(array, pivot, stop);\n reverse(array, start, stop);\n }\n\n /**\n * Fill an array with a static value.\n *\n * @param array - The mutable array-like object to fill.\n *\n * @param value - The static value to use to fill the array.\n *\n * @param start - The index of the first element in the range to be\n * filled, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * filled, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Notes\n * If `stop < start` the fill will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four'];\n * ArrayExt.fill(data, 'r'); // ['r', 'r', 'r', 'r']\n * ArrayExt.fill(data, 'g', 1); // ['r', 'g', 'g', 'g']\n * ArrayExt.fill(data, 'b', 2, 3); // ['r', 'g', 'b', 'b']\n * ArrayExt.fill(data, 'z', 3, 1); // ['z', 'z', 'b', 'z']\n * ```\n */\n export function fill<T>(\n array: MutableArrayLike<T>,\n value: T,\n start = 0,\n stop = -1\n ): void {\n let n = array.length;\n if (n === 0) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let span: number;\n if (stop < start) {\n span = stop + 1 + (n - start);\n } else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n array[(start + i) % n] = value;\n }\n }\n\n /**\n * Insert a value into an array at a specific index.\n *\n * @param array - The array of interest.\n *\n * @param index - The index at which to insert the value. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param value - The value to set at the specified index.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2];\n * ArrayExt.insert(data, 0, -1); // [-1, 0, 1, 2]\n * ArrayExt.insert(data, 2, 12); // [-1, 0, 12, 1, 2]\n * ArrayExt.insert(data, -1, 7); // [-1, 0, 12, 1, 7, 2]\n * ArrayExt.insert(data, 6, 19); // [-1, 0, 12, 1, 7, 2, 19]\n * ```\n */\n export function insert<T>(array: Array<T>, index: number, value: T): void {\n let n = array.length;\n if (index < 0) {\n index = Math.max(0, index + n);\n } else {\n index = Math.min(index, n);\n }\n for (let i = n; i > index; --i) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n }\n\n /**\n * Remove and return a value at a specific index in an array.\n *\n * @param array - The array of interest.\n *\n * @param index - The index of the value to remove. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The value at the specified index, or `undefined` if the\n * index is out of range.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeAt(data, 2); // 23\n * ArrayExt.removeAt(data, -2); // 12\n * ArrayExt.removeAt(data, 10); // undefined;\n * ```\n */\n export function removeAt<T>(array: Array<T>, index: number): T | undefined {\n let n = array.length;\n if (index < 0) {\n index += n;\n }\n if (index < 0 || index >= n) {\n return undefined;\n }\n let value = array[index];\n for (let i = index + 1; i < n; ++i) {\n array[i - 1] = array[i];\n }\n array.length = n - 1;\n return value;\n }\n\n /**\n * Remove the first occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstOf(data, 12); // 1\n * ArrayExt.removeFirstOf(data, 17); // -1\n * ArrayExt.removeFirstOf(data, 39, 3); // -1\n * ArrayExt.removeFirstOf(data, 39, 3, 2); // 2\n * ```\n */\n export function removeFirstOf<T>(\n array: Array<T>,\n value: T,\n start = 0,\n stop = -1\n ): number {\n let index = firstIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n\n /**\n * Remove the last occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastOf(data, 12); // 5\n * ArrayExt.removeLastOf(data, 17); // -1\n * ArrayExt.removeLastOf(data, 39, 2); // -1\n * ArrayExt.removeLastOf(data, 39, 2, 3); // 3\n * ```\n */\n export function removeLastOf<T>(\n array: Array<T>,\n value: T,\n start = -1,\n stop = 0\n ): number {\n let index = lastIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n\n /**\n * Remove all occurrences of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [14, 12, 23, 39, 14, 12, 19, 14];\n * ArrayExt.removeAllOf(data, 12); // 2\n * ArrayExt.removeAllOf(data, 17); // 0\n * ArrayExt.removeAllOf(data, 14, 1, 4); // 1\n * ```\n */\n export function removeAllOf<T>(\n array: Array<T>,\n value: T,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && array[i] === value) {\n count++;\n } else if (\n stop < start &&\n (i <= stop || i >= start) &&\n array[i] === value\n ) {\n count++;\n } else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n\n /**\n * Remove the first occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstWhere(data, isEven); // { index: 0, value: 0 }\n * ArrayExt.removeFirstWhere(data, isEven, 2); // { index: 3, value: 14 }\n * ArrayExt.removeFirstWhere(data, isEven, 4); // { index: -1, value: undefined }\n * ```\n */\n export function removeFirstWhere<T>(\n array: Array<T>,\n fn: (value: T, index: number) => boolean,\n start = 0,\n stop = -1\n ): { index: number; value: T | undefined } {\n let value: T | undefined;\n let index = findFirstIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n\n /**\n * Remove the last occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastWhere(data, isEven); // { index: 5, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2); // { index: 1, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2, 1); // { index: -1, value: undefined }\n * ```\n */\n export function removeLastWhere<T>(\n array: Array<T>,\n fn: (value: T, index: number) => boolean,\n start = -1,\n stop = 0\n ): { index: number; value: T | undefined } {\n let value: T | undefined;\n let index = findLastIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n\n /**\n * Remove all occurrences of values which match a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * function isNegative(value: number): boolean {\n * return value < 0;\n * }\n *\n * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];\n * ArrayExt.removeAllWhere(data, isEven); // 4\n * ArrayExt.removeAllWhere(data, isNegative, 0, 3); // 2\n * ```\n */\n export function removeAllWhere<T>(\n array: Array<T>,\n fn: (value: T, index: number) => boolean,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {\n count++;\n } else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {\n count++;\n } else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Chain together several iterables.\n *\n * @deprecated\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields the values of the iterables\n * in the order in which they are supplied.\n *\n * #### Example\n * ```typescript\n * import { chain } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = chain(data1, data2);\n *\n * Array.from(stream); // [1, 2, 3, 4, 5, 6]\n * ```\n */\nexport function* chain<T>(...objects: Iterable<T>[]): IterableIterator<T> {\n for (const object of objects) {\n yield* object;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Create an empty iterator.\n *\n * @returns A new iterator which yields nothing.\n *\n * #### Example\n * ```typescript\n * import { empty } from '@lumino/algorithm';\n *\n * let stream = empty<number>();\n *\n * Array.from(stream); // []\n * ```\n */\n// eslint-disable-next-line require-yield\nexport function* empty<T>(): IterableIterator<T> {\n return;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Enumerate an iterable object.\n *\n * @param object - The iterable object of interest.\n *\n * @param start - The starting enum value. The default is `0`.\n *\n * @returns An iterator which yields the enumerated values.\n *\n * #### Example\n * ```typescript\n * import { enumerate } from '@lumino/algorithm';\n *\n * let data = ['foo', 'bar', 'baz'];\n *\n * let stream = enumerate(data, 1);\n *\n * Array.from(stream); // [[1, 'foo'], [2, 'bar'], [3, 'baz']]\n * ```\n */\nexport function* enumerate<T>(\n object: Iterable<T>,\n start = 0\n): IterableIterator<[number, T]> {\n for (const value of object) {\n yield [start++, value];\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Filter an iterable for values which pass a test.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns An iterator which yields the values which pass the test.\n *\n * #### Example\n * ```typescript\n * import { filter } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = filter(data, value => value % 2 === 0);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nexport function* filter<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean\n): IterableIterator<T> {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n yield value;\n }\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Find the first value in an iterable which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { find } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * find(data, isCat).name; // 'fluffy'\n * ```\n */\nexport function find<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean\n): T | undefined {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return value;\n }\n }\n return undefined;\n}\n\n/**\n * Find the index of the first value which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { findIndex } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * findIndex(data, isCat); // 1\n * ```\n */\nexport function findIndex<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean\n): number {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return index - 1;\n }\n }\n return -1;\n}\n\n/**\n * Find the minimum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The minimum value in the iterable. If multiple values are\n * equivalent to the minimum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { min } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * min([7, 4, 0, 3, 9, 4], numberCmp); // 0\n * ```\n */\nexport function min<T>(\n object: Iterable<T>,\n fn: (first: T, second: T) => number\n): T | undefined {\n let result: T | undefined = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) < 0) {\n result = value;\n }\n }\n return result;\n}\n\n/**\n * Find the maximum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The maximum value in the iterable. If multiple values are\n * equivalent to the maximum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { max } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * max([7, 4, 0, 3, 9, 4], numberCmp); // 9\n * ```\n */\nexport function max<T>(\n object: Iterable<T>,\n fn: (first: T, second: T) => number\n): T | undefined {\n let result: T | undefined = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) > 0) {\n result = value;\n }\n }\n return result;\n}\n\n/**\n * Find the minimum and maximum values in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns A 2-tuple of the `[min, max]` values in the iterable. If\n * multiple values are equivalent, the left-most values are returned.\n * If the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { minmax } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * minmax([7, 4, 0, 3, 9, 4], numberCmp); // [0, 9]\n * ```\n */\nexport function minmax<T>(\n object: Iterable<T>,\n fn: (first: T, second: T) => number\n): [T, T] | undefined {\n let empty = true;\n let vmin: T;\n let vmax: T;\n for (const value of object) {\n if (empty) {\n vmin = value;\n vmax = value;\n empty = false;\n } else if (fn(value, vmin!) < 0) {\n vmin = value;\n } else if (fn(value, vmax!) > 0) {\n vmax = value;\n }\n }\n return empty ? undefined : [vmin!, vmax!];\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Create an array from an iterable of values.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new array of values from the given object.\n *\n * #### Example\n * ```typescript\n * import { toArray } from '@lumino/algorithm';\n *\n * let stream = [1, 2, 3, 4, 5, 6][Symbol.iterator]();\n *\n * toArray(stream); // [1, 2, 3, 4, 5, 6];\n * ```\n */\nexport function toArray<T>(object: Iterable<T>): T[] {\n return Array.from(object);\n}\n\n/**\n * Create an object from an iterable of key/value pairs.\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new object mapping keys to values.\n *\n * #### Example\n * ```typescript\n * import { toObject } from '@lumino/algorithm';\n *\n * let data: [string, number][] = [['one', 1], ['two', 2], ['three', 3]];\n *\n * toObject(data); // { one: 1, two: 2, three: 3 }\n * ```\n */\nexport function toObject<T>(object: Iterable<[string, T]>): {\n [key: string]: T;\n} {\n const result: { [key: string]: T } = {};\n for (const [key, value] of object) {\n result[key] = value;\n }\n return result;\n}\n\n/**\n * Invoke a function for each value in an iterable.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The callback function to invoke for each value.\n *\n * #### Notes\n * Iteration can be terminated early by returning `false` from the\n * callback function.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { each } from '@lumino/algorithm';\n *\n * let data = [5, 7, 0, -2, 9];\n *\n * each(data, value => { console.log(value); });\n * ```\n */\nexport function each<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean | void\n): void {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return;\n }\n }\n}\n\n/**\n * Test whether all values in an iterable satisfy a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if all values pass the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `false` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { every } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * every(data, value => value % 2 === 0); // false\n * every(data, value => value % 2 === 1); // true\n * ```\n */\nexport function every<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean\n): boolean {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Test whether any value in an iterable satisfies a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if any value passes the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `true` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { some } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * some(data, value => value === 7); // true\n * some(data, value => value === 3); // false\n * ```\n */\nexport function some<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean\n): boolean {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return true;\n }\n }\n return false;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Transform the values of an iterable with a mapping function.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The mapping function to invoke for each value.\n *\n * @returns An iterator which yields the transformed values.\n *\n * #### Example\n * ```typescript\n * import { map } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3];\n *\n * let stream = map(data, value => value * 2);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nexport function* map<T, U>(\n object: Iterable<T>,\n fn: (value: T, index: number) => U\n): IterableIterator<U> {\n let index = 0;\n for (const value of object) {\n yield fn(value, index++);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator of evenly spaced values.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns An iterator which produces evenly spaced values.\n *\n * #### Notes\n * In the single argument form of `range(stop)`, `start` defaults to\n * `0` and `step` defaults to `1`.\n *\n * In the two argument form of `range(start, stop)`, `step` defaults\n * to `1`.\n *\n * #### Example\n * ```typescript\n * import { range } from '@lumino/algorithm';\n *\n * let stream = range(2, 4);\n *\n * Array.from(stream); // [2, 3]\n * ```\n */\nexport function* range(\n start: number,\n stop?: number,\n step?: number\n): IterableIterator<number> {\n if (stop === undefined) {\n stop = start;\n start = 0;\n step = 1;\n } else if (step === undefined) {\n step = 1;\n }\n const length = Private.rangeLength(start, stop, step);\n for (let index = 0; index < length; index++) {\n yield start + step * index;\n }\n}\n\n/**\n * The namespace for the module implementation details.\n */\nnamespace Private {\n /**\n * Compute the effective length of a range.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns The number of steps need to traverse the range.\n */\n export function rangeLength(\n start: number,\n stop: number,\n step: number\n ): number {\n if (step === 0) {\n return Infinity;\n }\n if (start > stop && step > 0) {\n return 0;\n }\n if (start < stop && step < 0) {\n return 0;\n }\n return Math.ceil((stop - start) / step);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Summarize all values in an iterable using a reducer function.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The reducer function to invoke for each value.\n *\n * @param initial - The initial value to start accumulation.\n *\n * @returns The final accumulated value.\n *\n * #### Notes\n * The `reduce` function follows the conventions of `Array#reduce`.\n *\n * If the iterator is empty, an initial value is required. That value\n * will be used as the return value. If no initial value is provided,\n * an error will be thrown.\n *\n * If the iterator contains a single item and no initial value is\n * provided, the single item is used as the return value.\n *\n * Otherwise, the reducer is invoked for each element in the iterable.\n * If an initial value is not provided, the first element will be used\n * as the initial accumulated value.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { reduce } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5];\n *\n * let sum = reduce(data, (a, value) => a + value); // 15\n * ```\n */\nexport function reduce<T>(\n object: Iterable<T>,\n fn: (accumulator: T, value: T, index: number) => T\n): T;\nexport function reduce<T, U>(\n object: Iterable<T>,\n fn: (accumulator: U, value: T, index: number) => U,\n initial: U\n): U;\nexport function reduce<T>(\n object: Iterable<T>,\n fn: (accumulator: any, value: T, index: number) => any,\n initial?: unknown\n): any {\n // Setup the iterator and fetch the first value.\n const it = object[Symbol.iterator]();\n let index = 0;\n let first = it.next();\n\n // An empty iterator and no initial value is an error.\n if (first.done && initial === undefined) {\n throw new TypeError('Reduce of empty iterable with no initial value.');\n }\n\n // If the iterator is empty, return the initial value.\n if (first.done) {\n return initial;\n }\n\n // If the iterator has a single item and no initial value, the\n // reducer is not invoked and the first item is the return value.\n let second = it.next();\n if (second.done && initial === undefined) {\n return first.value;\n }\n\n // If iterator has a single item and an initial value is provided,\n // the reducer is invoked and that result is the return value.\n if (second.done) {\n return fn(initial, first.value, index++);\n }\n\n // Setup the initial accumlated value.\n let accumulator: any;\n if (initial === undefined) {\n accumulator = fn(first.value, second.value, index++);\n } else {\n accumulator = fn(fn(initial, first.value, index++), second.value, index++);\n }\n\n // Iterate the rest of the values, updating the accumulator.\n let next: IteratorResult<T>;\n while (!(next = it.next()).done) {\n accumulator = fn(accumulator, next.value, index++);\n }\n\n // Return the final accumulated value.\n return accumulator;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Create an iterator which repeats a value a number of times.\n *\n * @deprecated\n *\n * @param value - The value to repeat.\n *\n * @param count - The number of times to repeat the value.\n *\n * @returns A new iterator which repeats the specified value.\n *\n * #### Example\n * ```typescript\n * import { repeat } from '@lumino/algorithm';\n *\n * let stream = repeat(7, 3);\n *\n * Array.from(stream); // [7, 7, 7]\n * ```\n */\nexport function* repeat<T>(value: T, count: number): IterableIterator<T> {\n while (0 < count--) {\n yield value;\n }\n}\n\n/**\n * Create an iterator which yields a value a single time.\n *\n * @deprecated\n *\n * @param value - The value to wrap in an iterator.\n *\n * @returns A new iterator which yields the value a single time.\n *\n * #### Example\n * ```typescript\n * import { once } from '@lumino/algorithm';\n *\n * let stream = once(7);\n *\n * Array.from(stream); // [7]\n * ```\n */\nexport function* once<T>(value: T): IterableIterator<T> {\n yield value;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * An object which can produce a reverse iterator over its values.\n */\nexport interface IRetroable<T> {\n /**\n * Get a reverse iterator over the object's values.\n *\n * @returns An iterator which yields the object's values in reverse.\n */\n retro(): IterableIterator<T>;\n}\n\n/**\n * Create an iterator for a retroable object.\n *\n * @param object - The retroable or array-like object of interest.\n *\n * @returns An iterator which traverses the object's values in reverse.\n *\n * #### Example\n * ```typescript\n * import { retro } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = retro(data);\n *\n * Array.from(stream); // [6, 5, 4, 3, 2, 1]\n * ```\n */\nexport function* retro<T>(\n object: IRetroable<T> | ArrayLike<T>\n): IterableIterator<T> {\n if (typeof (object as IRetroable<T>).retro === 'function') {\n yield* (object as IRetroable<T>).retro();\n } else {\n for (let index = (object as ArrayLike<T>).length - 1; index > -1; index--) {\n yield (object as ArrayLike<T>)[index];\n }\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Topologically sort an iterable of edges.\n *\n * @param edges - The iterable object of edges to sort.\n * An edge is represented as a 2-tuple of `[fromNode, toNode]`.\n *\n * @returns The topologically sorted array of nodes.\n *\n * #### Notes\n * If a cycle is present in the graph, the cycle will be ignored and\n * the return value will be only approximately sorted.\n *\n * #### Example\n * ```typescript\n * import { topologicSort } from '@lumino/algorithm';\n *\n * let data = [\n * ['d', 'e'],\n * ['c', 'd'],\n * ['a', 'b'],\n * ['b', 'c']\n * ];\n *\n * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']\n * ```\n */\nexport function topologicSort<T>(edges: Iterable<[T, T]>): T[] {\n // Setup the shared sorting state.\n let sorted: T[] = [];\n let visited = new Set<T>();\n let graph = new Map<T, T[]>();\n\n // Add the edges to the graph.\n for (const edge of edges) {\n addEdge(edge);\n }\n\n // Visit each node in the graph.\n for (const [k] of graph) {\n visit(k);\n }\n\n // Return the sorted results.\n return sorted;\n\n // Add an edge to the graph.\n function addEdge(edge: [T, T]): void {\n let [fromNode, toNode] = edge;\n let children = graph.get(toNode);\n if (children) {\n children.push(fromNode);\n } else {\n graph.set(toNode, [fromNode]);\n }\n }\n\n // Recursively visit the node.\n function visit(node: T): void {\n if (visited.has(node)) {\n return;\n }\n visited.add(node);\n let children = graph.get(node);\n if (children) {\n for (const child of children) {\n visit(child);\n }\n }\n sorted.push(node);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Iterate over an iterable using a stepped increment.\n *\n * @param object - The iterable object of interest.\n *\n * @param step - The distance to step on each iteration. A value\n * of less than `1` will behave the same as a value of `1`.\n *\n * @returns An iterator which traverses the iterable step-wise.\n *\n * #### Example\n * ```typescript\n * import { stride } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = stride(data, 2);\n *\n * Array.from(stream); // [1, 3, 5];\n * ```\n */\nexport function* stride<T>(\n object: Iterable<T>,\n step: number\n): IterableIterator<T> {\n let count = 0;\n for (const value of object) {\n if (0 === count++ % step) {\n yield value;\n }\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * The namespace for string-specific algorithms.\n */\nexport namespace StringExt {\n /**\n * Find the indices of characters in a source text.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The matched indices, or `null` if there is no match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * In order for there to be a match, all of the characters in `query`\n * **must** appear in `source` in the order given by `query`.\n *\n * Characters are matched using strict `===` equality.\n */\n export function findIndices(\n source: string,\n query: string,\n start = 0\n ): number[] | null {\n let indices = new Array<number>(query.length);\n for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {\n j = source.indexOf(query[i], j);\n if (j === -1) {\n return null;\n }\n indices[i] = j;\n }\n return indices;\n }\n\n /**\n * The result of a string match function.\n */\n export interface IMatchResult {\n /**\n * A score which indicates the strength of the match.\n *\n * The documentation of a given match function should specify\n * whether a lower or higher score is a stronger match.\n */\n score: number;\n\n /**\n * The indices of the matched characters in the source text.\n *\n * The indices will appear in increasing order.\n */\n indices: number[];\n }\n\n /**\n * A string matcher which uses a sum-of-squares algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-squares approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The index of each\n * matching character is squared and added to the score. This means\n * that early and consecutive character matches are preferred, while\n * late matches are heavily penalized.\n */\n export function matchSumOfSquares(\n source: string,\n query: string,\n start = 0\n ): IMatchResult | null {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i] - start;\n score += j * j;\n }\n return { score, indices };\n }\n\n /**\n * A string matcher which uses a sum-of-deltas algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-deltas approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The delta between\n * the indices are summed to create the score. This means that groups\n * of matched characters are preferred, while fragmented matches are\n * penalized.\n */\n export function matchSumOfDeltas(\n source: string,\n query: string,\n start = 0\n ): IMatchResult | null {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n let last = start - 1;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i];\n score += j - last - 1;\n last = j;\n }\n return { score, indices };\n }\n\n /**\n * Highlight the matched characters of a source text.\n *\n * @param source - The text which should be highlighted.\n *\n * @param indices - The indices of the matched characters. They must\n * appear in increasing order and must be in bounds of the source.\n *\n * @param fn - The function to apply to the matched chunks.\n *\n * @returns An array of unmatched and highlighted chunks.\n */\n export function highlight<T>(\n source: string,\n indices: ReadonlyArray<number>,\n fn: (chunk: string) => T\n ): Array<string | T> {\n // Set up the result array.\n let result: Array<string | T> = [];\n\n // Set up the counter variables.\n let k = 0;\n let last = 0;\n let n = indices.length;\n\n // Iterator over each index.\n while (k < n) {\n // Set up the chunk indices.\n let i = indices[k];\n let j = indices[k];\n\n // Advance the right chunk index until it's non-contiguous.\n while (++k < n && indices[k] === j + 1) {\n j++;\n }\n\n // Extract the unmatched text.\n if (last < i) {\n result.push(source.slice(last, i));\n }\n\n // Extract and highlight the matched text.\n if (i < j + 1) {\n result.push(fn(source.slice(i, j + 1)));\n }\n\n // Update the last visited index.\n last = j + 1;\n }\n\n // Extract any remaining unmatched text.\n if (last < source.length) {\n result.push(source.slice(last));\n }\n\n // Return the highlighted result.\n return result;\n }\n\n /**\n * A 3-way string comparison function.\n *\n * @param a - The first string of interest.\n *\n * @param b - The second string of interest.\n *\n * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.\n */\n export function cmp(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Take a fixed number of items from an iterable.\n *\n * @param object - The iterable object of interest.\n *\n * @param count - The number of items to take from the iterable.\n *\n * @returns An iterator which yields the specified number of items\n * from the source iterable.\n *\n * #### Notes\n * The returned iterator will exhaust early if the source iterable\n * contains an insufficient number of items.\n *\n * #### Example\n * ```typescript\n * import { take } from '@lumino/algorithm';\n *\n * let stream = take([5, 4, 3, 2, 1, 0, -1], 3);\n *\n * Array.from(stream); // [5, 4, 3]\n * ```\n */\nexport function* take<T>(\n object: Iterable<T>,\n count: number\n): IterableIterator<T> {\n if (count < 1) {\n return;\n }\n const it = object[Symbol.iterator]();\n let item: IteratorResult<T>;\n while (0 < count-- && !(item = it.next()).done) {\n yield item.value;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nimport { every } from './iter';\n\n/**\n * Iterate several iterables in lockstep.\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields successive tuples of values where\n * each value is taken in turn from the provided iterables. It will\n * be as long as the shortest provided iterable.\n *\n * #### Example\n * ```typescript\n * import { zip } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = zip(data1, data2);\n *\n * Array.from(stream); // [[1, 4], [2, 5], [3, 6]]\n * ```\n */\nexport function* zip<T>(...objects: Iterable<T>[]): IterableIterator<T[]> {\n const iters = objects.map(obj => obj[Symbol.iterator]());\n let tuple = iters.map(it => it.next());\n for (; every(tuple, item => !item.done); tuple = iters.map(it => it.next())) {\n yield tuple.map(item => item.value);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * A type alias for a JSON primitive.\n */\nexport type JSONPrimitive = boolean | number | string | null;\n\n/**\n * A type alias for a JSON value.\n */\nexport type JSONValue = JSONPrimitive | JSONObject | JSONArray;\n\n/**\n * A type definition for a JSON object.\n */\nexport interface JSONObject {\n [key: string]: JSONValue;\n}\n\n/**\n * A type definition for a JSON array.\n */\nexport interface JSONArray extends Array<JSONValue> {}\n\n/**\n * A type definition for a readonly JSON object.\n */\nexport interface ReadonlyJSONObject {\n readonly [key: string]: ReadonlyJSONValue;\n}\n\n/**\n * A type definition for a readonly JSON array.\n */\nexport interface ReadonlyJSONArray extends ReadonlyArray<ReadonlyJSONValue> {}\n\n/**\n * A type alias for a readonly JSON value.\n */\nexport type ReadonlyJSONValue =\n | JSONPrimitive\n | ReadonlyJSONObject\n | ReadonlyJSONArray;\n\n/**\n * A type alias for a partial JSON value.\n *\n * Note: Partial here means that JSON object attributes can be `undefined`.\n */\nexport type PartialJSONValue =\n | JSONPrimitive\n | PartialJSONObject\n | PartialJSONArray;\n\n/**\n * A type definition for a partial JSON object.\n *\n * Note: Partial here means that the JSON object attributes can be `undefined`.\n */\nexport interface PartialJSONObject {\n [key: string]: PartialJSONValue | undefined;\n}\n\n/**\n * A type definition for a partial JSON array.\n *\n * Note: Partial here means that JSON object attributes can be `undefined`.\n */\nexport interface PartialJSONArray extends Array<PartialJSONValue> {}\n\n/**\n * A type definition for a readonly partial JSON object.\n *\n * Note: Partial here means that JSON object attributes can be `undefined`.\n */\nexport interface ReadonlyPartialJSONObject {\n readonly [key: string]: ReadonlyPartialJSONValue | undefined;\n}\n\n/**\n * A type definition for a readonly partial JSON array.\n *\n * Note: Partial here means that JSON object attributes can be `undefined`.\n */\nexport interface ReadonlyPartialJSONArray\n extends ReadonlyArray<ReadonlyPartialJSONValue> {}\n\n/**\n * A type alias for a readonly partial JSON value.\n *\n * Note: Partial here means that JSON object attributes can be `undefined`.\n */\nexport type ReadonlyPartialJSONValue =\n | JSONPrimitive\n | ReadonlyPartialJSONObject\n | ReadonlyPartialJSONArray;\n\n/**\n * The namespace for JSON-specific functions.\n */\nexport namespace JSONExt {\n /**\n * A shared frozen empty JSONObject\n */\n export const emptyObject = Object.freeze({}) as ReadonlyJSONObject;\n\n /**\n * A shared frozen empty JSONArray\n */\n export const emptyArray = Object.freeze([]) as ReadonlyJSONArray;\n\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n export function isPrimitive(\n value: ReadonlyPartialJSONValue\n ): value is JSONPrimitive {\n return (\n value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string'\n );\n }\n\n /**\n * Test whether a JSON value is an array.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a an array, `false` otherwise.\n */\n export function isArray(value: JSONValue): value is JSONArray;\n export function isArray(value: ReadonlyJSONValue): value is ReadonlyJSONArray;\n export function isArray(value: PartialJSONValue): value is PartialJSONArray;\n export function isArray(\n value: ReadonlyPartialJSONValue\n ): value is ReadonlyPartialJSONArray;\n export function isArray(value: ReadonlyPartialJSONValue): boolean {\n return Array.isArray(value);\n }\n\n /**\n * Test whether a JSON value is an object.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a an object, `false` otherwise.\n */\n export function isObject(value: JSONValue): value is JSONObject;\n export function isObject(\n value: ReadonlyJSONValue\n ): value is ReadonlyJSONObject;\n export function isObject(value: PartialJSONValue): value is PartialJSONObject;\n export function isObject(\n value: ReadonlyPartialJSONValue\n ): value is ReadonlyPartialJSONObject;\n export function isObject(value: ReadonlyPartialJSONValue): boolean {\n return !isPrimitive(value) && !isArray(value);\n }\n\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n export function deepEqual(\n first: ReadonlyPartialJSONValue,\n second: ReadonlyPartialJSONValue\n ): boolean {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(\n first as ReadonlyPartialJSONArray,\n second as ReadonlyPartialJSONArray\n );\n }\n\n // At this point, they must both be objects.\n return deepObjectEqual(\n first as ReadonlyPartialJSONObject,\n second as ReadonlyPartialJSONObject\n );\n }\n\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n export function deepCopy<T extends ReadonlyPartialJSONValue>(value: T): T {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(\n first: ReadonlyPartialJSONArray,\n second: ReadonlyPartialJSONArray\n ): boolean {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n\n // At this point, the arrays are equal.\n return true;\n }\n\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(\n first: ReadonlyPartialJSONObject,\n second: ReadonlyPartialJSONObject\n ): boolean {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n\n // At this point, the objects are equal.\n return true;\n }\n\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value: any): any {\n let result = new Array<any>(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value: any): any {\n let result: any = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\nexport class MimeData {\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types(): string[] {\n return this._types.slice();\n }\n\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime: string): boolean {\n return this._types.indexOf(mime) !== -1;\n }\n\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime: string): any | undefined {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime: string, data: unknown): void {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime: string): void {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n\n /**\n * Remove all data entries from the dataset.\n */\n clear(): void {\n this._types.length = 0;\n this._values.length = 0;\n }\n\n private _types: string[] = [];\n private _values: any[] = [];\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { topologicSort } from '@lumino/algorithm';\n\nimport { Token } from './token';\n\n/**\n * A user-defined application plugin.\n *\n * @typeParam T - The type for the application.\n *\n * @typeParam U - The service type, if the plugin `provides` one.\n *\n * #### Notes\n * Plugins are the foundation for building an extensible application.\n *\n * Plugins consume and provide \"services\", which are nothing more than\n * concrete implementations of interfaces and/or abstract types.\n *\n * Unlike regular imports and exports, which tie the service consumer\n * to a particular implementation of the service, plugins decouple the\n * service producer from the service consumer, allowing an application\n * to be easily customized by third parties in a type-safe fashion.\n */\nexport interface IPlugin<T, U> {\n /**\n * The human readable ID of the plugin.\n *\n * #### Notes\n * This must be unique within an application.\n */\n id: string;\n\n /**\n * Plugin description.\n *\n * #### Notes\n * This can be used to provide user documentation on the feature\n * brought by a plugin.\n */\n description?: string;\n\n /**\n * Whether the plugin should be activated on application start or waiting for being\n * required. If the value is 'defer' then the plugin should be activated only after\n * the application is started.\n *\n * #### Notes\n * The default is `false`.\n */\n autoStart?: boolean | 'defer';\n\n /**\n * The types of required services for the plugin, if any.\n *\n * #### Notes\n * These tokens correspond to the services that are required by\n * the plugin for correct operation.\n *\n * When the plugin is activated, a concrete instance of each type\n * will be passed to the `activate()` function, in the order they\n * are specified in the `requires` array.\n */\n requires?: Token<any>[];\n\n /**\n * The types of optional services for the plugin, if any.\n *\n * #### Notes\n * These tokens correspond to the services that can be used by the\n * plugin if available, but are not necessarily required.\n *\n * The optional services will be passed to the `activate()` function\n * following all required services. If an optional service cannot be\n * resolved, `null` will be passed in its place.\n */\n optional?: Token<any>[];\n\n /**\n * The type of service provided by the plugin, if any.\n *\n * #### Notes\n * This token corresponds to the service exported by the plugin.\n *\n * When the plugin is activated, the return value of `activate()`\n * is used as the concrete instance of the type.\n */\n provides?: Token<U> | null;\n\n /**\n * A function invoked to activate the plugin.\n *\n * @param app - The application provided by {@link PluginRegistry.application} .\n *\n * @param args - The services specified by the `requires` property.\n *\n * @returns The provided service, or a promise to the service.\n *\n * #### Notes\n * This function will be called whenever the plugin is manually\n * activated, or when another plugin being activated requires\n * the service it provides.\n *\n * This function will not be called unless all of its required\n * services can be fulfilled.\n */\n activate: (app: T, ...args: any[]) => U | Promise<U>;\n\n /**\n * A function invoked to deactivate the plugin.\n *\n * @param app - The application {@link PluginRegistry.application} .\n *\n * @param args - The services specified by the `requires` property.\n */\n deactivate?: ((app: T, ...args: any[]) => void | Promise<void>) | null;\n}\n\n/**\n * Plugin registry.\n */\nexport class PluginRegistry<T = any> {\n constructor(options: PluginRegistry.IOptions = {}) {\n if (options.validatePlugin) {\n console.info(\n 'Plugins may be rejected by the custom validation plugin method.'\n );\n this._validatePlugin = options.validatePlugin;\n }\n }\n\n /**\n * The application object.\n *\n * It will be provided as first argument to the\n * plugins activation and deactivation functions.\n *\n * It can only be set once.\n *\n * By default, it is `null`.\n */\n get application(): T {\n return this._application;\n }\n set application(v: T) {\n if (this._application !== null) {\n throw Error(\n 'PluginRegistry.application is already set. It cannot be overridden.'\n );\n }\n\n this._application = v;\n }\n\n /**\n * The list of all the deferred plugins.\n */\n get deferredPlugins(): string[] {\n return Array.from(this._plugins)\n .filter(([id, plugin]) => plugin.autoStart === 'defer')\n .map(([id, plugin]) => id);\n }\n\n /**\n * Get a plugin description.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns The plugin description.\n */\n getPluginDescription(id: string): string {\n return this._plugins.get(id)?.description ?? '';\n }\n\n /**\n * Test whether a plugin is registered with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns `true` if the plugin is registered, `false` otherwise.\n */\n hasPlugin(id: string): boolean {\n return this._plugins.has(id);\n }\n\n /**\n * Test whether a plugin is activated with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns `true` if the plugin is activated, `false` otherwise.\n */\n isPluginActivated(id: string): boolean {\n return this._plugins.get(id)?.activated ?? false;\n }\n\n /**\n * List the IDs of the plugins registered with the application.\n *\n * @returns A new array of the registered plugin IDs.\n */\n listPlugins(): string[] {\n return Array.from(this._plugins.keys());\n }\n\n /**\n * Register a plugin with the application.\n *\n * @param plugin - The plugin to register.\n *\n * #### Notes\n * An error will be thrown if a plugin with the same ID is already\n * registered, or if the plugin has a circular dependency.\n *\n * If the plugin provides a service which has already been provided\n * by another plugin, the new service will override the old service.\n */\n registerPlugin(plugin: IPlugin<T, any>): void {\n // Throw an error if the plugin ID is already registered.\n if (this._plugins.has(plugin.id)) {\n throw new TypeError(`Plugin '${plugin.id}' is already registered.`);\n }\n\n if (!this._validatePlugin(plugin)) {\n throw new Error(`Plugin '${plugin.id}' is not valid.`);\n }\n\n // Create the normalized plugin data.\n const data = Private.createPluginData(plugin);\n\n // Ensure the plugin does not cause a cyclic dependency.\n Private.ensureNoCycle(data, this._plugins, this._services);\n\n // Add the service token to the service map.\n if (data.provides) {\n this._services.set(data.provides, data.id);\n }\n\n // Add the plugin to the plugin map.\n this._plugins.set(data.id, data);\n }\n\n /**\n * Register multiple plugins with the application.\n *\n * @param plugins - The plugins to register.\n *\n * #### Notes\n * This calls `registerPlugin()` for each of the given plugins.\n */\n registerPlugins(plugins: IPlugin<T, any>[]): void {\n for (const plugin of plugins) {\n this.registerPlugin(plugin);\n }\n }\n\n /**\n * Deregister a plugin with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @param force - Whether to deregister the plugin even if it is active.\n */\n deregisterPlugin(id: string, force?: boolean): void {\n const plugin = this._plugins.get(id);\n if (!plugin) {\n return;\n }\n\n if (plugin.activated && !force) {\n throw new Error(`Plugin '${id}' is still active.`);\n }\n\n this._plugins.delete(id);\n }\n\n /**\n * Activate the plugin with the given ID.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns A promise which resolves when the plugin is activated\n * or rejects with an error if it cannot be activated.\n */\n async activatePlugin(id: string): Promise<void> {\n // Reject the promise if the plugin is not registered.\n const plugin = this._plugins.get(id);\n if (!plugin) {\n throw new ReferenceError(`Plugin '${id}' is not registered.`);\n }\n\n // Resolve immediately if the plugin is already activated.\n if (plugin.activated) {\n return;\n }\n\n // Return the pending resolver promise if it exists.\n if (plugin.promise) {\n return plugin.promise;\n }\n\n // Resolve the required services for the plugin.\n const required = plugin.requires.map(t => this.resolveRequiredService(t));\n\n // Resolve the optional services for the plugin.\n const optional = plugin.optional.map(t => this.resolveOptionalService(t));\n\n // Setup the resolver promise for the plugin.\n plugin.promise = Promise.all([...required, ...optional])\n .then(services =>\n plugin!.activate.apply(undefined, [this.application, ...services])\n )\n .then(service => {\n plugin!.service = service;\n plugin!.activated = true;\n plugin!.promise = null;\n })\n .catch(error => {\n plugin!.promise = null;\n throw error;\n });\n\n // Return the pending resolver promise.\n return plugin.promise;\n }\n\n /**\n * Activate all the deferred plugins.\n *\n * @returns A promise which will resolve when each plugin is activated\n * or rejects with an error if one cannot be activated.\n */\n async activatePlugins(\n kind: 'startUp' | 'defer',\n options: PluginRegistry.IStartOptions = {}\n ): Promise<void> {\n switch (kind) {\n case 'defer': {\n const promises = this.deferredPlugins\n .filter(pluginId => this._plugins.get(pluginId)!.autoStart)\n .map(pluginId => {\n return this.activatePlugin(pluginId);\n });\n await Promise.all(promises);\n break;\n }\n case 'startUp': {\n // Collect the ids of the startup plugins.\n const startups = Private.collectStartupPlugins(this._plugins, options);\n\n // Generate the activation promises.\n const promises = startups.map(async id => {\n try {\n return await this.activatePlugin(id);\n } catch (error) {\n console.error(`Plugin '${id}' failed to activate.`, error);\n }\n });\n await Promise.all(promises);\n break;\n }\n }\n }\n\n /**\n * Deactivate the plugin and its downstream dependents if and only if the\n * plugin and its dependents all support `deactivate`.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns A list of IDs of downstream plugins deactivated with this one.\n */\n async deactivatePlugin(id: string): Promise<string[]> {\n // Reject the promise if the plugin is not registered.\n const plugin = this._plugins.get(id);\n if (!plugin) {\n throw new ReferenceError(`Plugin '${id}' is not registered.`);\n }\n\n // Bail early if the plugin is not activated.\n if (!plugin.activated) {\n return [];\n }\n\n // Check that this plugin can deactivate.\n if (!plugin.deactivate) {\n throw new TypeError(`Plugin '${id}'#deactivate() method missing`);\n }\n\n // Find the optimal deactivation order for plugins downstream of this one.\n const manifest = Private.findDependents(id, this._plugins, this._services);\n const downstream = manifest.map(id => this._plugins.get(id)!);\n\n // Check that all downstream plugins can deactivate.\n for (const plugin of downstream) {\n if (!plugin.deactivate) {\n throw new TypeError(\n `Plugin ${plugin.id}#deactivate() method missing (depends on ${id})`\n );\n }\n }\n\n // Deactivate all downstream plugins.\n for (const plugin of downstream) {\n const services = [...plugin.requires, ...plugin.optional].map(service => {\n const id = this._services.get(service);\n return id ? this._plugins.get(id)!.service : null;\n });\n\n // Await deactivation so the next plugins only receive active services.\n await plugin.deactivate!(this.application, ...services);\n plugin.service = null;\n plugin.activated = false;\n }\n\n // Remove plugin ID and return manifest of deactivated plugins.\n manifest.pop();\n return manifest;\n }\n\n /**\n * Resolve a required service of a given type.\n *\n * @param token - The token for the service type of interest.\n *\n * @returns A promise which resolves to an instance of the requested\n * service, or rejects with an error if it cannot be resolved.\n *\n * #### Notes\n * Services are singletons. The same instance will be returned each\n * time a given service token is resolved.\n *\n * If the plugin which provides the service has not been activated,\n * resolving the service will automatically activate the plugin.\n *\n * User code will not typically call this method directly. Instead,\n * the required services for the user's plugins will be resolved\n * automatically when the plugin is activated.\n */\n async resolveRequiredService<U>(token: Token<U>): Promise<U> {\n // Reject the promise if there is no provider for the type.\n const id = this._services.get(token);\n if (!id) {\n throw new TypeError(`No provider for: ${token.name}.`);\n }\n\n // Activate the plugin if necessary.\n const plugin = this._plugins.get(id)!;\n if (!plugin.activated) {\n await this.activatePlugin(id);\n }\n\n return plugin.service;\n }\n\n /**\n * Resolve an optional service of a given type.\n *\n * @param token - The token for the service type of interest.\n *\n * @returns A promise which resolves to an instance of the requested\n * service, or `null` if it cannot be resolved.\n *\n * #### Notes\n * Services are singletons. The same instance will be returned each\n * time a given service token is resolved.\n *\n * If the plugin which provides the service has not been activated,\n * resolving the service will automatically activate the plugin.\n *\n * User code will not typically call this method directly. Instead,\n * the optional services for the user's plugins will be resolved\n * automatically when the plugin is activated.\n */\n async resolveOptionalService<U>(token: Token<U>): Promise<U | null> {\n // Resolve with `null` if there is no provider for the type.\n const id = this._services.get(token);\n if (!id) {\n return null;\n }\n\n // Activate the plugin if necessary.\n const plugin = this._plugins.get(id)!;\n if (!plugin.activated) {\n try {\n await this.activatePlugin(id);\n } catch (reason) {\n console.error(reason);\n return null;\n }\n }\n\n return plugin.service;\n }\n\n private _application: any = null;\n private _validatePlugin: (plugin: IPlugin<any, any>) => boolean = () => true;\n private _plugins = new Map<string, Private.IPluginData<T>>();\n private _services = new Map<Token<any>, string>();\n}\n\n/**\n * PluginRegistry namespace\n */\nexport namespace PluginRegistry {\n /**\n * PluginRegistry constructor options.\n */\n export interface IOptions {\n /**\n * Validate that a plugin is allowed to be registered.\n *\n * Default is `() => true`.\n *\n * @param plugin The plugin to validate\n * @returns Whether the plugin can be registered or not.\n *\n * #### Notes\n * We recommend you print a console message with the reason\n * a plugin is invalid.\n */\n validatePlugin?: (plugin: IPlugin<any, any>) => boolean;\n }\n\n /**\n * An options object for application startup.\n */\n export interface IStartOptions {\n /**\n * The plugins to activate on startup.\n *\n * #### Notes\n * These will be *in addition* to any `autoStart` plugins.\n */\n startPlugins?: string[];\n\n /**\n * The plugins to **not** activate on startup.\n *\n * #### Notes\n * This will override `startPlugins` and any `autoStart` plugins.\n */\n ignorePlugins?: string[];\n }\n}\n\n/**\n * The namespace for the module implementation details.\n */\nnamespace Private {\n /**\n * An object which holds the full application state for a plugin.\n */\n export interface IPluginData<T = any> {\n /**\n * The human readable ID of the plugin.\n */\n readonly id: string;\n\n /**\n * The description of the plugin.\n */\n readonly description: string;\n\n /**\n * Whether the plugin should be activated on application start or waiting for being\n * required. If the value is 'defer' then the plugin should be activated only after\n * the application is started.\n */\n readonly autoStart: boolean | 'defer';\n\n /**\n * The types of required services for the plugin, or `[]`.\n */\n readonly requires: Token<any>[];\n\n /**\n * The types of optional services for the the plugin, or `[]`.\n */\n readonly optional: Token<any>[];\n\n /**\n * The type of service provided by the plugin, or `null`.\n */\n readonly provides: Token<any> | null;\n\n /**\n * The function which activates the plugin.\n */\n readonly activate: (app: T, ...args: any[]) => any;\n\n /**\n * The optional function which deactivates the plugin.\n */\n readonly deactivate:\n | ((app: T, ...args: any[]) => void | Promise<void>)\n | null;\n\n /**\n * Whether the plugin has been activated.\n */\n activated: boolean;\n\n /**\n * The resolved service for the plugin, or `null`.\n */\n service: any | null;\n\n /**\n * The pending resolver promise, or `null`.\n */\n promise: Promise<void> | null;\n }\n\n class PluginData<T = any, U = any> implements IPluginData<T> {\n private _activated = false;\n private _promise: Promise<void> | null = null;\n private _service: U | null = null;\n\n constructor(plugin: IPlugin<T, U>) {\n this.id = plugin.id;\n this.description = plugin.description ?? '';\n this.activate = plugin.activate;\n this.deactivate = plugin.deactivate ?? null;\n this.provides = plugin.provides ?? null;\n this.autoStart = plugin.autoStart ?? false;\n this.requires = plugin.requires ? plugin.requires.slice() : [];\n this.optional = plugin.optional ? plugin.optional.slice() : [];\n }\n\n /**\n * The human readable ID of the plugin.\n */\n readonly id: string;\n\n /**\n * The description of the plugin.\n */\n readonly description: string;\n\n /**\n * Whether the plugin should be activated on application start or waiting for being\n * required. If the value is 'defer' then the plugin should be activated only after\n * the application is started.\n */\n readonly autoStart: boolean | 'defer';\n\n /**\n * The types of required services for the plugin, or `[]`.\n */\n readonly requires: Token<any>[];\n\n /**\n * The types of optional services for the the plugin, or `[]`.\n */\n readonly optional: Token<any>[];\n\n /**\n * The type of service provided by the plugin, or `null`.\n */\n readonly provides: Token<any> | null;\n\n /**\n * The function which activates the plugin.\n */\n readonly activate: (app: T, ...args: any[]) => any;\n\n /**\n * The optional function which deactivates the plugin.\n */\n readonly deactivate:\n | ((app: T, ...args: any[]) => void | Promise<void>)\n | null;\n\n /**\n * Whether the plugin has been activated.\n */\n get activated(): boolean {\n return this._activated;\n }\n set activated(a: boolean) {\n this._activated = a;\n }\n\n /**\n * The resolved service for the plugin, or `null`.\n */\n get service(): U | null {\n return this._service;\n }\n set service(s: U | null) {\n this._service = s;\n }\n\n /**\n * The pending resolver promise, or `null`.\n */\n get promise(): Promise<void> | null {\n return this._promise;\n }\n set promise(p: Promise<void> | null) {\n this._promise = p;\n }\n }\n\n /**\n * Create a normalized plugin data object for the given plugin.\n */\n export function createPluginData<T>(\n plugin: IPlugin<any, any>\n ): IPluginData<T> {\n return new PluginData(plugin);\n }\n\n /**\n * Ensure no cycle is present in the plugin resolution graph.\n *\n * If a cycle is detected, an error will be thrown.\n */\n export function ensureNoCycle(\n plugin: IPluginData,\n plugins: Map<string, IPluginData>,\n services: Map<Token<any>, string>\n ): void {\n const dependencies = [...plugin.requires, ...plugin.optional];\n const visit = (token: Token<any>): boolean => {\n if (token === plugin.provides) {\n return true;\n }\n const id = services.get(token);\n if (!id) {\n return false;\n }\n const visited = plugins.get(id)!;\n const dependencies = [...visited.requires, ...visited.optional];\n if (dependencies.length === 0) {\n return false;\n }\n trace.push(id);\n if (dependencies.some(visit)) {\n return true;\n }\n trace.pop();\n return false;\n };\n\n // Bail early if there cannot be a cycle.\n if (!plugin.provides || dependencies.length === 0) {\n return;\n }\n\n // Setup a stack to trace service resolution.\n const trace = [plugin.id];\n\n // Throw an exception if a cycle is present.\n if (dependencies.some(visit)) {\n throw new ReferenceError(`Cycle detected: ${trace.join(' -> ')}.`);\n }\n }\n\n /**\n * Find dependents in deactivation order.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @param plugins - The map containing all plugins.\n *\n * @param services - The map containing all services.\n *\n * @returns A list of dependent plugin IDs in order of deactivation\n *\n * #### Notes\n * The final item of the returned list is always the plugin of interest.\n */\n export function findDependents(\n id: string,\n plugins: Map<string, IPluginData>,\n services: Map<Token<any>, string>\n ): string[] {\n const edges = new Array<[string, string]>();\n const add = (id: string): void => {\n const plugin = plugins.get(id)!;\n // FIXME In the case of missing optional dependencies, we may consider\n // deactivating and reactivating the plugin without the missing service.\n const dependencies = [...plugin.requires, ...plugin.optional];\n edges.push(\n ...dependencies.reduce<[string, string][]>((acc, dep) => {\n const service = services.get(dep);\n if (service) {\n // An edge is oriented from dependent to provider.\n acc.push([id, service]);\n }\n return acc;\n }, [])\n );\n };\n\n for (const id of plugins.keys()) {\n add(id);\n }\n\n // Filter edges\n // - Get all packages that dependent on the package to be deactivated\n const newEdges = edges.filter(edge => edge[1] === id);\n let oldSize = 0;\n while (newEdges.length > oldSize) {\n const previousSize = newEdges.length;\n // Get all packages that dependent on packages that will be deactivated\n const packagesOfInterest = new Set(newEdges.map(edge => edge[0]));\n for (const poi of packagesOfInterest) {\n edges\n .filter(edge => edge[1] === poi)\n .forEach(edge => {\n // We check it is not already included to deal with circular dependencies\n if (!newEdges.includes(edge)) {\n newEdges.push(edge);\n }\n });\n }\n oldSize = previousSize;\n }\n\n const sorted = topologicSort(newEdges);\n const index = sorted.findIndex(candidate => candidate === id);\n\n if (index === -1) {\n return [id];\n }\n\n return sorted.slice(0, index + 1);\n }\n\n /**\n * Collect the IDs of the plugins to activate on startup.\n */\n export function collectStartupPlugins(\n plugins: Map<string, IPluginData>,\n options: PluginRegistry.IStartOptions\n ): string[] {\n // Create a set to hold the plugin IDs.\n const collection = new Set<string>();\n\n // Collect the auto-start (non deferred) plugins.\n for (const id of plugins.keys()) {\n if (plugins.get(id)!.autoStart === true) {\n collection.add(id);\n }\n }\n\n // Add the startup plugins.\n if (options.startPlugins) {\n for (const id of options.startPlugins) {\n collection.add(id);\n }\n }\n\n // Remove the ignored plugins.\n if (options.ignorePlugins) {\n for (const id of options.ignorePlugins) {\n collection.delete(id);\n }\n }\n\n // Return the collected startup plugins.\n return Array.from(collection);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\nexport class PromiseDelegate<T> {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise<T>((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n /**\n * The promise wrapped by the delegate.\n */\n readonly promise: Promise<T>;\n\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value: T | PromiseLike<T>): void {\n let resolve = this._resolve;\n resolve(value);\n }\n\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason: unknown): void {\n let reject = this._reject;\n reject(reason);\n }\n\n private _resolve: (value: T | PromiseLike<T>) => void;\n private _reject: (reason: any) => void;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\nexport class Token<T> {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name: string, description?: string) {\n this.name = name;\n this.description = description ?? '';\n this._tokenStructuralPropertyT = null!;\n }\n\n /**\n * Token purpose description.\n */\n readonly description?: string; // FIXME remove `?` for the next major version\n\n /**\n * The human readable name for the token.\n *\n * #### Notes\n * This can be useful for debugging and logging.\n */\n readonly name: string;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n private _tokenStructuralPropertyT: T;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n// Fallback\nexport function fallbackRandomValues(buffer: Uint8Array): void {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\nimport { fallbackRandomValues } from './random';\n\n// Declare ambient variables for `window` and `require` to avoid a\n// hard dependency on both. This package must run on node.\ndeclare let window: any;\n\n/**\n * The namespace for random number related functionality.\n */\nexport namespace Random {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n export const getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto: any =\n (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer: Uint8Array): void {\n return crypto.getRandomValues(buffer);\n };\n }\n\n // Fallback\n return fallbackRandomValues;\n })();\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\nexport function uuid4Factory(\n getRandomValues: (bytes: Uint8Array) => void\n): () => string {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n\n // Create a look up table from bytes to hex strings.\n const lut = new Array<string>(256);\n\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n\n // Return a function which generates the UUID.\n return function uuid4(): string {\n // Get a new batch of random values.\n getRandomValues(bytes);\n\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n\n // Assemble the UUID string.\n return (\n lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]\n );\n };\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nimport { Random } from './random.browser';\nimport { uuid4Factory } from './uuid';\n\n/**\n * The namespace for UUID related functionality.\n */\nexport namespace UUID {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n export const uuid4 = uuid4Factory(Random.getRandomValues);\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module signaling\n */\nimport { ArrayExt, find } from '@lumino/algorithm';\nimport { PromiseDelegate } from '@lumino/coreutils';\n\n/**\n * A type alias for a slot function.\n *\n * @param sender - The object emitting the signal.\n *\n * @param args - The args object emitted with the signal.\n *\n * #### Notes\n * A slot is invoked when a signal to which it is connected is emitted.\n */\nexport type Slot<T, U> = (sender: T, args: U) => void;\n\n/**\n * An object used for type-safe inter-object communication.\n *\n * #### Notes\n * Signals provide a type-safe implementation of the publish-subscribe\n * pattern. An object (publisher) declares which signals it will emit,\n * and consumers connect callbacks (subscribers) to those signals. The\n * subscribers are invoked whenever the publisher emits the signal.\n */\nexport interface ISignal<T, U> {\n /**\n * Connect a slot to the signal.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n *\n * #### Notes\n * Slots are invoked in the order in which they are connected.\n *\n * Signal connections are unique. If a connection already exists for\n * the given `slot` and `thisArg`, this method returns `false`.\n *\n * A newly connected slot will not be invoked until the next time the\n * signal is emitted, even if the slot is connected while the signal\n * is dispatching.\n */\n connect(slot: Slot<T, U>, thisArg?: any): boolean;\n\n /**\n * Disconnect a slot from the signal.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n *\n * #### Notes\n * If no connection exists for the given `slot` and `thisArg`, this\n * method returns `false`.\n *\n * A disconnected slot will no longer be invoked, even if the slot\n * is disconnected while the signal is dispatching.\n */\n disconnect(slot: Slot<T, U>, thisArg?: any): boolean;\n}\n\n/**\n * An object that is both a signal and an async iterable.\n */\nexport interface IStream<T, U> extends ISignal<T, U>, AsyncIterable<U> {}\n\n/**\n * A concrete implementation of `ISignal`.\n *\n * #### Example\n * ```typescript\n * import { ISignal, Signal } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get valueChanged: ISignal<this, number> {\n * return this._valueChanged;\n * }\n *\n * get value(): number {\n * return this._value;\n * }\n *\n * set value(value: number) {\n * if (value === this._value) {\n * return;\n * }\n * this._value = value;\n * this._valueChanged.emit(value);\n * }\n *\n * private _value = 0;\n * private _valueChanged = new Signal<this, number>(this);\n * }\n *\n * function logger(sender: SomeClass, value: number): void {\n * console.log(sender.name, value);\n * }\n *\n * let m1 = new SomeClass('foo');\n * let m2 = new SomeClass('bar');\n *\n * m1.valueChanged.connect(logger);\n * m2.valueChanged.connect(logger);\n *\n * m1.value = 42; // logs: foo 42\n * m2.value = 17; // logs: bar 17\n * ```\n */\nexport class Signal<T, U> implements ISignal<T, U> {\n /**\n * Construct a new signal.\n *\n * @param sender - The sender which owns the signal.\n */\n constructor(sender: T) {\n this.sender = sender;\n }\n\n /**\n * The sender which owns the signal.\n */\n readonly sender: T;\n\n /**\n * Connect a slot to the signal.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n connect(slot: Slot<T, U>, thisArg?: unknown): boolean {\n return Private.connect(this, slot, thisArg);\n }\n\n /**\n * Disconnect a slot from the signal.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n disconnect(slot: Slot<T, U>, thisArg?: unknown): boolean {\n return Private.disconnect(this, slot, thisArg);\n }\n\n /**\n * Emit the signal and invoke the connected slots.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n emit(args: U): void {\n Private.emit(this, args);\n }\n}\n\n/**\n * The namespace for the `Signal` class statics.\n */\nexport namespace Signal {\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n export function disconnectBetween(sender: unknown, receiver: unknown): void {\n Private.disconnectBetween(sender, receiver);\n }\n\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n export function disconnectSender(sender: unknown): void {\n Private.disconnectSender(sender);\n }\n\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n export function disconnectReceiver(receiver: unknown): void {\n Private.disconnectReceiver(receiver);\n }\n\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n export function disconnectAll(object: unknown): void {\n Private.disconnectAll(object);\n }\n\n /**\n * Clear all signal data associated with the given object.\n *\n * @param object - The object for which the data should be cleared.\n *\n * #### Notes\n * This removes all signal connections and any other signal data\n * associated with the object.\n */\n export function clearData(object: unknown): void {\n Private.disconnectAll(object);\n }\n\n /**\n * A type alias for the exception handler function.\n */\n export type ExceptionHandler = (err: Error) => void;\n\n /**\n * Get the signal exception handler.\n *\n * @returns The current exception handler.\n *\n * #### Notes\n * The default exception handler is `console.error`.\n */\n export function getExceptionHandler(): ExceptionHandler {\n return Private.exceptionHandler;\n }\n\n /**\n * Set the signal exception handler.\n *\n * @param handler - The function to use as the exception handler.\n *\n * @returns The old exception handler.\n *\n * #### Notes\n * The exception handler is invoked when a slot throws an exception.\n */\n export function setExceptionHandler(\n handler: ExceptionHandler\n ): ExceptionHandler {\n let old = Private.exceptionHandler;\n Private.exceptionHandler = handler;\n return old;\n }\n}\n\n/**\n * A concrete implementation of `IStream`.\n *\n * #### Example\n * ```typescript\n * import { IStream, Stream } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get pings(): IStream<this, string> {\n * return this._pings;\n * }\n *\n * ping(value: string) {\n * this._pings.emit(value);\n * }\n *\n * private _pings = new Stream<this, string>(this);\n * }\n *\n * let m1 = new SomeClass('foo');\n *\n * m1.pings.connect((_, value: string) => {\n * console.log('connect', value);\n * });\n *\n * void (async () => {\n * for await (const ping of m1.pings) {\n * console.log('iterator', ping);\n * }\n * })();\n *\n * m1.ping('alpha'); // logs: connect alpha\n * // logs: iterator alpha\n * m1.ping('beta'); // logs: connect beta\n * // logs: iterator beta\n * ```\n */\nexport class Stream<T, U> extends Signal<T, U> implements IStream<T, U> {\n /**\n * Return an async iterator that yields every emission.\n */\n async *[Symbol.asyncIterator](): AsyncIterableIterator<U> {\n let pending = this._pending;\n while (true) {\n try {\n const { args, next } = await pending.promise;\n pending = next;\n yield args;\n } catch (_) {\n return; // Any promise rejection stops the iterator.\n }\n }\n }\n\n /**\n * Emit the signal, invoke the connected slots, and yield the emission.\n *\n * @param args - The args to pass to the connected slots.\n */\n emit(args: U): void {\n const pending = this._pending;\n const next = (this._pending = new PromiseDelegate());\n pending.resolve({ args, next });\n super.emit(args);\n }\n\n /**\n * Stop the stream's async iteration.\n */\n stop(): void {\n this._pending.promise.catch(() => undefined);\n this._pending.reject('stop');\n this._pending = new PromiseDelegate();\n }\n\n private _pending: Private.Pending<U> = new PromiseDelegate();\n}\n\n/**\n * The namespace for the module implementation details.\n */\nnamespace Private {\n /**\n * A pending promise in a promise chain underlying a stream.\n */\n export type Pending<U> = PromiseDelegate<{ args: U; next: Pending<U> }>;\n\n /**\n * The signal exception handler function.\n */\n export let exceptionHandler: Signal.ExceptionHandler = (err: Error) => {\n console.error(err);\n };\n\n /**\n * Connect a slot to a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n export function connect<T, U>(\n signal: Signal<T, U>,\n slot: Slot<T, U>,\n thisArg?: unknown\n ): boolean {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n\n // Ensure the sender's array of receivers is created.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers) {\n receivers = [];\n receiversForSender.set(signal.sender, receivers);\n }\n\n // Bail if a matching connection already exists.\n if (findConnection(receivers, signal, slot, thisArg)) {\n return false;\n }\n\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n\n // Ensure the receiver's array of senders is created.\n let senders = sendersForReceiver.get(receiver);\n if (!senders) {\n senders = [];\n sendersForReceiver.set(receiver, senders);\n }\n\n // Create a new connection and add it to the end of each array.\n let connection = { signal, slot, thisArg };\n receivers.push(connection);\n senders.push(connection);\n\n // Indicate a successful connection.\n return true;\n }\n\n /**\n * Disconnect a slot from a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n export function disconnect<T, U>(\n signal: Signal<T, U>,\n slot: Slot<T, U>,\n thisArg?: unknown\n ): boolean {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n\n // Lookup the list of receivers, and bail if none exist.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return false;\n }\n\n // Bail if no matching connection exits.\n let connection = findConnection(receivers, signal, slot, thisArg);\n if (!connection) {\n return false;\n }\n\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n\n // Lookup the array of senders, which is now known to exist.\n let senders = sendersForReceiver.get(receiver)!;\n\n // Clear the connection and schedule cleanup of the arrays.\n connection.signal = null;\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n\n // Indicate a successful disconnection.\n return true;\n }\n\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n */\n export function disconnectBetween(sender: unknown, receiver: unknown): void {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n\n // Clear each connection between the sender and receiver.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n\n // Clear the connection if it matches the sender.\n if (connection.signal.sender === sender) {\n connection.signal = null;\n }\n }\n\n // Schedule a cleanup of the senders and receivers.\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n }\n\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n export function disconnectSender(sender: unknown): void {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n\n // Clear each receiver connection.\n for (const connection of receivers) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n\n // Choose the best object for the receiver.\n let receiver = connection.thisArg || connection.slot;\n\n // Clear the connection.\n connection.signal = null;\n\n // Cleanup the array of senders, which is now known to exist.\n scheduleCleanup(sendersForReceiver.get(receiver)!);\n }\n\n // Schedule a cleanup of the receivers.\n scheduleCleanup(receivers);\n }\n\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n */\n export function disconnectReceiver(receiver: unknown): void {\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n\n // Clear each sender connection.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n\n // Lookup the sender for the connection.\n let sender = connection.signal.sender;\n\n // Clear the connection.\n connection.signal = null;\n\n // Cleanup the array of receivers, which is now known to exist.\n scheduleCleanup(receiversForSender.get(sender)!);\n }\n\n // Schedule a cleanup of the list of senders.\n scheduleCleanup(senders);\n }\n\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n */\n export function disconnectAll(object: unknown): void {\n // Remove all connections where the given object is the sender.\n disconnectSender(object);\n // Remove all connections where the given object is the receiver.\n disconnectReceiver(object);\n }\n\n /**\n * Emit a signal and invoke its connected slots.\n *\n * @param signal - The signal of interest.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n export function emit<T, U>(signal: Signal<T, U>, args: U): void {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n\n // Invoke the slots for connections with a matching signal.\n // Any connections added during emission are not invoked.\n for (let i = 0, n = receivers.length; i < n; ++i) {\n let connection = receivers[i];\n if (connection.signal === signal) {\n invokeSlot(connection, args);\n }\n }\n }\n\n /**\n * An object which holds connection data.\n */\n interface IConnection {\n /**\n * The signal for the connection.\n *\n * A `null` signal indicates a cleared connection.\n */\n signal: Signal<any, any> | null;\n\n /**\n * The slot connected to the signal.\n */\n readonly slot: Slot<any, any>;\n\n /**\n * The `this` context for the slot.\n */\n readonly thisArg: any;\n }\n\n /**\n * A weak mapping of sender to array of receiver connections.\n */\n const receiversForSender = new WeakMap<any, IConnection[]>();\n\n /**\n * A weak mapping of receiver to array of sender connections.\n */\n const sendersForReceiver = new WeakMap<any, IConnection[]>();\n\n /**\n * A set of connection arrays which are pending cleanup.\n */\n const dirtySet = new Set<IConnection[]>();\n\n /**\n * A function to schedule an event loop callback.\n */\n const schedule = (() => {\n let ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n\n /**\n * Find a connection which matches the given parameters.\n */\n function findConnection(\n connections: IConnection[],\n signal: Signal<any, any>,\n slot: Slot<any, any>,\n thisArg: any\n ): IConnection | undefined {\n return find(\n connections,\n connection =>\n connection.signal === signal &&\n connection.slot === slot &&\n connection.thisArg === thisArg\n );\n }\n\n /**\n * Invoke a slot with the given parameters.\n *\n * The connection is assumed to be valid.\n *\n * Exceptions in the slot will be caught and logged.\n */\n function invokeSlot(connection: IConnection, args: any): void {\n let { signal, slot, thisArg } = connection;\n try {\n slot.call(thisArg, signal!.sender, args);\n } catch (err) {\n exceptionHandler(err);\n }\n }\n\n /**\n * Schedule a cleanup of a connection array.\n *\n * This will add the array to the dirty set and schedule a deferred\n * cleanup of the array contents. On cleanup, any connection with a\n * `null` signal will be removed from the array.\n */\n function scheduleCleanup(array: IConnection[]): void {\n if (dirtySet.size === 0) {\n schedule(cleanupDirtySet);\n }\n dirtySet.add(array);\n }\n\n /**\n * Cleanup the connection lists in the dirty set.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupDirtySet(): void {\n dirtySet.forEach(cleanupConnections);\n dirtySet.clear();\n }\n\n /**\n * Cleanup the dirty connections in a connections array.\n *\n * This will remove any connection with a `null` signal.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupConnections(connections: IConnection[]): void {\n ArrayExt.removeAllWhere(connections, isDeadConnection);\n }\n\n /**\n * Test whether a connection is dead.\n *\n * A dead connection has a `null` signal.\n */\n function isDeadConnection(connection: IConnection): boolean {\n return connection.signal === null;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { IDisposable } from '@lumino/disposable';\nimport { ISignal, Signal } from '@lumino/signaling';\n\n/**\n * A class that monitors activity on a signal.\n */\nexport class ActivityMonitor<Sender, Args> implements IDisposable {\n /**\n * Construct a new activity monitor.\n */\n constructor(options: ActivityMonitor.IOptions<Sender, Args>) {\n options.signal.connect(this._onSignalFired, this);\n this._timeout = options.timeout || 1000;\n }\n\n /**\n * A signal emitted when activity has ceased.\n */\n get activityStopped(): ISignal<\n this,\n ActivityMonitor.IArguments<Sender, Args>\n > {\n return this._activityStopped;\n }\n\n /**\n * The timeout associated with the monitor, in milliseconds.\n */\n get timeout(): number {\n return this._timeout;\n }\n set timeout(value: number) {\n this._timeout = value;\n }\n\n /**\n * Test whether the monitor has been disposed.\n *\n * #### Notes\n * This is a read-only property.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * Dispose of the resources used by the activity monitor.\n */\n dispose(): void {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n Signal.clearData(this);\n }\n\n /**\n * A signal handler for the monitored signal.\n */\n private _onSignalFired(sender: Sender, args: Args): void {\n clearTimeout(this._timer);\n this._sender = sender;\n this._args = args;\n this._timer = setTimeout(() => {\n this._activityStopped.emit({\n sender: this._sender,\n args: this._args\n });\n }, this._timeout);\n }\n\n private _timer: any = -1;\n private _timeout = -1;\n private _sender: Sender;\n private _args: Args;\n private _isDisposed = false;\n private _activityStopped = new Signal<\n this,\n ActivityMonitor.IArguments<Sender, Args>\n >(this);\n}\n\n/**\n * The namespace for `ActivityMonitor` statics.\n */\nexport namespace ActivityMonitor {\n /**\n * The options used to construct a new `ActivityMonitor`.\n */\n export interface IOptions<Sender, Args> {\n /**\n * The signal to monitor.\n */\n signal: ISignal<Sender, Args>;\n\n /**\n * The activity timeout in milliseconds.\n *\n * The default is 1 second.\n */\n timeout?: number;\n }\n\n /**\n * The argument object for an activity timeout.\n *\n */\n export interface IArguments<Sender, Args> {\n /**\n * The most recent sender object.\n */\n sender: Sender;\n\n /**\n * The most recent argument object.\n */\n args: Args;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nconst DEFAULT_MAX_SIZE = 128;\n\n/** A least-recently-used cache. */\nexport class LruCache<T, U> {\n protected _map = new Map<T, U>();\n protected _maxSize: number;\n\n constructor(options: LruCache.IOptions = {}) {\n this._maxSize = options?.maxSize || DEFAULT_MAX_SIZE;\n }\n\n /**\n * Return the current size of the cache.\n */\n get size() {\n return this._map.size;\n }\n\n /**\n * Clear the values in the cache.\n */\n clear() {\n this._map.clear();\n }\n\n /**\n * Get a value (or null) from the cache, pushing the item to the front of the cache.\n */\n get(key: T): U | null {\n const item = this._map.get(key) || null;\n if (item != null) {\n this._map.delete(key);\n this._map.set(key, item);\n }\n return item;\n }\n\n /**\n * Set a value in the cache, potentially evicting an old item.\n */\n set(key: T, value: U): void {\n if (this._map.size >= this._maxSize) {\n this._map.delete(this._map.keys().next().value);\n }\n this._map.set(key, value);\n }\n}\n\nexport namespace LruCache {\n export interface IOptions {\n maxSize?: number | null;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n/**\n * The namespace for code block functions which help\n * in extract code from markdown text\n */\nexport namespace MarkdownCodeBlocks {\n export const CODE_BLOCK_MARKER = '```';\n const markdownExtensions: string[] = [\n '.markdown',\n '.mdown',\n '.mkdn',\n '.md',\n '.mkd',\n '.mdwn',\n '.mdtxt',\n '.mdtext',\n '.text',\n '.txt',\n '.Rmd'\n ];\n\n export class MarkdownCodeBlock {\n startLine: number;\n endLine: number;\n code: string;\n constructor(startLine: number) {\n this.startLine = startLine;\n this.code = '';\n this.endLine = -1;\n }\n }\n\n /**\n * Check whether the given file extension is a markdown extension\n * @param extension - A file extension\n *\n * @returns true/false depending on whether this is a supported markdown extension\n */\n export function isMarkdown(extension: string): boolean {\n return markdownExtensions.indexOf(extension) > -1;\n }\n\n /**\n * Construct all code snippets from current text\n * (this could be potentially optimized if we can cache and detect differences)\n * @param text - A string to parse codeblocks from\n *\n * @returns An array of MarkdownCodeBlocks.\n */\n export function findMarkdownCodeBlocks(text: string): MarkdownCodeBlock[] {\n if (!text || text === '') {\n return [];\n }\n\n const lines = text.split('\\n');\n const codeBlocks: MarkdownCodeBlock[] = [];\n let currentBlock = null;\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n const lineContainsMarker = line.indexOf(CODE_BLOCK_MARKER) === 0;\n const constructingBlock = currentBlock != null;\n // Skip this line if it is not part of any code block and doesn't contain a marker.\n if (!lineContainsMarker && !constructingBlock) {\n continue;\n }\n\n // Check if we are already constructing a code block.\n if (!constructingBlock) {\n // Start constructing a new code block.\n currentBlock = new MarkdownCodeBlock(lineIndex);\n\n // Check whether this is a single line code block of the form ```a = 10```.\n const firstIndex = line.indexOf(CODE_BLOCK_MARKER);\n const lastIndex = line.lastIndexOf(CODE_BLOCK_MARKER);\n const isSingleLine = firstIndex !== lastIndex;\n if (isSingleLine) {\n currentBlock.code = line.substring(\n firstIndex + CODE_BLOCK_MARKER.length,\n lastIndex\n );\n currentBlock.endLine = lineIndex;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n }\n } else if (currentBlock) {\n if (lineContainsMarker) {\n // End of block, finish it up.\n currentBlock.endLine = lineIndex - 1;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n } else {\n // Append the current line.\n currentBlock.code += line + '\\n';\n }\n }\n }\n return codeBlocks;\n }\n}\n", "'use strict';\n\nfunction hasKey(obj, keys) {\n\tvar o = obj;\n\tkeys.slice(0, -1).forEach(function (key) {\n\t\to = o[key] || {};\n\t});\n\n\tvar key = keys[keys.length - 1];\n\treturn key in o;\n}\n\nfunction isNumber(x) {\n\tif (typeof x === 'number') { return true; }\n\tif ((/^0x[0-9a-f]+$/i).test(x)) { return true; }\n\treturn (/^[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(e[-+]?\\d+)?$/).test(x);\n}\n\nfunction isConstructorOrProto(obj, key) {\n\treturn (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__';\n}\n\nmodule.exports = function (args, opts) {\n\tif (!opts) { opts = {}; }\n\n\tvar flags = {\n\t\tbools: {},\n\t\tstrings: {},\n\t\tunknownFn: null,\n\t};\n\n\tif (typeof opts.unknown === 'function') {\n\t\tflags.unknownFn = opts.unknown;\n\t}\n\n\tif (typeof opts.boolean === 'boolean' && opts.boolean) {\n\t\tflags.allBools = true;\n\t} else {\n\t\t[].concat(opts.boolean).filter(Boolean).forEach(function (key) {\n\t\t\tflags.bools[key] = true;\n\t\t});\n\t}\n\n\tvar aliases = {};\n\n\tfunction aliasIsBoolean(key) {\n\t\treturn aliases[key].some(function (x) {\n\t\t\treturn flags.bools[x];\n\t\t});\n\t}\n\n\tObject.keys(opts.alias || {}).forEach(function (key) {\n\t\taliases[key] = [].concat(opts.alias[key]);\n\t\taliases[key].forEach(function (x) {\n\t\t\taliases[x] = [key].concat(aliases[key].filter(function (y) {\n\t\t\t\treturn x !== y;\n\t\t\t}));\n\t\t});\n\t});\n\n\t[].concat(opts.string).filter(Boolean).forEach(function (key) {\n\t\tflags.strings[key] = true;\n\t\tif (aliases[key]) {\n\t\t\t[].concat(aliases[key]).forEach(function (k) {\n\t\t\t\tflags.strings[k] = true;\n\t\t\t});\n\t\t}\n\t});\n\n\tvar defaults = opts.default || {};\n\n\tvar argv = { _: [] };\n\n\tfunction argDefined(key, arg) {\n\t\treturn (flags.allBools && (/^--[^=]+$/).test(arg))\n\t\t\t|| flags.strings[key]\n\t\t\t|| flags.bools[key]\n\t\t\t|| aliases[key];\n\t}\n\n\tfunction setKey(obj, keys, value) {\n\t\tvar o = obj;\n\t\tfor (var i = 0; i < keys.length - 1; i++) {\n\t\t\tvar key = keys[i];\n\t\t\tif (isConstructorOrProto(o, key)) { return; }\n\t\t\tif (o[key] === undefined) { o[key] = {}; }\n\t\t\tif (\n\t\t\t\to[key] === Object.prototype\n\t\t\t\t|| o[key] === Number.prototype\n\t\t\t\t|| o[key] === String.prototype\n\t\t\t) {\n\t\t\t\to[key] = {};\n\t\t\t}\n\t\t\tif (o[key] === Array.prototype) { o[key] = []; }\n\t\t\to = o[key];\n\t\t}\n\n\t\tvar lastKey = keys[keys.length - 1];\n\t\tif (isConstructorOrProto(o, lastKey)) { return; }\n\t\tif (\n\t\t\to === Object.prototype\n\t\t\t|| o === Number.prototype\n\t\t\t|| o === String.prototype\n\t\t) {\n\t\t\to = {};\n\t\t}\n\t\tif (o === Array.prototype) { o = []; }\n\t\tif (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') {\n\t\t\to[lastKey] = value;\n\t\t} else if (Array.isArray(o[lastKey])) {\n\t\t\to[lastKey].push(value);\n\t\t} else {\n\t\t\to[lastKey] = [o[lastKey], value];\n\t\t}\n\t}\n\n\tfunction setArg(key, val, arg) {\n\t\tif (arg && flags.unknownFn && !argDefined(key, arg)) {\n\t\t\tif (flags.unknownFn(arg) === false) { return; }\n\t\t}\n\n\t\tvar value = !flags.strings[key] && isNumber(val)\n\t\t\t? Number(val)\n\t\t\t: val;\n\t\tsetKey(argv, key.split('.'), value);\n\n\t\t(aliases[key] || []).forEach(function (x) {\n\t\t\tsetKey(argv, x.split('.'), value);\n\t\t});\n\t}\n\n\tObject.keys(flags.bools).forEach(function (key) {\n\t\tsetArg(key, defaults[key] === undefined ? false : defaults[key]);\n\t});\n\n\tvar notFlags = [];\n\n\tif (args.indexOf('--') !== -1) {\n\t\tnotFlags = args.slice(args.indexOf('--') + 1);\n\t\targs = args.slice(0, args.indexOf('--'));\n\t}\n\n\tfor (var i = 0; i < args.length; i++) {\n\t\tvar arg = args[i];\n\t\tvar key;\n\t\tvar next;\n\n\t\tif ((/^--.+=/).test(arg)) {\n\t\t\t// Using [\\s\\S] instead of . because js doesn't support the\n\t\t\t// 'dotall' regex modifier. See:\n\t\t\t// http://stackoverflow.com/a/1068308/13216\n\t\t\tvar m = arg.match(/^--([^=]+)=([\\s\\S]*)$/);\n\t\t\tkey = m[1];\n\t\t\tvar value = m[2];\n\t\t\tif (flags.bools[key]) {\n\t\t\t\tvalue = value !== 'false';\n\t\t\t}\n\t\t\tsetArg(key, value, arg);\n\t\t} else if ((/^--no-.+/).test(arg)) {\n\t\t\tkey = arg.match(/^--no-(.+)/)[1];\n\t\t\tsetArg(key, false, arg);\n\t\t} else if ((/^--.+/).test(arg)) {\n\t\t\tkey = arg.match(/^--(.+)/)[1];\n\t\t\tnext = args[i + 1];\n\t\t\tif (\n\t\t\t\tnext !== undefined\n\t\t\t\t&& !(/^(-|--)[^-]/).test(next)\n\t\t\t\t&& !flags.bools[key]\n\t\t\t\t&& !flags.allBools\n\t\t\t\t&& (aliases[key] ? !aliasIsBoolean(key) : true)\n\t\t\t) {\n\t\t\t\tsetArg(key, next, arg);\n\t\t\t\ti += 1;\n\t\t\t} else if ((/^(true|false)$/).test(next)) {\n\t\t\t\tsetArg(key, next === 'true', arg);\n\t\t\t\ti += 1;\n\t\t\t} else {\n\t\t\t\tsetArg(key, flags.strings[key] ? '' : true, arg);\n\t\t\t}\n\t\t} else if ((/^-[^-]+/).test(arg)) {\n\t\t\tvar letters = arg.slice(1, -1).split('');\n\n\t\t\tvar broken = false;\n\t\t\tfor (var j = 0; j < letters.length; j++) {\n\t\t\t\tnext = arg.slice(j + 2);\n\n\t\t\t\tif (next === '-') {\n\t\t\t\t\tsetArg(letters[j], next, arg);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') {\n\t\t\t\t\tsetArg(letters[j], next.slice(1), arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t(/[A-Za-z]/).test(letters[j])\n\t\t\t\t\t&& (/-?\\d+(\\.\\d*)?(e-?\\d+)?$/).test(next)\n\t\t\t\t) {\n\t\t\t\t\tsetArg(letters[j], next, arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (letters[j + 1] && letters[j + 1].match(/\\W/)) {\n\t\t\t\t\tsetArg(letters[j], arg.slice(j + 2), arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tsetArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tkey = arg.slice(-1)[0];\n\t\t\tif (!broken && key !== '-') {\n\t\t\t\tif (\n\t\t\t\t\targs[i + 1]\n\t\t\t\t\t&& !(/^(-|--)[^-]/).test(args[i + 1])\n\t\t\t\t\t&& !flags.bools[key]\n\t\t\t\t\t&& (aliases[key] ? !aliasIsBoolean(key) : true)\n\t\t\t\t) {\n\t\t\t\t\tsetArg(key, args[i + 1], arg);\n\t\t\t\t\ti += 1;\n\t\t\t\t} else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) {\n\t\t\t\t\tsetArg(key, args[i + 1] === 'true', arg);\n\t\t\t\t\ti += 1;\n\t\t\t\t} else {\n\t\t\t\t\tsetArg(key, flags.strings[key] ? '' : true, arg);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (!flags.unknownFn || flags.unknownFn(arg) !== false) {\n\t\t\t\targv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg));\n\t\t\t}\n\t\t\tif (opts.stopEarly) {\n\t\t\t\targv._.push.apply(argv._, args.slice(i + 1));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tObject.keys(defaults).forEach(function (k) {\n\t\tif (!hasKey(argv, k.split('.'))) {\n\t\t\tsetKey(argv, k.split('.'), defaults[k]);\n\n\t\t\t(aliases[k] || []).forEach(function (x) {\n\t\t\t\tsetKey(argv, x.split('.'), defaults[k]);\n\t\t\t});\n\t\t}\n\t});\n\n\tif (opts['--']) {\n\t\targv['--'] = notFlags.slice();\n\t} else {\n\t\tnotFlags.forEach(function (k) {\n\t\t\targv._.push(k);\n\t\t});\n\t}\n\n\treturn argv;\n};\n", "// 'path' module extracted from Node.js v8.11.1 (only the posix part)\n// transplited with Babel\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nfunction assertPath(path) {\n if (typeof path !== 'string') {\n throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));\n }\n}\n\n// Resolves . and .. elements in a path with directory names\nfunction normalizeStringPosix(path, allowAboveRoot) {\n var res = '';\n var lastSegmentLength = 0;\n var lastSlash = -1;\n var dots = 0;\n var code;\n for (var i = 0; i <= path.length; ++i) {\n if (i < path.length)\n code = path.charCodeAt(i);\n else if (code === 47 /*/*/)\n break;\n else\n code = 47 /*/*/;\n if (code === 47 /*/*/) {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n } else if (lastSlash !== i - 1 && dots === 2) {\n if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {\n if (res.length > 2) {\n var lastSlashIndex = res.lastIndexOf('/');\n if (lastSlashIndex !== res.length - 1) {\n if (lastSlashIndex === -1) {\n res = '';\n lastSegmentLength = 0;\n } else {\n res = res.slice(0, lastSlashIndex);\n lastSegmentLength = res.length - 1 - res.lastIndexOf('/');\n }\n lastSlash = i;\n dots = 0;\n continue;\n }\n } else if (res.length === 2 || res.length === 1) {\n res = '';\n lastSegmentLength = 0;\n lastSlash = i;\n dots = 0;\n continue;\n }\n }\n if (allowAboveRoot) {\n if (res.length > 0)\n res += '/..';\n else\n res = '..';\n lastSegmentLength = 2;\n }\n } else {\n if (res.length > 0)\n res += '/' + path.slice(lastSlash + 1, i);\n else\n res = path.slice(lastSlash + 1, i);\n lastSegmentLength = i - lastSlash - 1;\n }\n lastSlash = i;\n dots = 0;\n } else if (code === 46 /*.*/ && dots !== -1) {\n ++dots;\n } else {\n dots = -1;\n }\n }\n return res;\n}\n\nfunction _format(sep, pathObject) {\n var dir = pathObject.dir || pathObject.root;\n var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');\n if (!dir) {\n return base;\n }\n if (dir === pathObject.root) {\n return dir + base;\n }\n return dir + sep + base;\n}\n\nvar posix = {\n // path.resolve([from ...], to)\n resolve: function resolve() {\n var resolvedPath = '';\n var resolvedAbsolute = false;\n var cwd;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path;\n if (i >= 0)\n path = arguments[i];\n else {\n if (cwd === undefined)\n cwd = process.cwd();\n path = cwd;\n }\n\n assertPath(path);\n\n // Skip empty entries\n if (path.length === 0) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);\n\n if (resolvedAbsolute) {\n if (resolvedPath.length > 0)\n return '/' + resolvedPath;\n else\n return '/';\n } else if (resolvedPath.length > 0) {\n return resolvedPath;\n } else {\n return '.';\n }\n },\n\n normalize: function normalize(path) {\n assertPath(path);\n\n if (path.length === 0) return '.';\n\n var isAbsolute = path.charCodeAt(0) === 47 /*/*/;\n var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;\n\n // Normalize the path\n path = normalizeStringPosix(path, !isAbsolute);\n\n if (path.length === 0 && !isAbsolute) path = '.';\n if (path.length > 0 && trailingSeparator) path += '/';\n\n if (isAbsolute) return '/' + path;\n return path;\n },\n\n isAbsolute: function isAbsolute(path) {\n assertPath(path);\n return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;\n },\n\n join: function join() {\n if (arguments.length === 0)\n return '.';\n var joined;\n for (var i = 0; i < arguments.length; ++i) {\n var arg = arguments[i];\n assertPath(arg);\n if (arg.length > 0) {\n if (joined === undefined)\n joined = arg;\n else\n joined += '/' + arg;\n }\n }\n if (joined === undefined)\n return '.';\n return posix.normalize(joined);\n },\n\n relative: function relative(from, to) {\n assertPath(from);\n assertPath(to);\n\n if (from === to) return '';\n\n from = posix.resolve(from);\n to = posix.resolve(to);\n\n if (from === to) return '';\n\n // Trim any leading backslashes\n var fromStart = 1;\n for (; fromStart < from.length; ++fromStart) {\n if (from.charCodeAt(fromStart) !== 47 /*/*/)\n break;\n }\n var fromEnd = from.length;\n var fromLen = fromEnd - fromStart;\n\n // Trim any leading backslashes\n var toStart = 1;\n for (; toStart < to.length; ++toStart) {\n if (to.charCodeAt(toStart) !== 47 /*/*/)\n break;\n }\n var toEnd = to.length;\n var toLen = toEnd - toStart;\n\n // Compare paths to find the longest common path from root\n var length = fromLen < toLen ? fromLen : toLen;\n var lastCommonSep = -1;\n var i = 0;\n for (; i <= length; ++i) {\n if (i === length) {\n if (toLen > length) {\n if (to.charCodeAt(toStart + i) === 47 /*/*/) {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='/foo/bar'; to='/foo/bar/baz'\n return to.slice(toStart + i + 1);\n } else if (i === 0) {\n // We get here if `from` is the root\n // For example: from='/'; to='/foo'\n return to.slice(toStart + i);\n }\n } else if (fromLen > length) {\n if (from.charCodeAt(fromStart + i) === 47 /*/*/) {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='/foo/bar/baz'; to='/foo/bar'\n lastCommonSep = i;\n } else if (i === 0) {\n // We get here if `to` is the root.\n // For example: from='/foo'; to='/'\n lastCommonSep = 0;\n }\n }\n break;\n }\n var fromCode = from.charCodeAt(fromStart + i);\n var toCode = to.charCodeAt(toStart + i);\n if (fromCode !== toCode)\n break;\n else if (fromCode === 47 /*/*/)\n lastCommonSep = i;\n }\n\n var out = '';\n // Generate the relative path based on the path difference between `to`\n // and `from`\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {\n if (out.length === 0)\n out += '..';\n else\n out += '/..';\n }\n }\n\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts\n if (out.length > 0)\n return out + to.slice(toStart + lastCommonSep);\n else {\n toStart += lastCommonSep;\n if (to.charCodeAt(toStart) === 47 /*/*/)\n ++toStart;\n return to.slice(toStart);\n }\n },\n\n _makeLong: function _makeLong(path) {\n return path;\n },\n\n dirname: function dirname(path) {\n assertPath(path);\n if (path.length === 0) return '.';\n var code = path.charCodeAt(0);\n var hasRoot = code === 47 /*/*/;\n var end = -1;\n var matchedSlash = true;\n for (var i = path.length - 1; i >= 1; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n if (!matchedSlash) {\n end = i;\n break;\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n\n if (end === -1) return hasRoot ? '/' : '.';\n if (hasRoot && end === 1) return '//';\n return path.slice(0, end);\n },\n\n basename: function basename(path, ext) {\n if (ext !== undefined && typeof ext !== 'string') throw new TypeError('\"ext\" argument must be a string');\n assertPath(path);\n\n var start = 0;\n var end = -1;\n var matchedSlash = true;\n var i;\n\n if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {\n if (ext.length === path.length && ext === path) return '';\n var extIdx = ext.length - 1;\n var firstNonSlashEnd = -1;\n for (i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false;\n firstNonSlashEnd = i + 1;\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (code === ext.charCodeAt(extIdx)) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i;\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1;\n end = firstNonSlashEnd;\n }\n }\n }\n }\n\n if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;\n return path.slice(start, end);\n } else {\n for (i = path.length - 1; i >= 0; --i) {\n if (path.charCodeAt(i) === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n\n if (end === -1) return '';\n return path.slice(start, end);\n }\n },\n\n extname: function extname(path) {\n assertPath(path);\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n for (var i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n return '';\n }\n return path.slice(startDot, end);\n },\n\n format: function format(pathObject) {\n if (pathObject === null || typeof pathObject !== 'object') {\n throw new TypeError('The \"pathObject\" argument must be of type Object. Received type ' + typeof pathObject);\n }\n return _format('/', pathObject);\n },\n\n parse: function parse(path) {\n assertPath(path);\n\n var ret = { root: '', dir: '', base: '', ext: '', name: '' };\n if (path.length === 0) return ret;\n var code = path.charCodeAt(0);\n var isAbsolute = code === 47 /*/*/;\n var start;\n if (isAbsolute) {\n ret.root = '/';\n start = 1;\n } else {\n start = 0;\n }\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n var i = path.length - 1;\n\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n\n // Get non-dir info\n for (; i >= start; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n if (end !== -1) {\n if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);\n }\n } else {\n if (startPart === 0 && isAbsolute) {\n ret.name = path.slice(1, startDot);\n ret.base = path.slice(1, end);\n } else {\n ret.name = path.slice(startPart, startDot);\n ret.base = path.slice(startPart, end);\n }\n ret.ext = path.slice(startDot, end);\n }\n\n if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';\n\n return ret;\n },\n\n sep: '/',\n delimiter: ':',\n win32: null,\n posix: null\n};\n\nposix.posix = posix;\n\nmodule.exports = posix;\n", "'use strict';\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nmodule.exports = function required(port, protocol) {\n protocol = protocol.split(':')[0];\n port = +port;\n\n if (!port) return false;\n\n switch (protocol) {\n case 'http':\n case 'ws':\n return port !== 80;\n\n case 'https':\n case 'wss':\n return port !== 443;\n\n case 'ftp':\n return port !== 21;\n\n case 'gopher':\n return port !== 70;\n\n case 'file':\n return false;\n }\n\n return port !== 0;\n};\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , undef;\n\n/**\n * Decode a URI encoded string.\n *\n * @param {String} input The URI encoded string.\n * @returns {String|Null} The decoded string.\n * @api private\n */\nfunction decode(input) {\n try {\n return decodeURIComponent(input.replace(/\\+/g, ' '));\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Attempts to encode a given input.\n *\n * @param {String} input The string that needs to be encoded.\n * @returns {String|Null} The encoded string.\n * @api private\n */\nfunction encode(input) {\n try {\n return encodeURIComponent(input);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Simple query string parser.\n *\n * @param {String} query The query string that needs to be parsed.\n * @returns {Object}\n * @api public\n */\nfunction querystring(query) {\n var parser = /([^=?#&]+)=?([^&]*)/g\n , result = {}\n , part;\n\n while (part = parser.exec(query)) {\n var key = decode(part[1])\n , value = decode(part[2]);\n\n //\n // Prevent overriding of existing properties. This ensures that build-in\n // methods like `toString` or __proto__ are not overriden by malicious\n // querystrings.\n //\n // In the case if failed decoding, we want to omit the key/value pairs\n // from the result.\n //\n if (key === null || value === null || key in result) continue;\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Transform a query string to an object.\n *\n * @param {Object} obj Object that should be transformed.\n * @param {String} prefix Optional prefix.\n * @returns {String}\n * @api public\n */\nfunction querystringify(obj, prefix) {\n prefix = prefix || '';\n\n var pairs = []\n , value\n , key;\n\n //\n // Optionally prefix with a '?' if needed\n //\n if ('string' !== typeof prefix) prefix = '?';\n\n for (key in obj) {\n if (has.call(obj, key)) {\n value = obj[key];\n\n //\n // Edge cases where we actually want to encode the value to an empty\n // string instead of the stringified value.\n //\n if (!value && (value === null || value === undef || isNaN(value))) {\n value = '';\n }\n\n key = encode(key);\n value = encode(value);\n\n //\n // If we failed to encode the strings, we should bail out as we don't\n // want to add invalid strings to the query.\n //\n if (key === null || value === null) continue;\n pairs.push(key +'='+ value);\n }\n }\n\n return pairs.length ? prefix + pairs.join('&') : '';\n}\n\n//\n// Expose the module.\n//\nexports.stringify = querystringify;\nexports.parse = querystring;\n", "'use strict';\n\nvar required = require('requires-port')\n , qs = require('querystringify')\n , controlOrWhitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/\n , CRHTLF = /[\\n\\r\\t]/g\n , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//\n , port = /:\\d+$/\n , protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i\n , windowsDriveLetter = /^[a-zA-Z]:/;\n\n/**\n * Remove control characters and whitespace from the beginning of a string.\n *\n * @param {Object|String} str String to trim.\n * @returns {String} A new string representing `str` stripped of control\n * characters and whitespace from its beginning.\n * @public\n */\nfunction trimLeft(str) {\n return (str ? str : '').toString().replace(controlOrWhitespace, '');\n}\n\n/**\n * These are the parse rules for the URL parser, it informs the parser\n * about:\n *\n * 0. The char it Needs to parse, if it's a string it should be done using\n * indexOf, RegExp using exec and NaN means set as current value.\n * 1. The property we should set when parsing this value.\n * 2. Indication if it's backwards or forward parsing, when set as number it's\n * the value of extra chars that should be split off.\n * 3. Inherit from location if non existing in the parser.\n * 4. `toLowerCase` the resulting value.\n */\nvar rules = [\n ['#', 'hash'], // Extract from the back.\n ['?', 'query'], // Extract from the back.\n function sanitize(address, url) { // Sanitize what is left of the address\n return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n },\n ['/', 'pathname'], // Extract from the back.\n ['@', 'auth', 1], // Extract from the front.\n [NaN, 'host', undefined, 1, 1], // Set left over value.\n [/:(\\d*)$/, 'port', undefined, 1], // RegExp the back.\n [NaN, 'hostname', undefined, 1, 1] // Set left over.\n];\n\n/**\n * These properties should not be copied or inherited from. This is only needed\n * for all non blob URL's as a blob URL does not include a hash, only the\n * origin.\n *\n * @type {Object}\n * @private\n */\nvar ignore = { hash: 1, query: 1 };\n\n/**\n * The location object differs when your code is loaded through a normal page,\n * Worker or through a worker using a blob. And with the blobble begins the\n * trouble as the location object will contain the URL of the blob, not the\n * location of the page where our code is loaded in. The actual origin is\n * encoded in the `pathname` so we can thankfully generate a good \"default\"\n * location from it so we can generate proper relative URL's again.\n *\n * @param {Object|String} loc Optional default location object.\n * @returns {Object} lolcation object.\n * @public\n */\nfunction lolcation(loc) {\n var globalVar;\n\n if (typeof window !== 'undefined') globalVar = window;\n else if (typeof global !== 'undefined') globalVar = global;\n else if (typeof self !== 'undefined') globalVar = self;\n else globalVar = {};\n\n var location = globalVar.location || {};\n loc = loc || location;\n\n var finaldestination = {}\n , type = typeof loc\n , key;\n\n if ('blob:' === loc.protocol) {\n finaldestination = new Url(unescape(loc.pathname), {});\n } else if ('string' === type) {\n finaldestination = new Url(loc, {});\n for (key in ignore) delete finaldestination[key];\n } else if ('object' === type) {\n for (key in loc) {\n if (key in ignore) continue;\n finaldestination[key] = loc[key];\n }\n\n if (finaldestination.slashes === undefined) {\n finaldestination.slashes = slashes.test(loc.href);\n }\n }\n\n return finaldestination;\n}\n\n/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n return (\n scheme === 'file:' ||\n scheme === 'ftp:' ||\n scheme === 'http:' ||\n scheme === 'https:' ||\n scheme === 'ws:' ||\n scheme === 'wss:'\n );\n}\n\n/**\n * @typedef ProtocolExtract\n * @type Object\n * @property {String} protocol Protocol matched in the URL, in lowercase.\n * @property {Boolean} slashes `true` if protocol is followed by \"//\", else `false`.\n * @property {String} rest Rest of the URL that is not part of the protocol.\n */\n\n/**\n * Extract protocol information from a URL with/without double slash (\"//\").\n *\n * @param {String} address URL we want to extract from.\n * @param {Object} location\n * @return {ProtocolExtract} Extracted information.\n * @private\n */\nfunction extractProtocol(address, location) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n location = location || {};\n\n var match = protocolre.exec(address);\n var protocol = match[1] ? match[1].toLowerCase() : '';\n var forwardSlashes = !!match[2];\n var otherSlashes = !!match[3];\n var slashesCount = 0;\n var rest;\n\n if (forwardSlashes) {\n if (otherSlashes) {\n rest = match[2] + match[3] + match[4];\n slashesCount = match[2].length + match[3].length;\n } else {\n rest = match[2] + match[4];\n slashesCount = match[2].length;\n }\n } else {\n if (otherSlashes) {\n rest = match[3] + match[4];\n slashesCount = match[3].length;\n } else {\n rest = match[4]\n }\n }\n\n if (protocol === 'file:') {\n if (slashesCount >= 2) {\n rest = rest.slice(2);\n }\n } else if (isSpecial(protocol)) {\n rest = match[4];\n } else if (protocol) {\n if (forwardSlashes) {\n rest = rest.slice(2);\n }\n } else if (slashesCount >= 2 && isSpecial(location.protocol)) {\n rest = match[4];\n }\n\n return {\n protocol: protocol,\n slashes: forwardSlashes || isSpecial(protocol),\n slashesCount: slashesCount,\n rest: rest\n };\n}\n\n/**\n * Resolve a relative URL pathname against a base URL pathname.\n *\n * @param {String} relative Pathname of the relative URL.\n * @param {String} base Pathname of the base URL.\n * @return {String} Resolved pathname.\n * @private\n */\nfunction resolve(relative, base) {\n if (relative === '') return base;\n\n var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))\n , i = path.length\n , last = path[i - 1]\n , unshift = false\n , up = 0;\n\n while (i--) {\n if (path[i] === '.') {\n path.splice(i, 1);\n } else if (path[i] === '..') {\n path.splice(i, 1);\n up++;\n } else if (up) {\n if (i === 0) unshift = true;\n path.splice(i, 1);\n up--;\n }\n }\n\n if (unshift) path.unshift('');\n if (last === '.' || last === '..') path.push('');\n\n return path.join('/');\n}\n\n/**\n * The actual URL instance. Instead of returning an object we've opted-in to\n * create an actual constructor as it's much more memory efficient and\n * faster and it pleases my OCD.\n *\n * It is worth noting that we should not use `URL` as class name to prevent\n * clashes with the global URL instance that got introduced in browsers.\n *\n * @constructor\n * @param {String} address URL we want to parse.\n * @param {Object|String} [location] Location defaults for relative paths.\n * @param {Boolean|Function} [parser] Parser for the query string.\n * @private\n */\nfunction Url(address, location, parser) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n\n if (!(this instanceof Url)) {\n return new Url(address, location, parser);\n }\n\n var relative, extracted, parse, instruction, index, key\n , instructions = rules.slice()\n , type = typeof location\n , url = this\n , i = 0;\n\n //\n // The following if statements allows this module two have compatibility with\n // 2 different API:\n //\n // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n // where the boolean indicates that the query string should also be parsed.\n //\n // 2. The `URL` interface of the browser which accepts a URL, object as\n // arguments. The supplied object will be used as default values / fall-back\n // for relative paths.\n //\n if ('object' !== type && 'string' !== type) {\n parser = location;\n location = null;\n }\n\n if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n location = lolcation(location);\n\n //\n // Extract protocol information before running the instructions.\n //\n extracted = extractProtocol(address || '', location);\n relative = !extracted.protocol && !extracted.slashes;\n url.slashes = extracted.slashes || relative && location.slashes;\n url.protocol = extracted.protocol || location.protocol || '';\n address = extracted.rest;\n\n //\n // When the authority component is absent the URL starts with a path\n // component.\n //\n if (\n extracted.protocol === 'file:' && (\n extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n (!extracted.slashes &&\n (extracted.protocol ||\n extracted.slashesCount < 2 ||\n !isSpecial(url.protocol)))\n ) {\n instructions[3] = [/(.*)/, 'pathname'];\n }\n\n for (; i < instructions.length; i++) {\n instruction = instructions[i];\n\n if (typeof instruction === 'function') {\n address = instruction(address, url);\n continue;\n }\n\n parse = instruction[0];\n key = instruction[1];\n\n if (parse !== parse) {\n url[key] = address;\n } else if ('string' === typeof parse) {\n index = parse === '@'\n ? address.lastIndexOf(parse)\n : address.indexOf(parse);\n\n if (~index) {\n if ('number' === typeof instruction[2]) {\n url[key] = address.slice(0, index);\n address = address.slice(index + instruction[2]);\n } else {\n url[key] = address.slice(index);\n address = address.slice(0, index);\n }\n }\n } else if ((index = parse.exec(address))) {\n url[key] = index[1];\n address = address.slice(0, index.index);\n }\n\n url[key] = url[key] || (\n relative && instruction[3] ? location[key] || '' : ''\n );\n\n //\n // Hostname, host and protocol should be lowercased so they can be used to\n // create a proper `origin`.\n //\n if (instruction[4]) url[key] = url[key].toLowerCase();\n }\n\n //\n // Also parse the supplied query string in to an object. If we're supplied\n // with a custom parser as function use that instead of the default build-in\n // parser.\n //\n if (parser) url.query = parser(url.query);\n\n //\n // If the URL is relative, resolve the pathname against the base URL.\n //\n if (\n relative\n && location.slashes\n && url.pathname.charAt(0) !== '/'\n && (url.pathname !== '' || location.pathname !== '')\n ) {\n url.pathname = resolve(url.pathname, location.pathname);\n }\n\n //\n // Default to a / for pathname if none exists. This normalizes the URL\n // to always have a /\n //\n if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n url.pathname = '/' + url.pathname;\n }\n\n //\n // We should not add port numbers if they are already the default port number\n // for a given protocol. As the host also contains the port number we're going\n // override it with the hostname which contains no port number.\n //\n if (!required(url.port, url.protocol)) {\n url.host = url.hostname;\n url.port = '';\n }\n\n //\n // Parse down the `auth` for the username and password.\n //\n url.username = url.password = '';\n\n if (url.auth) {\n index = url.auth.indexOf(':');\n\n if (~index) {\n url.username = url.auth.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = url.auth.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password))\n } else {\n url.username = encodeURIComponent(decodeURIComponent(url.auth));\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n }\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n //\n // The href is just the compiled result.\n //\n url.href = url.toString();\n}\n\n/**\n * This is convenience method for changing properties in the URL instance to\n * insure that they all propagate correctly.\n *\n * @param {String} part Property we need to adjust.\n * @param {Mixed} value The newly assigned value.\n * @param {Boolean|Function} fn When setting the query, it will be the function\n * used to parse the query.\n * When setting the protocol, double slash will be\n * removed from the final url if it is true.\n * @returns {URL} URL instance for chaining.\n * @public\n */\nfunction set(part, value, fn) {\n var url = this;\n\n switch (part) {\n case 'query':\n if ('string' === typeof value && value.length) {\n value = (fn || qs.parse)(value);\n }\n\n url[part] = value;\n break;\n\n case 'port':\n url[part] = value;\n\n if (!required(value, url.protocol)) {\n url.host = url.hostname;\n url[part] = '';\n } else if (value) {\n url.host = url.hostname +':'+ value;\n }\n\n break;\n\n case 'hostname':\n url[part] = value;\n\n if (url.port) value += ':'+ url.port;\n url.host = value;\n break;\n\n case 'host':\n url[part] = value;\n\n if (port.test(value)) {\n value = value.split(':');\n url.port = value.pop();\n url.hostname = value.join(':');\n } else {\n url.hostname = value;\n url.port = '';\n }\n\n break;\n\n case 'protocol':\n url.protocol = value.toLowerCase();\n url.slashes = !fn;\n break;\n\n case 'pathname':\n case 'hash':\n if (value) {\n var char = part === 'pathname' ? '/' : '#';\n url[part] = value.charAt(0) !== char ? char + value : value;\n } else {\n url[part] = value;\n }\n break;\n\n case 'username':\n case 'password':\n url[part] = encodeURIComponent(value);\n break;\n\n case 'auth':\n var index = value.indexOf(':');\n\n if (~index) {\n url.username = value.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = value.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(value));\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var ins = rules[i];\n\n if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n url.href = url.toString();\n\n return url;\n}\n\n/**\n * Transform the properties back in to a valid and full URL string.\n *\n * @param {Function} stringify Optional query stringify function.\n * @returns {String} Compiled version of the URL.\n * @public\n */\nfunction toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n var query\n , url = this\n , host = url.host\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) result += ':'+ url.password;\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n //\n // Trailing colon is removed from `url.host` when it is parsed. If it still\n // ends with a colon, then add back the trailing colon that was removed. This\n // prevents an invalid URL from being transformed into a valid one.\n //\n if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {\n host += ':';\n }\n\n result += host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n if (url.hash) result += url.hash;\n\n return result;\n}\n\nUrl.prototype = { set: set, toString: toString };\n\n//\n// Expose the URL parser and some additional properties that might be useful for\n// others or testing.\n//\nUrl.extractProtocol = extractProtocol;\nUrl.location = lolcation;\nUrl.trimLeft = trimLeft;\nUrl.qs = qs;\n\nmodule.exports = Url;\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { PartialJSONObject } from '@lumino/coreutils';\nimport { posix } from 'path';\nimport urlparse from 'url-parse';\n\n/**\n * The namespace for URL-related functions.\n */\nexport namespace URLExt {\n /**\n * Parse a url into a URL object.\n *\n * @param url - The URL string to parse.\n *\n * @returns A URL object.\n */\n export function parse(url: string): IUrl {\n if (typeof document !== 'undefined' && document) {\n const a = document.createElement('a');\n a.href = url;\n return a;\n }\n return urlparse(url);\n }\n\n /**\n * Parse URL and retrieve hostname\n *\n * @param url - The URL string to parse\n *\n * @returns a hostname string value\n */\n export function getHostName(url: string): string {\n return urlparse(url).hostname;\n }\n /**\n * Normalize a url.\n */\n export function normalize(url: string): string;\n export function normalize(url: undefined): undefined;\n export function normalize(url: string | undefined): string | undefined;\n export function normalize(url: string | undefined): string | undefined {\n return url && parse(url).toString();\n }\n\n /**\n * Join a sequence of url components and normalizes as in node `path.join`.\n *\n * @param parts - The url components.\n *\n * @returns the joined url.\n */\n export function join(...parts: string[]): string {\n let u = urlparse(parts[0], {});\n // Schema-less URL can be only parsed as relative to a base URL\n // see https://github.com/unshiftio/url-parse/issues/219#issuecomment-1002219326\n const isSchemaLess = u.protocol === '' && u.slashes;\n if (isSchemaLess) {\n u = urlparse(parts[0], 'https:' + parts[0]);\n }\n const prefix = `${isSchemaLess ? '' : u.protocol}${u.slashes ? '//' : ''}${\n u.auth\n }${u.auth ? '@' : ''}${u.host}`;\n // If there was a prefix, then the first path must start at the root.\n const path = posix.join(\n `${!!prefix && u.pathname[0] !== '/' ? '/' : ''}${u.pathname}`,\n ...parts.slice(1)\n );\n return `${prefix}${path === '.' ? '' : path}`;\n }\n\n /**\n * Encode the components of a multi-segment url.\n *\n * @param url - The url to encode.\n *\n * @returns the encoded url.\n *\n * #### Notes\n * Preserves the `'/'` separators.\n * Should not include the base url, since all parts are escaped.\n */\n export function encodeParts(url: string): string {\n return join(...url.split('/').map(encodeURIComponent));\n }\n\n /**\n * Return a serialized object string suitable for a query.\n *\n * @param value The source object.\n *\n * @returns an encoded url query.\n *\n * #### Notes\n * Modified version of [stackoverflow](http://stackoverflow.com/a/30707423).\n */\n export function objectToQueryString(value: PartialJSONObject): string {\n const keys = Object.keys(value).filter(key => key.length > 0);\n\n if (!keys.length) {\n return '';\n }\n\n return (\n '?' +\n keys\n .map(key => {\n const content = encodeURIComponent(String(value[key]));\n\n return key + (content ? '=' + content : '');\n })\n .join('&')\n );\n }\n\n /**\n * Return a parsed object that represents the values in a query string.\n */\n export function queryStringToObject(value: string): {\n [key: string]: string | undefined;\n } {\n return value\n .replace(/^\\?/, '')\n .split('&')\n .reduce(\n (acc, val) => {\n const [key, value] = val.split('=');\n\n if (key.length > 0) {\n acc[key] = decodeURIComponent(value || '');\n }\n\n return acc;\n },\n {} as { [key: string]: string }\n );\n }\n\n /**\n * Test whether the url is a local url.\n *\n * @param allowRoot - Whether the paths starting at Unix-style filesystem root (`/`) are permitted.\n *\n * #### Notes\n * This function returns `false` for any fully qualified url, including\n * `data:`, `file:`, and `//` protocol URLs.\n */\n export function isLocal(url: string, allowRoot: boolean = false): boolean {\n const { protocol } = parse(url);\n\n return (\n (!protocol || url.toLowerCase().indexOf(protocol) !== 0) &&\n (allowRoot ? url.indexOf('//') !== 0 : url.indexOf('/') !== 0)\n );\n }\n\n /**\n * The interface for a URL object\n */\n export interface IUrl {\n /**\n * The full URL string that was parsed with both the protocol and host\n * components converted to lower-case.\n */\n href: string;\n\n /**\n * Identifies the URL's lower-cased protocol scheme.\n */\n protocol: string;\n\n /**\n * The full lower-cased host portion of the URL, including the port if\n * specified.\n */\n host: string;\n\n /**\n * The lower-cased host name portion of the host component without the\n * port included.\n */\n hostname: string;\n\n /**\n * The numeric port portion of the host component.\n */\n port: string;\n\n /**\n * The entire path section of the URL.\n */\n pathname: string;\n\n /**\n * The \"fragment\" portion of the URL including the leading ASCII hash\n * `(#)` character\n */\n hash: string;\n\n /**\n * The search element, including leading question mark (`'?'`), if any,\n * of the URL.\n */\n search?: string;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { JSONExt } from '@lumino/coreutils';\nimport minimist from 'minimist';\nimport { URLExt } from './url';\n\n/**\n * Declare stubs for the node variables.\n */\ndeclare let process: any;\ndeclare let require: any;\n\n/**\n * The namespace for `PageConfig` functions.\n */\nexport namespace PageConfig {\n /**\n * Get global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n *\n * @returns The config value or an empty string if not found.\n *\n * #### Notes\n * All values are treated as strings.\n * For browser based applications, it is assumed that the page HTML\n * includes a script tag with the id `jupyter-config-data` containing the\n * configuration as valid JSON. In order to support the classic Notebook,\n * we fall back on checking for `body` data of the given `name`.\n *\n * For node applications, it is assumed that the process was launched\n * with a `--jupyter-config-data` option pointing to a JSON settings\n * file.\n */\n export function getOption(name: string): string {\n if (configData) {\n return configData[name] || getBodyData(name);\n }\n configData = Object.create(null);\n let found = false;\n\n // Use script tag if available.\n if (typeof document !== 'undefined' && document) {\n const el = document.getElementById('jupyter-config-data');\n\n if (el) {\n configData = JSON.parse(el.textContent || '') as {\n [key: string]: string;\n };\n found = true;\n }\n }\n // Otherwise use CLI if given.\n if (!found && typeof process !== 'undefined' && process.argv) {\n try {\n const cli = minimist(process.argv.slice(2));\n const path: any = require('path');\n let fullPath = '';\n if ('jupyter-config-data' in cli) {\n fullPath = path.resolve(cli['jupyter-config-data']);\n } else if ('JUPYTER_CONFIG_DATA' in process.env) {\n fullPath = path.resolve(process.env['JUPYTER_CONFIG_DATA']);\n }\n if (fullPath) {\n // Force Webpack to ignore this require.\n // eslint-disable-next-line\n configData = eval('require')(fullPath) as { [key: string]: string };\n }\n } catch (e) {\n console.error(e);\n }\n }\n\n if (!JSONExt.isObject(configData)) {\n configData = Object.create(null);\n } else {\n for (const key in configData) {\n // PageConfig expects strings\n if (typeof configData[key] !== 'string') {\n configData[key] = JSON.stringify(configData[key]);\n }\n }\n }\n return configData![name] || getBodyData(name);\n }\n\n /**\n * Set global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n * @param value - The value to set the option to.\n *\n * @returns The last config value or an empty string if it doesn't exist.\n */\n export function setOption(name: string, value: string): string {\n const last = getOption(name);\n\n configData![name] = value;\n return last;\n }\n\n /**\n * Get the base url for a Jupyter application, or the base url of the page.\n */\n export function getBaseUrl(): string {\n return URLExt.normalize(getOption('baseUrl') || '/');\n }\n\n /**\n * Get the tree url for a JupyterLab application.\n */\n export function getTreeUrl(): string {\n return URLExt.join(getBaseUrl(), getOption('treeUrl'));\n }\n\n /**\n * Get the base url for sharing links (usually baseUrl)\n */\n export function getShareUrl(): string {\n return URLExt.normalize(getOption('shareUrl') || getBaseUrl());\n }\n\n /**\n * Get the tree url for shareable links.\n * Usually the same as treeUrl,\n * but overridable e.g. when sharing with JupyterHub.\n */\n export function getTreeShareUrl(): string {\n return URLExt.normalize(URLExt.join(getShareUrl(), getOption('treeUrl')));\n }\n\n /**\n * Create a new URL given an optional mode and tree path.\n *\n * This is used to create URLS when the mode or tree path change as the user\n * changes mode or the current document in the main area. If fields in\n * options are omitted, the value in PageConfig will be used.\n *\n * @param options - IGetUrlOptions for the new path.\n */\n export function getUrl(options: IGetUrlOptions): string {\n let path = options.toShare ? getShareUrl() : getBaseUrl();\n const mode = options.mode ?? getOption('mode');\n const workspace = options.workspace ?? getOption('workspace');\n const labOrDoc = mode === 'single-document' ? 'doc' : 'lab';\n path = URLExt.join(path, labOrDoc);\n if (workspace !== defaultWorkspace) {\n path = URLExt.join(\n path,\n 'workspaces',\n encodeURIComponent(getOption('workspace') ?? defaultWorkspace)\n );\n }\n const treePath = options.treePath ?? getOption('treePath');\n if (treePath) {\n path = URLExt.join(path, 'tree', URLExt.encodeParts(treePath));\n }\n return path;\n }\n\n export const defaultWorkspace: string = 'default';\n\n /**\n * Options for getUrl\n */\n\n export interface IGetUrlOptions {\n /**\n * The optional mode as a string 'single-document' or 'multiple-document'. If\n * the mode argument is missing, it will be provided from the PageConfig.\n */\n mode?: string;\n\n /**\n * The optional workspace as a string. If this argument is missing, the value will\n * be pulled from PageConfig. To use the default workspace (no /workspaces/<name>\n * URL segment will be included) pass the string PageConfig.defaultWorkspace.\n */\n workspace?: string;\n\n /**\n * Whether the url is meant to be shared or not; default false.\n */\n toShare?: boolean;\n\n /**\n * The optional tree path as as string. If treePath is not provided it will be\n * provided from the PageConfig. If an empty string, the resulting path will not\n * contain a tree portion.\n */\n treePath?: string;\n }\n\n /**\n * Get the base websocket url for a Jupyter application, or an empty string.\n */\n export function getWsUrl(baseUrl?: string): string {\n let wsUrl = getOption('wsUrl');\n if (!wsUrl) {\n baseUrl = baseUrl ? URLExt.normalize(baseUrl) : getBaseUrl();\n if (baseUrl.indexOf('http') !== 0) {\n return '';\n }\n wsUrl = 'ws' + baseUrl.slice(4);\n }\n return URLExt.normalize(wsUrl);\n }\n\n /**\n * Returns the URL converting this notebook to a certain\n * format with nbconvert.\n */\n export function getNBConvertURL({\n path,\n format,\n download\n }: {\n path: string;\n format: string;\n download: boolean;\n }): string {\n const notebookPath = URLExt.encodeParts(path);\n const url = URLExt.join(getBaseUrl(), 'nbconvert', format, notebookPath);\n if (download) {\n return url + '?download=true';\n }\n return url;\n }\n\n /**\n * Get the authorization token for a Jupyter application.\n */\n export function getToken(): string {\n return getOption('token') || getBodyData('jupyterApiToken');\n }\n\n /**\n * Get the Notebook version info [major, minor, patch].\n */\n export function getNotebookVersion(): [number, number, number] {\n const notebookVersion = getOption('notebookVersion');\n if (notebookVersion === '') {\n return [0, 0, 0];\n }\n return JSON.parse(notebookVersion);\n }\n\n /**\n * Private page config data for the Jupyter application.\n */\n let configData: { [key: string]: string } | null = null;\n\n /**\n * Get a url-encoded item from `body.data` and decode it\n * We should never have any encoded URLs anywhere else in code\n * until we are building an actual request.\n */\n function getBodyData(key: string): string {\n if (typeof document === 'undefined' || !document.body) {\n return '';\n }\n const val = document.body.dataset[key];\n if (typeof val === 'undefined') {\n return '';\n }\n return decodeURIComponent(val);\n }\n\n /**\n * The namespace for page config `Extension` functions.\n */\n export namespace Extension {\n /**\n * Populate an array from page config.\n *\n * @param key - The page config key (e.g., `deferredExtensions`).\n *\n * #### Notes\n * This is intended for `deferredExtensions` and `disabledExtensions`.\n */\n function populate(key: string): string[] {\n try {\n const raw = getOption(key);\n if (raw) {\n return JSON.parse(raw);\n }\n } catch (error) {\n console.warn(`Unable to parse ${key}.`, error);\n }\n return [];\n }\n\n /**\n * The collection of deferred extensions in page config.\n */\n export const deferred = populate('deferredExtensions');\n\n /**\n * The collection of disabled extensions in page config.\n */\n export const disabled = populate('disabledExtensions');\n\n /**\n * Returns whether a plugin is deferred.\n *\n * @param id - The plugin ID.\n */\n export function isDeferred(id: string): boolean {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return deferred.some(val => val === id || (extName && val === extName));\n }\n\n /**\n * Returns whether a plugin is disabled.\n *\n * @param id - The plugin ID.\n */\n export function isDisabled(id: string): boolean {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return disabled.some(val => val === id || (extName && val === extName));\n }\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { posix } from 'path';\n\n/**\n * The namespace for path-related functions.\n *\n * Note that Jupyter server paths do not start with a leading slash.\n */\nexport namespace PathExt {\n /**\n * Join all arguments together and normalize the resulting path.\n * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.\n *\n * @param paths - The string paths to join.\n */\n export function join(...paths: string[]): string {\n const path = posix.join(...paths);\n return path === '.' ? '' : removeSlash(path);\n }\n\n /**\n * Join all arguments together and normalize the resulting path and preserve the leading slash.\n *\n * @param paths - The string paths to join.\n */\n export function joinWithLeadingSlash(...paths: string[]): string {\n const path = posix.join(...paths);\n return path === '.' ? '' : path;\n }\n\n /**\n * Return the last portion of a path. Similar to the Unix basename command.\n * Often used to extract the file name from a fully qualified path.\n *\n * @param path - The path to evaluate.\n *\n * @param ext - An extension to remove from the result.\n */\n export function basename(path: string, ext?: string): string {\n return posix.basename(path, ext);\n }\n\n /**\n * Get the directory name of a path, similar to the Unix dirname command.\n * When an empty path is given, returns the root path.\n *\n * @param path - The file path.\n */\n export function dirname(path: string): string {\n const dir = removeSlash(posix.dirname(path));\n return dir === '.' ? '' : dir;\n }\n\n /**\n * Get the extension of the path.\n *\n * @param path - The file path.\n *\n * @returns the extension of the file.\n *\n * #### Notes\n * The extension is the string from the last occurrence of the `.`\n * character to end of string in the last portion of the path, inclusive.\n * If there is no `.` in the last portion of the path, or if the first\n * character of the basename of path [[basename]] is `.`, then an\n * empty string is returned.\n */\n export function extname(path: string): string {\n return posix.extname(path);\n }\n\n /**\n * Normalize a string path, reducing '..' and '.' parts.\n * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.\n * When an empty path is given, returns the root path.\n *\n * @param path - The string path to normalize.\n */\n export function normalize(path: string): string {\n if (path === '') {\n return '';\n }\n return removeSlash(posix.normalize(path));\n }\n\n /**\n * Resolve a sequence of paths or path segments into an absolute path.\n * The root path in the application has no leading slash, so it is removed.\n *\n * @param parts - The paths to join.\n *\n * #### Notes\n * The right-most parameter is considered \\{to\\}. Other parameters are considered an array of \\{from\\}.\n *\n * Starting from leftmost \\{from\\} parameter, resolves \\{to\\} to an absolute path.\n *\n * If \\{to\\} isn't already absolute, \\{from\\} arguments are prepended in right to left order, until an absolute path is found. If after using all \\{from\\} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.\n */\n export function resolve(...parts: string[]): string {\n return removeSlash(posix.resolve(...parts));\n }\n\n /**\n * Solve the relative path from \\{from\\} to \\{to\\}.\n *\n * @param from - The source path.\n *\n * @param to - The target path.\n *\n * #### Notes\n * If from and to each resolve to the same path (after calling\n * path.resolve() on each), a zero-length string is returned.\n * If a zero-length string is passed as from or to, `/`\n * will be used instead of the zero-length strings.\n */\n export function relative(from: string, to: string): string {\n return removeSlash(posix.relative(from, to));\n }\n\n /**\n * Normalize a file extension to be of the type `'.foo'`.\n *\n * @param extension - the file extension.\n *\n * #### Notes\n * Adds a leading dot if not present and converts to lower case.\n */\n export function normalizeExtension(extension: string): string {\n if (extension.length > 0 && extension.indexOf('.') !== 0) {\n extension = `.${extension}`;\n }\n return extension;\n }\n\n /**\n * Remove the leading slash from a path.\n *\n * @param path the path from which to remove a leading slash.\n */\n export function removeSlash(path: string): string {\n if (path.indexOf('/') === 0) {\n path = path.slice(1);\n }\n return path;\n }\n}\n", "/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\n\nimport { PromiseDelegate } from '@lumino/coreutils';\nimport { ISignal } from '@lumino/signaling';\n\n/**\n * Convert a signal into a promise for the first emitted value.\n *\n * @param signal - The signal we are listening to.\n * @param timeout - Timeout to wait for signal in ms (not timeout if not defined or 0)\n *\n * @returns a Promise that resolves with a `(sender, args)` pair.\n */\nexport function signalToPromise<T, U>(\n signal: ISignal<T, U>,\n timeout?: number\n): Promise<[T, U]> {\n const waitForSignal = new PromiseDelegate<[T, U]>();\n\n function cleanup() {\n signal.disconnect(slot);\n }\n\n function slot(sender: T, args: U) {\n cleanup();\n waitForSignal.resolve([sender, args]);\n }\n signal.connect(slot);\n\n if ((timeout ?? 0) > 0) {\n setTimeout(() => {\n cleanup();\n waitForSignal.reject(`Signal not emitted within ${timeout} ms.`);\n }, timeout);\n }\n return waitForSignal.promise;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n/**\n * The namespace for text-related functions.\n */\nexport namespace Text {\n // javascript stores text as utf16 and string indices use \"code units\",\n // which stores high-codepoint characters as \"surrogate pairs\",\n // which occupy two indices in the javascript string.\n // We need to translate cursor_pos in the Jupyter protocol (in characters)\n // to js offset (with surrogate pairs taking two spots).\n\n const HAS_SURROGATES: boolean = '\uD835\uDC1A'.length > 1;\n\n /**\n * Convert a javascript string index into a unicode character offset\n *\n * @param jsIdx - The javascript string index (counting surrogate pairs)\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The unicode character offset\n */\n export function jsIndexToCharIndex(jsIdx: number, text: string): number {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return jsIdx;\n }\n let charIdx = jsIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n charIdx--;\n i++;\n }\n }\n }\n return charIdx;\n }\n\n /**\n * Convert a unicode character offset to a javascript string index.\n *\n * @param charIdx - The index in unicode characters\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The js-native index\n */\n export function charIndexToJsIndex(charIdx: number, text: string): number {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return charIdx;\n }\n let jsIdx = charIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n jsIdx++;\n i++;\n }\n }\n }\n return jsIdx;\n }\n\n /**\n * Given a 'snake-case', 'snake_case', 'snake:case', or\n * 'snake case' string, will return the camel case version: 'snakeCase'.\n *\n * @param str the snake-case input string.\n *\n * @param upper default = false. If true, the first letter of the\n * returned string will be capitalized.\n *\n * @returns the camel case version of the input string.\n */\n export function camelCase(str: string, upper: boolean = false): string {\n return str.replace(/^(\\w)|[\\s-_:]+(\\w)/g, function (match, p1, p2) {\n if (p2) {\n return p2.toUpperCase();\n } else {\n return upper ? p1.toUpperCase() : p1.toLowerCase();\n }\n });\n }\n\n /**\n * Given a string, title case the words in the string.\n *\n * @param str the string to title case.\n *\n * @returns the same string, but with each word capitalized.\n */\n export function titleCase(str: string): string {\n return (str || '')\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n/**\n * A list of time units with their associated value in milliseconds.\n */\nconst UNITS: { name: Intl.RelativeTimeFormatUnit; milliseconds: number }[] = [\n { name: 'years', milliseconds: 365 * 24 * 60 * 60 * 1000 },\n { name: 'months', milliseconds: 30 * 24 * 60 * 60 * 1000 },\n { name: 'days', milliseconds: 24 * 60 * 60 * 1000 },\n { name: 'hours', milliseconds: 60 * 60 * 1000 },\n { name: 'minutes', milliseconds: 60 * 1000 },\n { name: 'seconds', milliseconds: 1000 }\n];\n\n/**\n * The namespace for date functions.\n */\nexport namespace Time {\n export type HumanStyle = Intl.ResolvedRelativeTimeFormatOptions['style'];\n\n /**\n * Convert a timestring to a human readable string (e.g. 'two minutes ago').\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n export function formatHuman(\n value: string | Date,\n format: HumanStyle = 'long'\n ): string {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.RelativeTimeFormat(lang, {\n numeric: 'auto',\n style: format\n });\n const delta = new Date(value).getTime() - Date.now();\n for (let unit of UNITS) {\n const amount = Math.ceil(delta / unit.milliseconds);\n if (amount === 0) {\n continue;\n }\n return formatter.format(amount, unit.name);\n }\n return formatter.format(0, 'seconds');\n }\n\n /**\n * Convenient helper to convert a timestring to a date format.\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n export function format(value: string | Date): string {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.DateTimeFormat(lang, {\n dateStyle: 'short',\n timeStyle: 'short'\n });\n return formatter.format(new Date(value));\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * @packageDocumentation\n * @module coreutils\n */\n\nexport * from './activitymonitor';\nexport * from './interfaces';\nexport * from './lru';\nexport * from './markdowncodeblocks';\nexport * from './pageconfig';\nexport * from './path';\nexport * from './signal';\nexport * from './text';\nexport * from './time';\nexport * from './url';\n", "'use strict';\n\n/**\n * @param typeMap [Object] Map of MIME type -> Array[extensions]\n * @param ...\n */\nfunction Mime() {\n this._types = Object.create(null);\n this._extensions = Object.create(null);\n\n for (let i = 0; i < arguments.length; i++) {\n this.define(arguments[i]);\n }\n\n this.define = this.define.bind(this);\n this.getType = this.getType.bind(this);\n this.getExtension = this.getExtension.bind(this);\n}\n\n/**\n * Define mimetype -> extension mappings. Each key is a mime-type that maps\n * to an array of extensions associated with the type. The first extension is\n * used as the default extension for the type.\n *\n * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});\n *\n * If a type declares an extension that has already been defined, an error will\n * be thrown. To suppress this error and force the extension to be associated\n * with the new type, pass `force`=true. Alternatively, you may prefix the\n * extension with \"*\" to map the type to extension, without mapping the\n * extension to the type.\n *\n * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});\n *\n *\n * @param map (Object) type definitions\n * @param force (Boolean) if true, force overriding of existing definitions\n */\nMime.prototype.define = function(typeMap, force) {\n for (let type in typeMap) {\n let extensions = typeMap[type].map(function(t) {\n return t.toLowerCase();\n });\n type = type.toLowerCase();\n\n for (let i = 0; i < extensions.length; i++) {\n const ext = extensions[i];\n\n // '*' prefix = not the preferred type for this extension. So fixup the\n // extension, and skip it.\n if (ext[0] === '*') {\n continue;\n }\n\n if (!force && (ext in this._types)) {\n throw new Error(\n 'Attempt to change mapping for \"' + ext +\n '\" extension from \"' + this._types[ext] + '\" to \"' + type +\n '\". Pass `force=true` to allow this, otherwise remove \"' + ext +\n '\" from the list of extensions for \"' + type + '\".'\n );\n }\n\n this._types[ext] = type;\n }\n\n // Use first extension as default\n if (force || !this._extensions[type]) {\n const ext = extensions[0];\n this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);\n }\n }\n};\n\n/**\n * Lookup a mime type based on extension\n */\nMime.prototype.getType = function(path) {\n path = String(path);\n let last = path.replace(/^.*[/\\\\]/, '').toLowerCase();\n let ext = last.replace(/^.*\\./, '').toLowerCase();\n\n let hasPath = last.length < path.length;\n let hasDot = ext.length < last.length - 1;\n\n return (hasDot || !hasPath) && this._types[ext] || null;\n};\n\n/**\n * Return file extension associated with a mime type\n */\nMime.prototype.getExtension = function(type) {\n type = /^\\s*([^;\\s]*)/.test(type) && RegExp.$1;\n return type && this._extensions[type.toLowerCase()] || null;\n};\n\nmodule.exports = Mime;\n", "module.exports = {\"application/andrew-inset\":[\"ez\"],\"application/applixware\":[\"aw\"],\"application/atom+xml\":[\"atom\"],\"application/atomcat+xml\":[\"atomcat\"],\"application/atomdeleted+xml\":[\"atomdeleted\"],\"application/atomsvc+xml\":[\"atomsvc\"],\"application/atsc-dwd+xml\":[\"dwd\"],\"application/atsc-held+xml\":[\"held\"],\"application/atsc-rsat+xml\":[\"rsat\"],\"application/bdoc\":[\"bdoc\"],\"application/calendar+xml\":[\"xcs\"],\"application/ccxml+xml\":[\"ccxml\"],\"application/cdfx+xml\":[\"cdfx\"],\"application/cdmi-capability\":[\"cdmia\"],\"application/cdmi-container\":[\"cdmic\"],\"application/cdmi-domain\":[\"cdmid\"],\"application/cdmi-object\":[\"cdmio\"],\"application/cdmi-queue\":[\"cdmiq\"],\"application/cu-seeme\":[\"cu\"],\"application/dash+xml\":[\"mpd\"],\"application/davmount+xml\":[\"davmount\"],\"application/docbook+xml\":[\"dbk\"],\"application/dssc+der\":[\"dssc\"],\"application/dssc+xml\":[\"xdssc\"],\"application/ecmascript\":[\"es\",\"ecma\"],\"application/emma+xml\":[\"emma\"],\"application/emotionml+xml\":[\"emotionml\"],\"application/epub+zip\":[\"epub\"],\"application/exi\":[\"exi\"],\"application/express\":[\"exp\"],\"application/fdt+xml\":[\"fdt\"],\"application/font-tdpfr\":[\"pfr\"],\"application/geo+json\":[\"geojson\"],\"application/gml+xml\":[\"gml\"],\"application/gpx+xml\":[\"gpx\"],\"application/gxf\":[\"gxf\"],\"application/gzip\":[\"gz\"],\"application/hjson\":[\"hjson\"],\"application/hyperstudio\":[\"stk\"],\"application/inkml+xml\":[\"ink\",\"inkml\"],\"application/ipfix\":[\"ipfix\"],\"application/its+xml\":[\"its\"],\"application/java-archive\":[\"jar\",\"war\",\"ear\"],\"application/java-serialized-object\":[\"ser\"],\"application/java-vm\":[\"class\"],\"application/javascript\":[\"js\",\"mjs\"],\"application/json\":[\"json\",\"map\"],\"application/json5\":[\"json5\"],\"application/jsonml+json\":[\"jsonml\"],\"application/ld+json\":[\"jsonld\"],\"application/lgr+xml\":[\"lgr\"],\"application/lost+xml\":[\"lostxml\"],\"application/mac-binhex40\":[\"hqx\"],\"application/mac-compactpro\":[\"cpt\"],\"application/mads+xml\":[\"mads\"],\"application/manifest+json\":[\"webmanifest\"],\"application/marc\":[\"mrc\"],\"application/marcxml+xml\":[\"mrcx\"],\"application/mathematica\":[\"ma\",\"nb\",\"mb\"],\"application/mathml+xml\":[\"mathml\"],\"application/mbox\":[\"mbox\"],\"application/mediaservercontrol+xml\":[\"mscml\"],\"application/metalink+xml\":[\"metalink\"],\"application/metalink4+xml\":[\"meta4\"],\"application/mets+xml\":[\"mets\"],\"application/mmt-aei+xml\":[\"maei\"],\"application/mmt-usd+xml\":[\"musd\"],\"application/mods+xml\":[\"mods\"],\"application/mp21\":[\"m21\",\"mp21\"],\"application/mp4\":[\"mp4s\",\"m4p\"],\"application/msword\":[\"doc\",\"dot\"],\"application/mxf\":[\"mxf\"],\"application/n-quads\":[\"nq\"],\"application/n-triples\":[\"nt\"],\"application/node\":[\"cjs\"],\"application/octet-stream\":[\"bin\",\"dms\",\"lrf\",\"mar\",\"so\",\"dist\",\"distz\",\"pkg\",\"bpk\",\"dump\",\"elc\",\"deploy\",\"exe\",\"dll\",\"deb\",\"dmg\",\"iso\",\"img\",\"msi\",\"msp\",\"msm\",\"buffer\"],\"application/oda\":[\"oda\"],\"application/oebps-package+xml\":[\"opf\"],\"application/ogg\":[\"ogx\"],\"application/omdoc+xml\":[\"omdoc\"],\"application/onenote\":[\"onetoc\",\"onetoc2\",\"onetmp\",\"onepkg\"],\"application/oxps\":[\"oxps\"],\"application/p2p-overlay+xml\":[\"relo\"],\"application/patch-ops-error+xml\":[\"xer\"],\"application/pdf\":[\"pdf\"],\"application/pgp-encrypted\":[\"pgp\"],\"application/pgp-signature\":[\"asc\",\"sig\"],\"application/pics-rules\":[\"prf\"],\"application/pkcs10\":[\"p10\"],\"application/pkcs7-mime\":[\"p7m\",\"p7c\"],\"application/pkcs7-signature\":[\"p7s\"],\"application/pkcs8\":[\"p8\"],\"application/pkix-attr-cert\":[\"ac\"],\"application/pkix-cert\":[\"cer\"],\"application/pkix-crl\":[\"crl\"],\"application/pkix-pkipath\":[\"pkipath\"],\"application/pkixcmp\":[\"pki\"],\"application/pls+xml\":[\"pls\"],\"application/postscript\":[\"ai\",\"eps\",\"ps\"],\"application/provenance+xml\":[\"provx\"],\"application/pskc+xml\":[\"pskcxml\"],\"application/raml+yaml\":[\"raml\"],\"application/rdf+xml\":[\"rdf\",\"owl\"],\"application/reginfo+xml\":[\"rif\"],\"application/relax-ng-compact-syntax\":[\"rnc\"],\"application/resource-lists+xml\":[\"rl\"],\"application/resource-lists-diff+xml\":[\"rld\"],\"application/rls-services+xml\":[\"rs\"],\"application/route-apd+xml\":[\"rapd\"],\"application/route-s-tsid+xml\":[\"sls\"],\"application/route-usd+xml\":[\"rusd\"],\"application/rpki-ghostbusters\":[\"gbr\"],\"application/rpki-manifest\":[\"mft\"],\"application/rpki-roa\":[\"roa\"],\"application/rsd+xml\":[\"rsd\"],\"application/rss+xml\":[\"rss\"],\"application/rtf\":[\"rtf\"],\"application/sbml+xml\":[\"sbml\"],\"application/scvp-cv-request\":[\"scq\"],\"application/scvp-cv-response\":[\"scs\"],\"application/scvp-vp-request\":[\"spq\"],\"application/scvp-vp-response\":[\"spp\"],\"application/sdp\":[\"sdp\"],\"application/senml+xml\":[\"senmlx\"],\"application/sensml+xml\":[\"sensmlx\"],\"application/set-payment-initiation\":[\"setpay\"],\"application/set-registration-initiation\":[\"setreg\"],\"application/shf+xml\":[\"shf\"],\"application/sieve\":[\"siv\",\"sieve\"],\"application/smil+xml\":[\"smi\",\"smil\"],\"application/sparql-query\":[\"rq\"],\"application/sparql-results+xml\":[\"srx\"],\"application/srgs\":[\"gram\"],\"application/srgs+xml\":[\"grxml\"],\"application/sru+xml\":[\"sru\"],\"application/ssdl+xml\":[\"ssdl\"],\"application/ssml+xml\":[\"ssml\"],\"application/swid+xml\":[\"swidtag\"],\"application/tei+xml\":[\"tei\",\"teicorpus\"],\"application/thraud+xml\":[\"tfi\"],\"application/timestamped-data\":[\"tsd\"],\"application/toml\":[\"toml\"],\"application/trig\":[\"trig\"],\"application/ttml+xml\":[\"ttml\"],\"application/ubjson\":[\"ubj\"],\"application/urc-ressheet+xml\":[\"rsheet\"],\"application/urc-targetdesc+xml\":[\"td\"],\"application/voicexml+xml\":[\"vxml\"],\"application/wasm\":[\"wasm\"],\"application/widget\":[\"wgt\"],\"application/winhlp\":[\"hlp\"],\"application/wsdl+xml\":[\"wsdl\"],\"application/wspolicy+xml\":[\"wspolicy\"],\"application/xaml+xml\":[\"xaml\"],\"application/xcap-att+xml\":[\"xav\"],\"application/xcap-caps+xml\":[\"xca\"],\"application/xcap-diff+xml\":[\"xdf\"],\"application/xcap-el+xml\":[\"xel\"],\"application/xcap-ns+xml\":[\"xns\"],\"application/xenc+xml\":[\"xenc\"],\"application/xhtml+xml\":[\"xhtml\",\"xht\"],\"application/xliff+xml\":[\"xlf\"],\"application/xml\":[\"xml\",\"xsl\",\"xsd\",\"rng\"],\"application/xml-dtd\":[\"dtd\"],\"application/xop+xml\":[\"xop\"],\"application/xproc+xml\":[\"xpl\"],\"application/xslt+xml\":[\"*xsl\",\"xslt\"],\"application/xspf+xml\":[\"xspf\"],\"application/xv+xml\":[\"mxml\",\"xhvml\",\"xvml\",\"xvm\"],\"application/yang\":[\"yang\"],\"application/yin+xml\":[\"yin\"],\"application/zip\":[\"zip\"],\"audio/3gpp\":[\"*3gpp\"],\"audio/adpcm\":[\"adp\"],\"audio/amr\":[\"amr\"],\"audio/basic\":[\"au\",\"snd\"],\"audio/midi\":[\"mid\",\"midi\",\"kar\",\"rmi\"],\"audio/mobile-xmf\":[\"mxmf\"],\"audio/mp3\":[\"*mp3\"],\"audio/mp4\":[\"m4a\",\"mp4a\"],\"audio/mpeg\":[\"mpga\",\"mp2\",\"mp2a\",\"mp3\",\"m2a\",\"m3a\"],\"audio/ogg\":[\"oga\",\"ogg\",\"spx\",\"opus\"],\"audio/s3m\":[\"s3m\"],\"audio/silk\":[\"sil\"],\"audio/wav\":[\"wav\"],\"audio/wave\":[\"*wav\"],\"audio/webm\":[\"weba\"],\"audio/xm\":[\"xm\"],\"font/collection\":[\"ttc\"],\"font/otf\":[\"otf\"],\"font/ttf\":[\"ttf\"],\"font/woff\":[\"woff\"],\"font/woff2\":[\"woff2\"],\"image/aces\":[\"exr\"],\"image/apng\":[\"apng\"],\"image/avif\":[\"avif\"],\"image/bmp\":[\"bmp\"],\"image/cgm\":[\"cgm\"],\"image/dicom-rle\":[\"drle\"],\"image/emf\":[\"emf\"],\"image/fits\":[\"fits\"],\"image/g3fax\":[\"g3\"],\"image/gif\":[\"gif\"],\"image/heic\":[\"heic\"],\"image/heic-sequence\":[\"heics\"],\"image/heif\":[\"heif\"],\"image/heif-sequence\":[\"heifs\"],\"image/hej2k\":[\"hej2\"],\"image/hsj2\":[\"hsj2\"],\"image/ief\":[\"ief\"],\"image/jls\":[\"jls\"],\"image/jp2\":[\"jp2\",\"jpg2\"],\"image/jpeg\":[\"jpeg\",\"jpg\",\"jpe\"],\"image/jph\":[\"jph\"],\"image/jphc\":[\"jhc\"],\"image/jpm\":[\"jpm\"],\"image/jpx\":[\"jpx\",\"jpf\"],\"image/jxr\":[\"jxr\"],\"image/jxra\":[\"jxra\"],\"image/jxrs\":[\"jxrs\"],\"image/jxs\":[\"jxs\"],\"image/jxsc\":[\"jxsc\"],\"image/jxsi\":[\"jxsi\"],\"image/jxss\":[\"jxss\"],\"image/ktx\":[\"ktx\"],\"image/ktx2\":[\"ktx2\"],\"image/png\":[\"png\"],\"image/sgi\":[\"sgi\"],\"image/svg+xml\":[\"svg\",\"svgz\"],\"image/t38\":[\"t38\"],\"image/tiff\":[\"tif\",\"tiff\"],\"image/tiff-fx\":[\"tfx\"],\"image/webp\":[\"webp\"],\"image/wmf\":[\"wmf\"],\"message/disposition-notification\":[\"disposition-notification\"],\"message/global\":[\"u8msg\"],\"message/global-delivery-status\":[\"u8dsn\"],\"message/global-disposition-notification\":[\"u8mdn\"],\"message/global-headers\":[\"u8hdr\"],\"message/rfc822\":[\"eml\",\"mime\"],\"model/3mf\":[\"3mf\"],\"model/gltf+json\":[\"gltf\"],\"model/gltf-binary\":[\"glb\"],\"model/iges\":[\"igs\",\"iges\"],\"model/mesh\":[\"msh\",\"mesh\",\"silo\"],\"model/mtl\":[\"mtl\"],\"model/obj\":[\"obj\"],\"model/step+xml\":[\"stpx\"],\"model/step+zip\":[\"stpz\"],\"model/step-xml+zip\":[\"stpxz\"],\"model/stl\":[\"stl\"],\"model/vrml\":[\"wrl\",\"vrml\"],\"model/x3d+binary\":[\"*x3db\",\"x3dbz\"],\"model/x3d+fastinfoset\":[\"x3db\"],\"model/x3d+vrml\":[\"*x3dv\",\"x3dvz\"],\"model/x3d+xml\":[\"x3d\",\"x3dz\"],\"model/x3d-vrml\":[\"x3dv\"],\"text/cache-manifest\":[\"appcache\",\"manifest\"],\"text/calendar\":[\"ics\",\"ifb\"],\"text/coffeescript\":[\"coffee\",\"litcoffee\"],\"text/css\":[\"css\"],\"text/csv\":[\"csv\"],\"text/html\":[\"html\",\"htm\",\"shtml\"],\"text/jade\":[\"jade\"],\"text/jsx\":[\"jsx\"],\"text/less\":[\"less\"],\"text/markdown\":[\"markdown\",\"md\"],\"text/mathml\":[\"mml\"],\"text/mdx\":[\"mdx\"],\"text/n3\":[\"n3\"],\"text/plain\":[\"txt\",\"text\",\"conf\",\"def\",\"list\",\"log\",\"in\",\"ini\"],\"text/richtext\":[\"rtx\"],\"text/rtf\":[\"*rtf\"],\"text/sgml\":[\"sgml\",\"sgm\"],\"text/shex\":[\"shex\"],\"text/slim\":[\"slim\",\"slm\"],\"text/spdx\":[\"spdx\"],\"text/stylus\":[\"stylus\",\"styl\"],\"text/tab-separated-values\":[\"tsv\"],\"text/troff\":[\"t\",\"tr\",\"roff\",\"man\",\"me\",\"ms\"],\"text/turtle\":[\"ttl\"],\"text/uri-list\":[\"uri\",\"uris\",\"urls\"],\"text/vcard\":[\"vcard\"],\"text/vtt\":[\"vtt\"],\"text/xml\":[\"*xml\"],\"text/yaml\":[\"yaml\",\"yml\"],\"video/3gpp\":[\"3gp\",\"3gpp\"],\"video/3gpp2\":[\"3g2\"],\"video/h261\":[\"h261\"],\"video/h263\":[\"h263\"],\"video/h264\":[\"h264\"],\"video/iso.segment\":[\"m4s\"],\"video/jpeg\":[\"jpgv\"],\"video/jpm\":[\"*jpm\",\"jpgm\"],\"video/mj2\":[\"mj2\",\"mjp2\"],\"video/mp2t\":[\"ts\"],\"video/mp4\":[\"mp4\",\"mp4v\",\"mpg4\"],\"video/mpeg\":[\"mpeg\",\"mpg\",\"mpe\",\"m1v\",\"m2v\"],\"video/ogg\":[\"ogv\"],\"video/quicktime\":[\"qt\",\"mov\"],\"video/webm\":[\"webm\"]};", "module.exports = {\"application/prs.cww\":[\"cww\"],\"application/vnd.1000minds.decision-model+xml\":[\"1km\"],\"application/vnd.3gpp.pic-bw-large\":[\"plb\"],\"application/vnd.3gpp.pic-bw-small\":[\"psb\"],\"application/vnd.3gpp.pic-bw-var\":[\"pvb\"],\"application/vnd.3gpp2.tcap\":[\"tcap\"],\"application/vnd.3m.post-it-notes\":[\"pwn\"],\"application/vnd.accpac.simply.aso\":[\"aso\"],\"application/vnd.accpac.simply.imp\":[\"imp\"],\"application/vnd.acucobol\":[\"acu\"],\"application/vnd.acucorp\":[\"atc\",\"acutc\"],\"application/vnd.adobe.air-application-installer-package+zip\":[\"air\"],\"application/vnd.adobe.formscentral.fcdt\":[\"fcdt\"],\"application/vnd.adobe.fxp\":[\"fxp\",\"fxpl\"],\"application/vnd.adobe.xdp+xml\":[\"xdp\"],\"application/vnd.adobe.xfdf\":[\"xfdf\"],\"application/vnd.ahead.space\":[\"ahead\"],\"application/vnd.airzip.filesecure.azf\":[\"azf\"],\"application/vnd.airzip.filesecure.azs\":[\"azs\"],\"application/vnd.amazon.ebook\":[\"azw\"],\"application/vnd.americandynamics.acc\":[\"acc\"],\"application/vnd.amiga.ami\":[\"ami\"],\"application/vnd.android.package-archive\":[\"apk\"],\"application/vnd.anser-web-certificate-issue-initiation\":[\"cii\"],\"application/vnd.anser-web-funds-transfer-initiation\":[\"fti\"],\"application/vnd.antix.game-component\":[\"atx\"],\"application/vnd.apple.installer+xml\":[\"mpkg\"],\"application/vnd.apple.keynote\":[\"key\"],\"application/vnd.apple.mpegurl\":[\"m3u8\"],\"application/vnd.apple.numbers\":[\"numbers\"],\"application/vnd.apple.pages\":[\"pages\"],\"application/vnd.apple.pkpass\":[\"pkpass\"],\"application/vnd.aristanetworks.swi\":[\"swi\"],\"application/vnd.astraea-software.iota\":[\"iota\"],\"application/vnd.audiograph\":[\"aep\"],\"application/vnd.balsamiq.bmml+xml\":[\"bmml\"],\"application/vnd.blueice.multipass\":[\"mpm\"],\"application/vnd.bmi\":[\"bmi\"],\"application/vnd.businessobjects\":[\"rep\"],\"application/vnd.chemdraw+xml\":[\"cdxml\"],\"application/vnd.chipnuts.karaoke-mmd\":[\"mmd\"],\"application/vnd.cinderella\":[\"cdy\"],\"application/vnd.citationstyles.style+xml\":[\"csl\"],\"application/vnd.claymore\":[\"cla\"],\"application/vnd.cloanto.rp9\":[\"rp9\"],\"application/vnd.clonk.c4group\":[\"c4g\",\"c4d\",\"c4f\",\"c4p\",\"c4u\"],\"application/vnd.cluetrust.cartomobile-config\":[\"c11amc\"],\"application/vnd.cluetrust.cartomobile-config-pkg\":[\"c11amz\"],\"application/vnd.commonspace\":[\"csp\"],\"application/vnd.contact.cmsg\":[\"cdbcmsg\"],\"application/vnd.cosmocaller\":[\"cmc\"],\"application/vnd.crick.clicker\":[\"clkx\"],\"application/vnd.crick.clicker.keyboard\":[\"clkk\"],\"application/vnd.crick.clicker.palette\":[\"clkp\"],\"application/vnd.crick.clicker.template\":[\"clkt\"],\"application/vnd.crick.clicker.wordbank\":[\"clkw\"],\"application/vnd.criticaltools.wbs+xml\":[\"wbs\"],\"application/vnd.ctc-posml\":[\"pml\"],\"application/vnd.cups-ppd\":[\"ppd\"],\"application/vnd.curl.car\":[\"car\"],\"application/vnd.curl.pcurl\":[\"pcurl\"],\"application/vnd.dart\":[\"dart\"],\"application/vnd.data-vision.rdz\":[\"rdz\"],\"application/vnd.dbf\":[\"dbf\"],\"application/vnd.dece.data\":[\"uvf\",\"uvvf\",\"uvd\",\"uvvd\"],\"application/vnd.dece.ttml+xml\":[\"uvt\",\"uvvt\"],\"application/vnd.dece.unspecified\":[\"uvx\",\"uvvx\"],\"application/vnd.dece.zip\":[\"uvz\",\"uvvz\"],\"application/vnd.denovo.fcselayout-link\":[\"fe_launch\"],\"application/vnd.dna\":[\"dna\"],\"application/vnd.dolby.mlp\":[\"mlp\"],\"application/vnd.dpgraph\":[\"dpg\"],\"application/vnd.dreamfactory\":[\"dfac\"],\"application/vnd.ds-keypoint\":[\"kpxx\"],\"application/vnd.dvb.ait\":[\"ait\"],\"application/vnd.dvb.service\":[\"svc\"],\"application/vnd.dynageo\":[\"geo\"],\"application/vnd.ecowin.chart\":[\"mag\"],\"application/vnd.enliven\":[\"nml\"],\"application/vnd.epson.esf\":[\"esf\"],\"application/vnd.epson.msf\":[\"msf\"],\"application/vnd.epson.quickanime\":[\"qam\"],\"application/vnd.epson.salt\":[\"slt\"],\"application/vnd.epson.ssf\":[\"ssf\"],\"application/vnd.eszigno3+xml\":[\"es3\",\"et3\"],\"application/vnd.ezpix-album\":[\"ez2\"],\"application/vnd.ezpix-package\":[\"ez3\"],\"application/vnd.fdf\":[\"fdf\"],\"application/vnd.fdsn.mseed\":[\"mseed\"],\"application/vnd.fdsn.seed\":[\"seed\",\"dataless\"],\"application/vnd.flographit\":[\"gph\"],\"application/vnd.fluxtime.clip\":[\"ftc\"],\"application/vnd.framemaker\":[\"fm\",\"frame\",\"maker\",\"book\"],\"application/vnd.frogans.fnc\":[\"fnc\"],\"application/vnd.frogans.ltf\":[\"ltf\"],\"application/vnd.fsc.weblaunch\":[\"fsc\"],\"application/vnd.fujitsu.oasys\":[\"oas\"],\"application/vnd.fujitsu.oasys2\":[\"oa2\"],\"application/vnd.fujitsu.oasys3\":[\"oa3\"],\"application/vnd.fujitsu.oasysgp\":[\"fg5\"],\"application/vnd.fujitsu.oasysprs\":[\"bh2\"],\"application/vnd.fujixerox.ddd\":[\"ddd\"],\"application/vnd.fujixerox.docuworks\":[\"xdw\"],\"application/vnd.fujixerox.docuworks.binder\":[\"xbd\"],\"application/vnd.fuzzysheet\":[\"fzs\"],\"application/vnd.genomatix.tuxedo\":[\"txd\"],\"application/vnd.geogebra.file\":[\"ggb\"],\"application/vnd.geogebra.tool\":[\"ggt\"],\"application/vnd.geometry-explorer\":[\"gex\",\"gre\"],\"application/vnd.geonext\":[\"gxt\"],\"application/vnd.geoplan\":[\"g2w\"],\"application/vnd.geospace\":[\"g3w\"],\"application/vnd.gmx\":[\"gmx\"],\"application/vnd.google-apps.document\":[\"gdoc\"],\"application/vnd.google-apps.presentation\":[\"gslides\"],\"application/vnd.google-apps.spreadsheet\":[\"gsheet\"],\"application/vnd.google-earth.kml+xml\":[\"kml\"],\"application/vnd.google-earth.kmz\":[\"kmz\"],\"application/vnd.grafeq\":[\"gqf\",\"gqs\"],\"application/vnd.groove-account\":[\"gac\"],\"application/vnd.groove-help\":[\"ghf\"],\"application/vnd.groove-identity-message\":[\"gim\"],\"application/vnd.groove-injector\":[\"grv\"],\"application/vnd.groove-tool-message\":[\"gtm\"],\"application/vnd.groove-tool-template\":[\"tpl\"],\"application/vnd.groove-vcard\":[\"vcg\"],\"application/vnd.hal+xml\":[\"hal\"],\"application/vnd.handheld-entertainment+xml\":[\"zmm\"],\"application/vnd.hbci\":[\"hbci\"],\"application/vnd.hhe.lesson-player\":[\"les\"],\"application/vnd.hp-hpgl\":[\"hpgl\"],\"application/vnd.hp-hpid\":[\"hpid\"],\"application/vnd.hp-hps\":[\"hps\"],\"application/vnd.hp-jlyt\":[\"jlt\"],\"application/vnd.hp-pcl\":[\"pcl\"],\"application/vnd.hp-pclxl\":[\"pclxl\"],\"application/vnd.hydrostatix.sof-data\":[\"sfd-hdstx\"],\"application/vnd.ibm.minipay\":[\"mpy\"],\"application/vnd.ibm.modcap\":[\"afp\",\"listafp\",\"list3820\"],\"application/vnd.ibm.rights-management\":[\"irm\"],\"application/vnd.ibm.secure-container\":[\"sc\"],\"application/vnd.iccprofile\":[\"icc\",\"icm\"],\"application/vnd.igloader\":[\"igl\"],\"application/vnd.immervision-ivp\":[\"ivp\"],\"application/vnd.immervision-ivu\":[\"ivu\"],\"application/vnd.insors.igm\":[\"igm\"],\"application/vnd.intercon.formnet\":[\"xpw\",\"xpx\"],\"application/vnd.intergeo\":[\"i2g\"],\"application/vnd.intu.qbo\":[\"qbo\"],\"application/vnd.intu.qfx\":[\"qfx\"],\"application/vnd.ipunplugged.rcprofile\":[\"rcprofile\"],\"application/vnd.irepository.package+xml\":[\"irp\"],\"application/vnd.is-xpr\":[\"xpr\"],\"application/vnd.isac.fcs\":[\"fcs\"],\"application/vnd.jam\":[\"jam\"],\"application/vnd.jcp.javame.midlet-rms\":[\"rms\"],\"application/vnd.jisp\":[\"jisp\"],\"application/vnd.joost.joda-archive\":[\"joda\"],\"application/vnd.kahootz\":[\"ktz\",\"ktr\"],\"application/vnd.kde.karbon\":[\"karbon\"],\"application/vnd.kde.kchart\":[\"chrt\"],\"application/vnd.kde.kformula\":[\"kfo\"],\"application/vnd.kde.kivio\":[\"flw\"],\"application/vnd.kde.kontour\":[\"kon\"],\"application/vnd.kde.kpresenter\":[\"kpr\",\"kpt\"],\"application/vnd.kde.kspread\":[\"ksp\"],\"application/vnd.kde.kword\":[\"kwd\",\"kwt\"],\"application/vnd.kenameaapp\":[\"htke\"],\"application/vnd.kidspiration\":[\"kia\"],\"application/vnd.kinar\":[\"kne\",\"knp\"],\"application/vnd.koan\":[\"skp\",\"skd\",\"skt\",\"skm\"],\"application/vnd.kodak-descriptor\":[\"sse\"],\"application/vnd.las.las+xml\":[\"lasxml\"],\"application/vnd.llamagraphics.life-balance.desktop\":[\"lbd\"],\"application/vnd.llamagraphics.life-balance.exchange+xml\":[\"lbe\"],\"application/vnd.lotus-1-2-3\":[\"123\"],\"application/vnd.lotus-approach\":[\"apr\"],\"application/vnd.lotus-freelance\":[\"pre\"],\"application/vnd.lotus-notes\":[\"nsf\"],\"application/vnd.lotus-organizer\":[\"org\"],\"application/vnd.lotus-screencam\":[\"scm\"],\"application/vnd.lotus-wordpro\":[\"lwp\"],\"application/vnd.macports.portpkg\":[\"portpkg\"],\"application/vnd.mapbox-vector-tile\":[\"mvt\"],\"application/vnd.mcd\":[\"mcd\"],\"application/vnd.medcalcdata\":[\"mc1\"],\"application/vnd.mediastation.cdkey\":[\"cdkey\"],\"application/vnd.mfer\":[\"mwf\"],\"application/vnd.mfmp\":[\"mfm\"],\"application/vnd.micrografx.flo\":[\"flo\"],\"application/vnd.micrografx.igx\":[\"igx\"],\"application/vnd.mif\":[\"mif\"],\"application/vnd.mobius.daf\":[\"daf\"],\"application/vnd.mobius.dis\":[\"dis\"],\"application/vnd.mobius.mbk\":[\"mbk\"],\"application/vnd.mobius.mqy\":[\"mqy\"],\"application/vnd.mobius.msl\":[\"msl\"],\"application/vnd.mobius.plc\":[\"plc\"],\"application/vnd.mobius.txf\":[\"txf\"],\"application/vnd.mophun.application\":[\"mpn\"],\"application/vnd.mophun.certificate\":[\"mpc\"],\"application/vnd.mozilla.xul+xml\":[\"xul\"],\"application/vnd.ms-artgalry\":[\"cil\"],\"application/vnd.ms-cab-compressed\":[\"cab\"],\"application/vnd.ms-excel\":[\"xls\",\"xlm\",\"xla\",\"xlc\",\"xlt\",\"xlw\"],\"application/vnd.ms-excel.addin.macroenabled.12\":[\"xlam\"],\"application/vnd.ms-excel.sheet.binary.macroenabled.12\":[\"xlsb\"],\"application/vnd.ms-excel.sheet.macroenabled.12\":[\"xlsm\"],\"application/vnd.ms-excel.template.macroenabled.12\":[\"xltm\"],\"application/vnd.ms-fontobject\":[\"eot\"],\"application/vnd.ms-htmlhelp\":[\"chm\"],\"application/vnd.ms-ims\":[\"ims\"],\"application/vnd.ms-lrm\":[\"lrm\"],\"application/vnd.ms-officetheme\":[\"thmx\"],\"application/vnd.ms-outlook\":[\"msg\"],\"application/vnd.ms-pki.seccat\":[\"cat\"],\"application/vnd.ms-pki.stl\":[\"*stl\"],\"application/vnd.ms-powerpoint\":[\"ppt\",\"pps\",\"pot\"],\"application/vnd.ms-powerpoint.addin.macroenabled.12\":[\"ppam\"],\"application/vnd.ms-powerpoint.presentation.macroenabled.12\":[\"pptm\"],\"application/vnd.ms-powerpoint.slide.macroenabled.12\":[\"sldm\"],\"application/vnd.ms-powerpoint.slideshow.macroenabled.12\":[\"ppsm\"],\"application/vnd.ms-powerpoint.template.macroenabled.12\":[\"potm\"],\"application/vnd.ms-project\":[\"mpp\",\"mpt\"],\"application/vnd.ms-word.document.macroenabled.12\":[\"docm\"],\"application/vnd.ms-word.template.macroenabled.12\":[\"dotm\"],\"application/vnd.ms-works\":[\"wps\",\"wks\",\"wcm\",\"wdb\"],\"application/vnd.ms-wpl\":[\"wpl\"],\"application/vnd.ms-xpsdocument\":[\"xps\"],\"application/vnd.mseq\":[\"mseq\"],\"application/vnd.musician\":[\"mus\"],\"application/vnd.muvee.style\":[\"msty\"],\"application/vnd.mynfc\":[\"taglet\"],\"application/vnd.neurolanguage.nlu\":[\"nlu\"],\"application/vnd.nitf\":[\"ntf\",\"nitf\"],\"application/vnd.noblenet-directory\":[\"nnd\"],\"application/vnd.noblenet-sealer\":[\"nns\"],\"application/vnd.noblenet-web\":[\"nnw\"],\"application/vnd.nokia.n-gage.ac+xml\":[\"*ac\"],\"application/vnd.nokia.n-gage.data\":[\"ngdat\"],\"application/vnd.nokia.n-gage.symbian.install\":[\"n-gage\"],\"application/vnd.nokia.radio-preset\":[\"rpst\"],\"application/vnd.nokia.radio-presets\":[\"rpss\"],\"application/vnd.novadigm.edm\":[\"edm\"],\"application/vnd.novadigm.edx\":[\"edx\"],\"application/vnd.novadigm.ext\":[\"ext\"],\"application/vnd.oasis.opendocument.chart\":[\"odc\"],\"application/vnd.oasis.opendocument.chart-template\":[\"otc\"],\"application/vnd.oasis.opendocument.database\":[\"odb\"],\"application/vnd.oasis.opendocument.formula\":[\"odf\"],\"application/vnd.oasis.opendocument.formula-template\":[\"odft\"],\"application/vnd.oasis.opendocument.graphics\":[\"odg\"],\"application/vnd.oasis.opendocument.graphics-template\":[\"otg\"],\"application/vnd.oasis.opendocument.image\":[\"odi\"],\"application/vnd.oasis.opendocument.image-template\":[\"oti\"],\"application/vnd.oasis.opendocument.presentation\":[\"odp\"],\"application/vnd.oasis.opendocument.presentation-template\":[\"otp\"],\"application/vnd.oasis.opendocument.spreadsheet\":[\"ods\"],\"application/vnd.oasis.opendocument.spreadsheet-template\":[\"ots\"],\"application/vnd.oasis.opendocument.text\":[\"odt\"],\"application/vnd.oasis.opendocument.text-master\":[\"odm\"],\"application/vnd.oasis.opendocument.text-template\":[\"ott\"],\"application/vnd.oasis.opendocument.text-web\":[\"oth\"],\"application/vnd.olpc-sugar\":[\"xo\"],\"application/vnd.oma.dd2+xml\":[\"dd2\"],\"application/vnd.openblox.game+xml\":[\"obgx\"],\"application/vnd.openofficeorg.extension\":[\"oxt\"],\"application/vnd.openstreetmap.data+xml\":[\"osm\"],\"application/vnd.openxmlformats-officedocument.presentationml.presentation\":[\"pptx\"],\"application/vnd.openxmlformats-officedocument.presentationml.slide\":[\"sldx\"],\"application/vnd.openxmlformats-officedocument.presentationml.slideshow\":[\"ppsx\"],\"application/vnd.openxmlformats-officedocument.presentationml.template\":[\"potx\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\":[\"xlsx\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.template\":[\"xltx\"],\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":[\"docx\"],\"application/vnd.openxmlformats-officedocument.wordprocessingml.template\":[\"dotx\"],\"application/vnd.osgeo.mapguide.package\":[\"mgp\"],\"application/vnd.osgi.dp\":[\"dp\"],\"application/vnd.osgi.subsystem\":[\"esa\"],\"application/vnd.palm\":[\"pdb\",\"pqa\",\"oprc\"],\"application/vnd.pawaafile\":[\"paw\"],\"application/vnd.pg.format\":[\"str\"],\"application/vnd.pg.osasli\":[\"ei6\"],\"application/vnd.picsel\":[\"efif\"],\"application/vnd.pmi.widget\":[\"wg\"],\"application/vnd.pocketlearn\":[\"plf\"],\"application/vnd.powerbuilder6\":[\"pbd\"],\"application/vnd.previewsystems.box\":[\"box\"],\"application/vnd.proteus.magazine\":[\"mgz\"],\"application/vnd.publishare-delta-tree\":[\"qps\"],\"application/vnd.pvi.ptid1\":[\"ptid\"],\"application/vnd.quark.quarkxpress\":[\"qxd\",\"qxt\",\"qwd\",\"qwt\",\"qxl\",\"qxb\"],\"application/vnd.rar\":[\"rar\"],\"application/vnd.realvnc.bed\":[\"bed\"],\"application/vnd.recordare.musicxml\":[\"mxl\"],\"application/vnd.recordare.musicxml+xml\":[\"musicxml\"],\"application/vnd.rig.cryptonote\":[\"cryptonote\"],\"application/vnd.rim.cod\":[\"cod\"],\"application/vnd.rn-realmedia\":[\"rm\"],\"application/vnd.rn-realmedia-vbr\":[\"rmvb\"],\"application/vnd.route66.link66+xml\":[\"link66\"],\"application/vnd.sailingtracker.track\":[\"st\"],\"application/vnd.seemail\":[\"see\"],\"application/vnd.sema\":[\"sema\"],\"application/vnd.semd\":[\"semd\"],\"application/vnd.semf\":[\"semf\"],\"application/vnd.shana.informed.formdata\":[\"ifm\"],\"application/vnd.shana.informed.formtemplate\":[\"itp\"],\"application/vnd.shana.informed.interchange\":[\"iif\"],\"application/vnd.shana.informed.package\":[\"ipk\"],\"application/vnd.simtech-mindmapper\":[\"twd\",\"twds\"],\"application/vnd.smaf\":[\"mmf\"],\"application/vnd.smart.teacher\":[\"teacher\"],\"application/vnd.software602.filler.form+xml\":[\"fo\"],\"application/vnd.solent.sdkm+xml\":[\"sdkm\",\"sdkd\"],\"application/vnd.spotfire.dxp\":[\"dxp\"],\"application/vnd.spotfire.sfs\":[\"sfs\"],\"application/vnd.stardivision.calc\":[\"sdc\"],\"application/vnd.stardivision.draw\":[\"sda\"],\"application/vnd.stardivision.impress\":[\"sdd\"],\"application/vnd.stardivision.math\":[\"smf\"],\"application/vnd.stardivision.writer\":[\"sdw\",\"vor\"],\"application/vnd.stardivision.writer-global\":[\"sgl\"],\"application/vnd.stepmania.package\":[\"smzip\"],\"application/vnd.stepmania.stepchart\":[\"sm\"],\"application/vnd.sun.wadl+xml\":[\"wadl\"],\"application/vnd.sun.xml.calc\":[\"sxc\"],\"application/vnd.sun.xml.calc.template\":[\"stc\"],\"application/vnd.sun.xml.draw\":[\"sxd\"],\"application/vnd.sun.xml.draw.template\":[\"std\"],\"application/vnd.sun.xml.impress\":[\"sxi\"],\"application/vnd.sun.xml.impress.template\":[\"sti\"],\"application/vnd.sun.xml.math\":[\"sxm\"],\"application/vnd.sun.xml.writer\":[\"sxw\"],\"application/vnd.sun.xml.writer.global\":[\"sxg\"],\"application/vnd.sun.xml.writer.template\":[\"stw\"],\"application/vnd.sus-calendar\":[\"sus\",\"susp\"],\"application/vnd.svd\":[\"svd\"],\"application/vnd.symbian.install\":[\"sis\",\"sisx\"],\"application/vnd.syncml+xml\":[\"xsm\"],\"application/vnd.syncml.dm+wbxml\":[\"bdm\"],\"application/vnd.syncml.dm+xml\":[\"xdm\"],\"application/vnd.syncml.dmddf+xml\":[\"ddf\"],\"application/vnd.tao.intent-module-archive\":[\"tao\"],\"application/vnd.tcpdump.pcap\":[\"pcap\",\"cap\",\"dmp\"],\"application/vnd.tmobile-livetv\":[\"tmo\"],\"application/vnd.trid.tpt\":[\"tpt\"],\"application/vnd.triscape.mxs\":[\"mxs\"],\"application/vnd.trueapp\":[\"tra\"],\"application/vnd.ufdl\":[\"ufd\",\"ufdl\"],\"application/vnd.uiq.theme\":[\"utz\"],\"application/vnd.umajin\":[\"umj\"],\"application/vnd.unity\":[\"unityweb\"],\"application/vnd.uoml+xml\":[\"uoml\"],\"application/vnd.vcx\":[\"vcx\"],\"application/vnd.visio\":[\"vsd\",\"vst\",\"vss\",\"vsw\"],\"application/vnd.visionary\":[\"vis\"],\"application/vnd.vsf\":[\"vsf\"],\"application/vnd.wap.wbxml\":[\"wbxml\"],\"application/vnd.wap.wmlc\":[\"wmlc\"],\"application/vnd.wap.wmlscriptc\":[\"wmlsc\"],\"application/vnd.webturbo\":[\"wtb\"],\"application/vnd.wolfram.player\":[\"nbp\"],\"application/vnd.wordperfect\":[\"wpd\"],\"application/vnd.wqd\":[\"wqd\"],\"application/vnd.wt.stf\":[\"stf\"],\"application/vnd.xara\":[\"xar\"],\"application/vnd.xfdl\":[\"xfdl\"],\"application/vnd.yamaha.hv-dic\":[\"hvd\"],\"application/vnd.yamaha.hv-script\":[\"hvs\"],\"application/vnd.yamaha.hv-voice\":[\"hvp\"],\"application/vnd.yamaha.openscoreformat\":[\"osf\"],\"application/vnd.yamaha.openscoreformat.osfpvg+xml\":[\"osfpvg\"],\"application/vnd.yamaha.smaf-audio\":[\"saf\"],\"application/vnd.yamaha.smaf-phrase\":[\"spf\"],\"application/vnd.yellowriver-custom-menu\":[\"cmp\"],\"application/vnd.zul\":[\"zir\",\"zirz\"],\"application/vnd.zzazz.deck+xml\":[\"zaz\"],\"application/x-7z-compressed\":[\"7z\"],\"application/x-abiword\":[\"abw\"],\"application/x-ace-compressed\":[\"ace\"],\"application/x-apple-diskimage\":[\"*dmg\"],\"application/x-arj\":[\"arj\"],\"application/x-authorware-bin\":[\"aab\",\"x32\",\"u32\",\"vox\"],\"application/x-authorware-map\":[\"aam\"],\"application/x-authorware-seg\":[\"aas\"],\"application/x-bcpio\":[\"bcpio\"],\"application/x-bdoc\":[\"*bdoc\"],\"application/x-bittorrent\":[\"torrent\"],\"application/x-blorb\":[\"blb\",\"blorb\"],\"application/x-bzip\":[\"bz\"],\"application/x-bzip2\":[\"bz2\",\"boz\"],\"application/x-cbr\":[\"cbr\",\"cba\",\"cbt\",\"cbz\",\"cb7\"],\"application/x-cdlink\":[\"vcd\"],\"application/x-cfs-compressed\":[\"cfs\"],\"application/x-chat\":[\"chat\"],\"application/x-chess-pgn\":[\"pgn\"],\"application/x-chrome-extension\":[\"crx\"],\"application/x-cocoa\":[\"cco\"],\"application/x-conference\":[\"nsc\"],\"application/x-cpio\":[\"cpio\"],\"application/x-csh\":[\"csh\"],\"application/x-debian-package\":[\"*deb\",\"udeb\"],\"application/x-dgc-compressed\":[\"dgc\"],\"application/x-director\":[\"dir\",\"dcr\",\"dxr\",\"cst\",\"cct\",\"cxt\",\"w3d\",\"fgd\",\"swa\"],\"application/x-doom\":[\"wad\"],\"application/x-dtbncx+xml\":[\"ncx\"],\"application/x-dtbook+xml\":[\"dtb\"],\"application/x-dtbresource+xml\":[\"res\"],\"application/x-dvi\":[\"dvi\"],\"application/x-envoy\":[\"evy\"],\"application/x-eva\":[\"eva\"],\"application/x-font-bdf\":[\"bdf\"],\"application/x-font-ghostscript\":[\"gsf\"],\"application/x-font-linux-psf\":[\"psf\"],\"application/x-font-pcf\":[\"pcf\"],\"application/x-font-snf\":[\"snf\"],\"application/x-font-type1\":[\"pfa\",\"pfb\",\"pfm\",\"afm\"],\"application/x-freearc\":[\"arc\"],\"application/x-futuresplash\":[\"spl\"],\"application/x-gca-compressed\":[\"gca\"],\"application/x-glulx\":[\"ulx\"],\"application/x-gnumeric\":[\"gnumeric\"],\"application/x-gramps-xml\":[\"gramps\"],\"application/x-gtar\":[\"gtar\"],\"application/x-hdf\":[\"hdf\"],\"application/x-httpd-php\":[\"php\"],\"application/x-install-instructions\":[\"install\"],\"application/x-iso9660-image\":[\"*iso\"],\"application/x-iwork-keynote-sffkey\":[\"*key\"],\"application/x-iwork-numbers-sffnumbers\":[\"*numbers\"],\"application/x-iwork-pages-sffpages\":[\"*pages\"],\"application/x-java-archive-diff\":[\"jardiff\"],\"application/x-java-jnlp-file\":[\"jnlp\"],\"application/x-keepass2\":[\"kdbx\"],\"application/x-latex\":[\"latex\"],\"application/x-lua-bytecode\":[\"luac\"],\"application/x-lzh-compressed\":[\"lzh\",\"lha\"],\"application/x-makeself\":[\"run\"],\"application/x-mie\":[\"mie\"],\"application/x-mobipocket-ebook\":[\"prc\",\"mobi\"],\"application/x-ms-application\":[\"application\"],\"application/x-ms-shortcut\":[\"lnk\"],\"application/x-ms-wmd\":[\"wmd\"],\"application/x-ms-wmz\":[\"wmz\"],\"application/x-ms-xbap\":[\"xbap\"],\"application/x-msaccess\":[\"mdb\"],\"application/x-msbinder\":[\"obd\"],\"application/x-mscardfile\":[\"crd\"],\"application/x-msclip\":[\"clp\"],\"application/x-msdos-program\":[\"*exe\"],\"application/x-msdownload\":[\"*exe\",\"*dll\",\"com\",\"bat\",\"*msi\"],\"application/x-msmediaview\":[\"mvb\",\"m13\",\"m14\"],\"application/x-msmetafile\":[\"*wmf\",\"*wmz\",\"*emf\",\"emz\"],\"application/x-msmoney\":[\"mny\"],\"application/x-mspublisher\":[\"pub\"],\"application/x-msschedule\":[\"scd\"],\"application/x-msterminal\":[\"trm\"],\"application/x-mswrite\":[\"wri\"],\"application/x-netcdf\":[\"nc\",\"cdf\"],\"application/x-ns-proxy-autoconfig\":[\"pac\"],\"application/x-nzb\":[\"nzb\"],\"application/x-perl\":[\"pl\",\"pm\"],\"application/x-pilot\":[\"*prc\",\"*pdb\"],\"application/x-pkcs12\":[\"p12\",\"pfx\"],\"application/x-pkcs7-certificates\":[\"p7b\",\"spc\"],\"application/x-pkcs7-certreqresp\":[\"p7r\"],\"application/x-rar-compressed\":[\"*rar\"],\"application/x-redhat-package-manager\":[\"rpm\"],\"application/x-research-info-systems\":[\"ris\"],\"application/x-sea\":[\"sea\"],\"application/x-sh\":[\"sh\"],\"application/x-shar\":[\"shar\"],\"application/x-shockwave-flash\":[\"swf\"],\"application/x-silverlight-app\":[\"xap\"],\"application/x-sql\":[\"sql\"],\"application/x-stuffit\":[\"sit\"],\"application/x-stuffitx\":[\"sitx\"],\"application/x-subrip\":[\"srt\"],\"application/x-sv4cpio\":[\"sv4cpio\"],\"application/x-sv4crc\":[\"sv4crc\"],\"application/x-t3vm-image\":[\"t3\"],\"application/x-tads\":[\"gam\"],\"application/x-tar\":[\"tar\"],\"application/x-tcl\":[\"tcl\",\"tk\"],\"application/x-tex\":[\"tex\"],\"application/x-tex-tfm\":[\"tfm\"],\"application/x-texinfo\":[\"texinfo\",\"texi\"],\"application/x-tgif\":[\"*obj\"],\"application/x-ustar\":[\"ustar\"],\"application/x-virtualbox-hdd\":[\"hdd\"],\"application/x-virtualbox-ova\":[\"ova\"],\"application/x-virtualbox-ovf\":[\"ovf\"],\"application/x-virtualbox-vbox\":[\"vbox\"],\"application/x-virtualbox-vbox-extpack\":[\"vbox-extpack\"],\"application/x-virtualbox-vdi\":[\"vdi\"],\"application/x-virtualbox-vhd\":[\"vhd\"],\"application/x-virtualbox-vmdk\":[\"vmdk\"],\"application/x-wais-source\":[\"src\"],\"application/x-web-app-manifest+json\":[\"webapp\"],\"application/x-x509-ca-cert\":[\"der\",\"crt\",\"pem\"],\"application/x-xfig\":[\"fig\"],\"application/x-xliff+xml\":[\"*xlf\"],\"application/x-xpinstall\":[\"xpi\"],\"application/x-xz\":[\"xz\"],\"application/x-zmachine\":[\"z1\",\"z2\",\"z3\",\"z4\",\"z5\",\"z6\",\"z7\",\"z8\"],\"audio/vnd.dece.audio\":[\"uva\",\"uvva\"],\"audio/vnd.digital-winds\":[\"eol\"],\"audio/vnd.dra\":[\"dra\"],\"audio/vnd.dts\":[\"dts\"],\"audio/vnd.dts.hd\":[\"dtshd\"],\"audio/vnd.lucent.voice\":[\"lvp\"],\"audio/vnd.ms-playready.media.pya\":[\"pya\"],\"audio/vnd.nuera.ecelp4800\":[\"ecelp4800\"],\"audio/vnd.nuera.ecelp7470\":[\"ecelp7470\"],\"audio/vnd.nuera.ecelp9600\":[\"ecelp9600\"],\"audio/vnd.rip\":[\"rip\"],\"audio/x-aac\":[\"aac\"],\"audio/x-aiff\":[\"aif\",\"aiff\",\"aifc\"],\"audio/x-caf\":[\"caf\"],\"audio/x-flac\":[\"flac\"],\"audio/x-m4a\":[\"*m4a\"],\"audio/x-matroska\":[\"mka\"],\"audio/x-mpegurl\":[\"m3u\"],\"audio/x-ms-wax\":[\"wax\"],\"audio/x-ms-wma\":[\"wma\"],\"audio/x-pn-realaudio\":[\"ram\",\"ra\"],\"audio/x-pn-realaudio-plugin\":[\"rmp\"],\"audio/x-realaudio\":[\"*ra\"],\"audio/x-wav\":[\"*wav\"],\"chemical/x-cdx\":[\"cdx\"],\"chemical/x-cif\":[\"cif\"],\"chemical/x-cmdf\":[\"cmdf\"],\"chemical/x-cml\":[\"cml\"],\"chemical/x-csml\":[\"csml\"],\"chemical/x-xyz\":[\"xyz\"],\"image/prs.btif\":[\"btif\"],\"image/prs.pti\":[\"pti\"],\"image/vnd.adobe.photoshop\":[\"psd\"],\"image/vnd.airzip.accelerator.azv\":[\"azv\"],\"image/vnd.dece.graphic\":[\"uvi\",\"uvvi\",\"uvg\",\"uvvg\"],\"image/vnd.djvu\":[\"djvu\",\"djv\"],\"image/vnd.dvb.subtitle\":[\"*sub\"],\"image/vnd.dwg\":[\"dwg\"],\"image/vnd.dxf\":[\"dxf\"],\"image/vnd.fastbidsheet\":[\"fbs\"],\"image/vnd.fpx\":[\"fpx\"],\"image/vnd.fst\":[\"fst\"],\"image/vnd.fujixerox.edmics-mmr\":[\"mmr\"],\"image/vnd.fujixerox.edmics-rlc\":[\"rlc\"],\"image/vnd.microsoft.icon\":[\"ico\"],\"image/vnd.ms-dds\":[\"dds\"],\"image/vnd.ms-modi\":[\"mdi\"],\"image/vnd.ms-photo\":[\"wdp\"],\"image/vnd.net-fpx\":[\"npx\"],\"image/vnd.pco.b16\":[\"b16\"],\"image/vnd.tencent.tap\":[\"tap\"],\"image/vnd.valve.source.texture\":[\"vtf\"],\"image/vnd.wap.wbmp\":[\"wbmp\"],\"image/vnd.xiff\":[\"xif\"],\"image/vnd.zbrush.pcx\":[\"pcx\"],\"image/x-3ds\":[\"3ds\"],\"image/x-cmu-raster\":[\"ras\"],\"image/x-cmx\":[\"cmx\"],\"image/x-freehand\":[\"fh\",\"fhc\",\"fh4\",\"fh5\",\"fh7\"],\"image/x-icon\":[\"*ico\"],\"image/x-jng\":[\"jng\"],\"image/x-mrsid-image\":[\"sid\"],\"image/x-ms-bmp\":[\"*bmp\"],\"image/x-pcx\":[\"*pcx\"],\"image/x-pict\":[\"pic\",\"pct\"],\"image/x-portable-anymap\":[\"pnm\"],\"image/x-portable-bitmap\":[\"pbm\"],\"image/x-portable-graymap\":[\"pgm\"],\"image/x-portable-pixmap\":[\"ppm\"],\"image/x-rgb\":[\"rgb\"],\"image/x-tga\":[\"tga\"],\"image/x-xbitmap\":[\"xbm\"],\"image/x-xpixmap\":[\"xpm\"],\"image/x-xwindowdump\":[\"xwd\"],\"message/vnd.wfa.wsc\":[\"wsc\"],\"model/vnd.collada+xml\":[\"dae\"],\"model/vnd.dwf\":[\"dwf\"],\"model/vnd.gdl\":[\"gdl\"],\"model/vnd.gtw\":[\"gtw\"],\"model/vnd.mts\":[\"mts\"],\"model/vnd.opengex\":[\"ogex\"],\"model/vnd.parasolid.transmit.binary\":[\"x_b\"],\"model/vnd.parasolid.transmit.text\":[\"x_t\"],\"model/vnd.sap.vds\":[\"vds\"],\"model/vnd.usdz+zip\":[\"usdz\"],\"model/vnd.valve.source.compiled-map\":[\"bsp\"],\"model/vnd.vtu\":[\"vtu\"],\"text/prs.lines.tag\":[\"dsc\"],\"text/vnd.curl\":[\"curl\"],\"text/vnd.curl.dcurl\":[\"dcurl\"],\"text/vnd.curl.mcurl\":[\"mcurl\"],\"text/vnd.curl.scurl\":[\"scurl\"],\"text/vnd.dvb.subtitle\":[\"sub\"],\"text/vnd.fly\":[\"fly\"],\"text/vnd.fmi.flexstor\":[\"flx\"],\"text/vnd.graphviz\":[\"gv\"],\"text/vnd.in3d.3dml\":[\"3dml\"],\"text/vnd.in3d.spot\":[\"spot\"],\"text/vnd.sun.j2me.app-descriptor\":[\"jad\"],\"text/vnd.wap.wml\":[\"wml\"],\"text/vnd.wap.wmlscript\":[\"wmls\"],\"text/x-asm\":[\"s\",\"asm\"],\"text/x-c\":[\"c\",\"cc\",\"cxx\",\"cpp\",\"h\",\"hh\",\"dic\"],\"text/x-component\":[\"htc\"],\"text/x-fortran\":[\"f\",\"for\",\"f77\",\"f90\"],\"text/x-handlebars-template\":[\"hbs\"],\"text/x-java-source\":[\"java\"],\"text/x-lua\":[\"lua\"],\"text/x-markdown\":[\"mkd\"],\"text/x-nfo\":[\"nfo\"],\"text/x-opml\":[\"opml\"],\"text/x-org\":[\"*org\"],\"text/x-pascal\":[\"p\",\"pas\"],\"text/x-processing\":[\"pde\"],\"text/x-sass\":[\"sass\"],\"text/x-scss\":[\"scss\"],\"text/x-setext\":[\"etx\"],\"text/x-sfv\":[\"sfv\"],\"text/x-suse-ymp\":[\"ymp\"],\"text/x-uuencode\":[\"uu\"],\"text/x-vcalendar\":[\"vcs\"],\"text/x-vcard\":[\"vcf\"],\"video/vnd.dece.hd\":[\"uvh\",\"uvvh\"],\"video/vnd.dece.mobile\":[\"uvm\",\"uvvm\"],\"video/vnd.dece.pd\":[\"uvp\",\"uvvp\"],\"video/vnd.dece.sd\":[\"uvs\",\"uvvs\"],\"video/vnd.dece.video\":[\"uvv\",\"uvvv\"],\"video/vnd.dvb.file\":[\"dvb\"],\"video/vnd.fvt\":[\"fvt\"],\"video/vnd.mpegurl\":[\"mxu\",\"m4u\"],\"video/vnd.ms-playready.media.pyv\":[\"pyv\"],\"video/vnd.uvvu.mp4\":[\"uvu\",\"uvvu\"],\"video/vnd.vivo\":[\"viv\"],\"video/x-f4v\":[\"f4v\"],\"video/x-fli\":[\"fli\"],\"video/x-flv\":[\"flv\"],\"video/x-m4v\":[\"m4v\"],\"video/x-matroska\":[\"mkv\",\"mk3d\",\"mks\"],\"video/x-mng\":[\"mng\"],\"video/x-ms-asf\":[\"asf\",\"asx\"],\"video/x-ms-vob\":[\"vob\"],\"video/x-ms-wm\":[\"wm\"],\"video/x-ms-wmv\":[\"wmv\"],\"video/x-ms-wmx\":[\"wmx\"],\"video/x-ms-wvx\":[\"wvx\"],\"video/x-msvideo\":[\"avi\"],\"video/x-sgi-movie\":[\"movie\"],\"video/x-smv\":[\"smv\"],\"x-conference/x-cooltalk\":[\"ice\"]};", "'use strict';\n\nlet Mime = require('./Mime');\nmodule.exports = new Mime(require('./types/standard'), require('./types/other'));\n", "import { IDisposable } from '@lumino/disposable';\nimport { IRenderMime } from '@jupyterlab/rendermime-interfaces';\nimport { PageConfig } from '@jupyterlab/coreutils';\nimport mime from 'mime';\n\nimport { Contents as ServerContents } from '@jupyterlab/services';\n\nimport { Token } from '@lumino/coreutils';\n\n/**\n * The token for the settings service.\n */\nexport const IContents = new Token<IContents>('@jupyterlite/contents:IContents');\n\n/**\n * The interface for the contents service.\n */\nexport interface IContents {\n /**\n * A promise that resolves after the contents have been full initialized.\n */\n ready: Promise<void>;\n\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options: The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the file is created.\n */\n newUntitled(\n options?: ServerContents.ICreateOptions,\n ): Promise<ServerContents.IModel | null>;\n\n /**\n * Copy a file into a given directory.\n *\n * @param path - The original file path.\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n */\n copy(path: string, toDir: string): Promise<ServerContents.IModel>;\n\n /**\n * Get a file or directory.\n *\n * @param path: The path to the file.\n * @param options: The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n */\n get(\n path: string,\n options?: ServerContents.IFetchOptions,\n ): Promise<ServerContents.IModel | null>;\n\n /**\n * Rename a file or directory.\n *\n * @param oldLocalPath - The original file path.\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with the new file content model when the file is renamed.\n */\n rename(oldLocalPath: string, newLocalPath: string): Promise<ServerContents.IModel>;\n\n /**\n * Save a file.\n *\n * @param path - The desired file path.\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the file is saved.\n */\n save(\n path: string,\n options?: Partial<ServerContents.IModel>,\n ): Promise<ServerContents.IModel | null>;\n\n /**\n * Delete a file.\n *\n * @param path - The path to the file.\n */\n delete(path: string): Promise<void>;\n\n /**\n * Create a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n */\n createCheckpoint(path: string): Promise<ServerContents.ICheckpointModel>;\n\n /**\n * List available checkpoints for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n */\n listCheckpoints(path: string): Promise<ServerContents.ICheckpointModel[]>;\n\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param path - The path of the file.\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n */\n restoreCheckpoint(path: string, checkpointID: string): Promise<void>;\n\n /**\n * Delete a checkpoint for a file.\n *\n * @param path - The path of the file.\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n */\n deleteCheckpoint(path: string, checkpointID: string): Promise<void>;\n}\n\n/**\n * Commonly-used mimetypes\n */\nexport namespace MIME {\n export const JSON = 'application/json';\n export const PLAIN_TEXT = 'text/plain';\n export const OCTET_STREAM = 'octet/stream';\n}\n\n/**\n * A namespace for file constructs.\n */\nexport namespace FILE {\n /**\n * Build-time configured file types.\n */\n const TYPES: Record<string, Partial<IRenderMime.IFileType>> = JSON.parse(\n PageConfig.getOption('fileTypes') || '{}',\n );\n\n /**\n * Get a mimetype (or fallback).\n */\n export function getType(ext: string, defaultType: string | null = null): string {\n ext = ext.toLowerCase();\n for (const fileType of Object.values(TYPES)) {\n for (const fileExt of fileType.extensions || []) {\n if (fileExt === ext && fileType.mimeTypes && fileType.mimeTypes.length) {\n return fileType.mimeTypes[0];\n }\n }\n }\n\n return mime.getType(ext) || defaultType || MIME.OCTET_STREAM;\n }\n\n /**\n * Determine whether the given extension matches a given fileFormat.\n */\n export function hasFormat(\n ext: string,\n fileFormat: 'base64' | 'text' | 'json',\n ): boolean {\n ext = ext.toLowerCase();\n for (const fileType of Object.values(TYPES)) {\n if (fileType.fileFormat !== fileFormat) {\n continue;\n }\n for (const fileExt of fileType.extensions || []) {\n if (fileExt === ext) {\n return true;\n }\n }\n }\n return false;\n }\n}\n\n/**\n * The token for the BroadcastChannel broadcaster.\n */\nexport const IBroadcastChannelWrapper = new Token<IBroadcastChannelWrapper>(\n '@jupyterlite/contents:IBroadcastChannelWrapper',\n);\n\nexport interface IBroadcastChannelWrapper extends IDisposable {\n enable(): void;\n disable(): void;\n enabled: boolean;\n}\n", "import { PageConfig, URLExt } from '@jupyterlab/coreutils';\n\nimport { Contents as ServerContents } from '@jupyterlab/services';\n\nimport { INotebookContent } from '@jupyterlab/nbformat';\n\nimport { PathExt } from '@jupyterlab/coreutils';\n\nimport type localforage from 'localforage';\n\nimport { IContents, MIME, FILE } from './tokens';\nimport { PromiseDelegate } from '@lumino/coreutils';\n\nexport type IModel = ServerContents.IModel;\n\n/**\n * The name of the local storage.\n */\nconst DEFAULT_STORAGE_NAME = 'JupyterLite Storage';\n\n/**\n * The number of checkpoints to save.\n */\nconst N_CHECKPOINTS = 5;\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8');\n\n/**\n * A class to handle requests to /api/contents\n */\nexport class Contents implements IContents {\n /**\n * Construct a new localForage-powered contents provider\n */\n constructor(options: Contents.IOptions) {\n this._localforage = options.localforage;\n this._storageName = options.storageName || DEFAULT_STORAGE_NAME;\n this._storageDrivers = options.storageDrivers || null;\n this._ready = new PromiseDelegate();\n }\n\n /**\n * Finish any initialization after server has started and all extensions are applied.\n */\n async initialize() {\n await this.initStorage();\n this._ready.resolve(void 0);\n }\n\n /**\n * Initialize all storage instances\n */\n protected async initStorage(): Promise<void> {\n this._storage = this.createDefaultStorage();\n this._counters = this.createDefaultCounters();\n this._checkpoints = this.createDefaultCheckpoints();\n }\n\n /**\n * A promise that resolves once all storage is fully initialized.\n */\n get ready(): Promise<void> {\n return this._ready.promise;\n }\n\n /**\n * A lazy reference to the underlying storage.\n */\n protected get storage(): Promise<LocalForage> {\n return this.ready.then(() => this._storage as LocalForage);\n }\n\n /**\n * A lazy reference to the underlying counters.\n */\n protected get counters(): Promise<LocalForage> {\n return this.ready.then(() => this._counters as LocalForage);\n }\n\n /**\n * A lazy reference to the underlying checkpoints.\n */\n protected get checkpoints(): Promise<LocalForage> {\n return this.ready.then(() => this._checkpoints as LocalForage);\n }\n\n /**\n * Get default options for localForage instances\n */\n protected get defaultStorageOptions(): LocalForageOptions {\n const driver =\n this._storageDrivers && this._storageDrivers.length ? this._storageDrivers : null;\n return {\n version: 1,\n name: this._storageName,\n ...(driver ? { driver } : {}),\n };\n }\n\n /**\n * Initialize the default storage for contents.\n */\n protected createDefaultStorage(): LocalForage {\n return this._localforage.createInstance({\n description: 'Offline Storage for Notebooks and Files',\n storeName: 'files',\n ...this.defaultStorageOptions,\n });\n }\n\n /**\n * Initialize the default storage for counting file suffixes.\n */\n protected createDefaultCounters(): LocalForage {\n return this._localforage.createInstance({\n description: 'Store the current file suffix counters',\n storeName: 'counters',\n ...this.defaultStorageOptions,\n });\n }\n\n /**\n * Create the default checkpoint storage.\n */\n protected createDefaultCheckpoints(): LocalForage {\n return this._localforage.createInstance({\n description: 'Offline Storage for Checkpoints',\n storeName: 'checkpoints',\n ...this.defaultStorageOptions,\n });\n }\n\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options: The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the file is created.\n */\n async newUntitled(options?: ServerContents.ICreateOptions): Promise<IModel | null> {\n const path = options?.path ?? '';\n const type = options?.type ?? 'notebook';\n const created = new Date().toISOString();\n\n let dirname = PathExt.dirname(path);\n const basename = PathExt.basename(path);\n const extname = PathExt.extname(path);\n const item = await this.get(dirname);\n\n // handle the case of \"Save As\", where the path points to the new file\n // to create, e.g. subfolder/example-copy.ipynb\n let name = '';\n if (path && !extname && item) {\n // directory\n dirname = `${path}/`;\n name = '';\n } else if (dirname && basename) {\n // file in a subfolder\n dirname = `${dirname}/`;\n name = basename;\n } else {\n // file at the top level\n dirname = '';\n name = path;\n }\n\n let file: IModel;\n switch (type) {\n case 'directory': {\n const counter = await this._incrementCounter('directory');\n name = `Untitled Folder${counter || ''}`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format: 'json',\n mimetype: '',\n content: null,\n size: 0,\n writable: true,\n type: 'directory',\n };\n break;\n }\n case 'notebook': {\n const counter = await this._incrementCounter('notebook');\n name = name || `Untitled${counter || ''}.ipynb`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format: 'json',\n mimetype: MIME.JSON,\n content: Private.EMPTY_NB,\n size: encoder.encode(JSON.stringify(Private.EMPTY_NB)).length,\n writable: true,\n type: 'notebook',\n };\n break;\n }\n default: {\n const ext = options?.ext ?? '.txt';\n const counter = await this._incrementCounter('file');\n const mimetype = FILE.getType(ext) || MIME.OCTET_STREAM;\n\n let format: ServerContents.FileFormat;\n if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {\n format = 'text';\n } else if (ext.indexOf('json') !== -1 || ext.indexOf('ipynb') !== -1) {\n format = 'json';\n } else {\n format = 'base64';\n }\n\n name = name || `untitled${counter || ''}${ext}`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format,\n mimetype,\n content: '',\n size: 0,\n writable: true,\n type: 'file',\n };\n break;\n }\n }\n\n const key = file.path;\n await (await this.storage).setItem(key, file);\n return file;\n }\n\n /**\n * Copy a file into a given directory.\n *\n * @param path - The original file path.\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n */\n async copy(path: string, toDir: string): Promise<IModel> {\n let name = PathExt.basename(path);\n toDir = toDir === '' ? '' : `${PathExt.removeSlash(toDir)}/`;\n // TODO: better handle naming collisions with existing files\n while (await this.get(`${toDir}${name}`, { content: true })) {\n const ext = PathExt.extname(name);\n const base = name.replace(ext, '');\n name = `${base} (copy)${ext}`;\n }\n const toPath = `${toDir}${name}`;\n let item = await this.get(path, { content: true });\n if (!item) {\n throw Error(`Could not find file with path ${path}`);\n }\n item = {\n ...item,\n name,\n path: toPath,\n };\n await (await this.storage).setItem(toPath, item);\n return item;\n }\n\n /**\n * Get a file or directory.\n *\n * @param path: The path to the file.\n * @param options: The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n */\n async get(\n path: string,\n options?: ServerContents.IFetchOptions,\n ): Promise<IModel | null> {\n // remove leading slash\n path = decodeURIComponent(path.replace(/^\\//, ''));\n\n if (path === '') {\n return await this._getFolder(path);\n }\n\n const storage = await this.storage;\n const item = await storage.getItem(path);\n const serverItem = await this._getServerContents(path, options);\n\n const model = (item || serverItem) as IModel | null;\n\n if (!model) {\n return null;\n }\n\n if (!options?.content) {\n return {\n size: 0,\n ...model,\n content: null,\n };\n }\n\n // for directories, find all files with the path as the prefix\n if (model.type === 'directory') {\n const contentMap = new Map<string, IModel>();\n await storage.iterate<IModel, void>((file, key) => {\n // use an additional slash to not include the directory itself\n if (key === `${path}/${file.name}`) {\n contentMap.set(file.name, file);\n }\n });\n\n const serverContents: IModel[] = serverItem\n ? serverItem.content\n : Array.from((await this._getServerDirectory(path)).values());\n for (const file of serverContents) {\n if (!contentMap.has(file.name)) {\n contentMap.set(file.name, file);\n }\n }\n\n const content = [...contentMap.values()];\n\n return {\n name: PathExt.basename(path),\n path,\n last_modified: model.last_modified,\n created: model.created,\n format: 'json',\n mimetype: MIME.JSON,\n content,\n size: 0,\n writable: true,\n type: 'directory',\n };\n }\n return model;\n }\n\n /**\n * Rename a file or directory.\n *\n * @param oldLocalPath - The original file path.\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with the new file content model when the file is renamed.\n */\n async rename(oldLocalPath: string, newLocalPath: string): Promise<IModel> {\n const path = decodeURIComponent(oldLocalPath);\n const file = await this.get(path, { content: true });\n if (!file) {\n throw Error(`Could not find file with path ${path}`);\n }\n const modified = new Date().toISOString();\n const name = PathExt.basename(newLocalPath);\n const newFile = {\n ...file,\n name,\n path: newLocalPath,\n last_modified: modified,\n };\n const storage = await this.storage;\n await storage.setItem(newLocalPath, newFile);\n // remove the old file\n await storage.removeItem(path);\n // remove the corresponding checkpoint\n await (await this.checkpoints).removeItem(path);\n // if a directory, recurse through all children\n if (file.type === 'directory') {\n let child: IModel;\n for (child of file.content) {\n await this.rename(\n URLExt.join(oldLocalPath, child.name),\n URLExt.join(newLocalPath, child.name),\n );\n }\n }\n\n return newFile;\n }\n\n /**\n * Save a file.\n *\n * @param path - The desired file path.\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the file is saved.\n */\n async save(path: string, options: Partial<IModel> = {}): Promise<IModel | null> {\n path = decodeURIComponent(path);\n\n // process the file if coming from an upload\n const ext = PathExt.extname(options.name ?? '');\n const chunk = options.chunk;\n\n // retrieve the content if it is a later chunk or the last one\n // the new content will then be appended to the existing one\n const appendChunk = chunk ? chunk > 1 || chunk === -1 : false;\n let item: IModel | null = await this.get(path, { content: appendChunk });\n\n if (!item) {\n item = await this.newUntitled({ path, ext, type: 'file' });\n }\n\n if (!item) {\n return null;\n }\n\n // keep a reference to the original content\n const originalContent = item.content;\n\n const modified = new Date().toISOString();\n // override with the new values\n item = {\n ...item,\n ...options,\n last_modified: modified,\n };\n\n if (options.content && options.format === 'base64') {\n const lastChunk = chunk ? chunk === -1 : true;\n\n const contentBinaryString = this._handleUploadChunk(\n options.content,\n originalContent,\n appendChunk,\n );\n\n if (ext === '.ipynb') {\n const content = lastChunk\n ? JSON.parse(decoder.decode(this._binaryStringToBytes(contentBinaryString)))\n : contentBinaryString;\n item = {\n ...item,\n content,\n format: 'json',\n type: 'notebook',\n size: contentBinaryString.length,\n };\n } else if (FILE.hasFormat(ext, 'json')) {\n const content = lastChunk\n ? JSON.parse(decoder.decode(this._binaryStringToBytes(contentBinaryString)))\n : contentBinaryString;\n item = {\n ...item,\n content,\n format: 'json',\n type: 'file',\n size: contentBinaryString.length,\n };\n } else if (FILE.hasFormat(ext, 'text')) {\n const content = lastChunk\n ? decoder.decode(this._binaryStringToBytes(contentBinaryString))\n : contentBinaryString;\n item = {\n ...item,\n content,\n format: 'text',\n type: 'file',\n size: contentBinaryString.length,\n };\n } else {\n const content = lastChunk ? btoa(contentBinaryString) : contentBinaryString;\n item = {\n ...item,\n content,\n format: 'base64',\n type: 'file',\n size: contentBinaryString.length,\n };\n }\n }\n\n // fixup content sizes if necessary\n if (item.content) {\n switch (options.format) {\n case 'json': {\n item = { ...item, size: encoder.encode(JSON.stringify(item.content)).length };\n break;\n }\n case 'text': {\n item = { ...item, size: encoder.encode(item.content).length };\n break;\n }\n // base64 save was already handled above\n case 'base64': {\n break;\n }\n default: {\n item = { ...item, size: 0 };\n break;\n }\n }\n } else {\n item = { ...item, size: 0 };\n }\n\n await (await this.storage).setItem(path, item);\n return item;\n }\n\n /**\n * Delete a file from browser storage.\n *\n * Has no effect on server-backed files, which will re-appear with their\n * original timestamp.\n *\n * @param path - The path to the file.\n */\n async delete(path: string): Promise<void> {\n path = decodeURIComponent(path);\n const slashed = `${path}/`;\n const toDelete = (await (await this.storage).keys()).filter(\n (key) => key === path || key.startsWith(slashed),\n );\n await Promise.all(toDelete.map(this.forgetPath, this));\n }\n\n /**\n * Remove the localForage and checkpoints for a path.\n *\n * @param path - The path to the file\n */\n protected async forgetPath(path: string): Promise<void> {\n await Promise.all([\n (await this.storage).removeItem(path),\n (await this.checkpoints).removeItem(path),\n ]);\n }\n\n /**\n * Create a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n */\n async createCheckpoint(path: string): Promise<ServerContents.ICheckpointModel> {\n const checkpoints = await this.checkpoints;\n path = decodeURIComponent(path);\n const item = await this.get(path, { content: true });\n if (!item) {\n throw Error(`Could not find file with path ${path}`);\n }\n const copies = (((await checkpoints.getItem(path)) as IModel[]) ?? []).filter(\n Boolean,\n );\n copies.push(item);\n // keep only a certain amount of checkpoints per file\n if (copies.length > N_CHECKPOINTS) {\n copies.splice(0, copies.length - N_CHECKPOINTS);\n }\n await checkpoints.setItem(path, copies);\n const id = `${copies.length - 1}`;\n return { id, last_modified: (item as IModel).last_modified };\n }\n\n /**\n * List available checkpoints for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n */\n async listCheckpoints(path: string): Promise<ServerContents.ICheckpointModel[]> {\n const copies: IModel[] = (await (await this.checkpoints).getItem(path)) || [];\n return copies.filter(Boolean).map(this.normalizeCheckpoint, this);\n }\n\n protected normalizeCheckpoint(\n model: IModel,\n id: number,\n ): ServerContents.ICheckpointModel {\n return { id: id.toString(), last_modified: model.last_modified };\n }\n\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param path - The path of the file.\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n */\n async restoreCheckpoint(path: string, checkpointID: string): Promise<void> {\n path = decodeURIComponent(path);\n const copies = ((await (await this.checkpoints).getItem(path)) || []) as IModel[];\n const id = parseInt(checkpointID);\n const item = copies[id];\n await (await this.storage).setItem(path, item);\n }\n\n /**\n * Delete a checkpoint for a file.\n *\n * @param path - The path of the file.\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n */\n async deleteCheckpoint(path: string, checkpointID: string): Promise<void> {\n path = decodeURIComponent(path);\n const copies = ((await (await this.checkpoints).getItem(path)) || []) as IModel[];\n const id = parseInt(checkpointID);\n copies.splice(id, 1);\n await (await this.checkpoints).setItem(path, copies);\n }\n\n /**\n * Handle an upload chunk for a file.\n * each chunk is base64 encoded, so we need to decode it and append it to the\n * original content.\n * @param newContent the new content to process, base64 encoded\n * @param originalContent the original content, must be null or a binary string if chunked is true\n * @param appendChunk whether the chunk should be appended to the originalContent\n *\n *\n * @returns the decoded binary string, appended to the original content if requested\n * /\n */\n private _handleUploadChunk(\n newContent: string,\n originalContent: any,\n appendChunk: boolean,\n ): string {\n const newContentBinaryString = atob(newContent);\n const contentBinaryString = appendChunk\n ? originalContent + newContentBinaryString\n : newContentBinaryString;\n return contentBinaryString;\n }\n\n /**\n * Convert a binary string to an Uint8Array\n * @param binaryString the binary string\n * @returns the bytes of the binary string\n */\n private _binaryStringToBytes(binaryString: string): Uint8Array {\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n }\n\n /**\n * retrieve the contents for this path from the union of local storage and\n * `api/contents/{path}/all.json`.\n *\n * @param path - The contents path to retrieve\n *\n * @returns A promise which resolves with a Map of contents, keyed by local file name\n */\n private async _getFolder(path: string): Promise<IModel | null> {\n const content = new Map<string, IModel>();\n const storage = await this.storage;\n await storage.iterate<IModel, void>((file, key) => {\n if (key.includes('/')) {\n return;\n }\n content.set(file.path, file);\n });\n\n // layer in contents that don't have local overwrites\n for (const file of (await this._getServerDirectory(path)).values()) {\n if (!content.has(file.path)) {\n content.set(file.path, file);\n }\n }\n\n if (path && content.size === 0) {\n return null;\n }\n\n return {\n name: '',\n path,\n last_modified: new Date(0).toISOString(),\n created: new Date(0).toISOString(),\n format: 'json',\n mimetype: MIME.JSON,\n content: Array.from(content.values()),\n size: 0,\n writable: true,\n type: 'directory',\n };\n }\n\n /**\n * Attempt to recover the model from `{:path}/__all__.json` file, fall back to\n * deriving the model (including content) off the file in `/files/`. Otherwise\n * return `null`.\n */\n private async _getServerContents(\n path: string,\n options?: ServerContents.IFetchOptions,\n ): Promise<IModel | null> {\n const name = PathExt.basename(path);\n const parentContents = await this._getServerDirectory(URLExt.join(path, '..'));\n let model = parentContents.get(name);\n if (!model) {\n return null;\n }\n model = model || {\n name,\n path,\n last_modified: new Date(0).toISOString(),\n created: new Date(0).toISOString(),\n format: 'text',\n mimetype: MIME.PLAIN_TEXT,\n type: 'file',\n writable: true,\n size: 0,\n content: '',\n };\n\n if (options?.content) {\n if (model.type === 'directory') {\n const serverContents = await this._getServerDirectory(path);\n model = { ...model, content: Array.from(serverContents.values()) };\n } else {\n const fileUrl = URLExt.join(PageConfig.getBaseUrl(), 'files', path);\n const response = await fetch(fileUrl);\n if (!response.ok) {\n return null;\n }\n const mimetype = model.mimetype || response.headers.get('Content-Type');\n const ext = PathExt.extname(name);\n\n if (\n model.type === 'notebook' ||\n FILE.hasFormat(ext, 'json') ||\n mimetype?.indexOf('json') !== -1 ||\n path.match(/\\.(ipynb|[^/]*json[^/]*)$/)\n ) {\n const contentText = await response.text();\n model = {\n ...model,\n content: JSON.parse(contentText),\n format: 'json',\n mimetype: model.mimetype || MIME.JSON,\n size: encoder.encode(contentText).length,\n };\n } else if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {\n const contentText = await response.text();\n model = {\n ...model,\n content: contentText,\n format: 'text',\n mimetype: mimetype || MIME.PLAIN_TEXT,\n size: encoder.encode(contentText).length,\n };\n } else {\n const contentBuffer = await response.arrayBuffer();\n const contentBytes = new Uint8Array(contentBuffer);\n model = {\n ...model,\n content: btoa(contentBytes.reduce(this.reduceBytesToString, '')),\n format: 'base64',\n mimetype: mimetype || MIME.OCTET_STREAM,\n size: contentBytes.length,\n };\n }\n }\n }\n\n return model;\n }\n\n /**\n * A reducer for turning arbitrary binary into a string\n */\n protected reduceBytesToString = (data: string, byte: number): string => {\n return data + String.fromCharCode(byte);\n };\n\n /**\n * retrieve the contents for this path from `__index__.json` in the appropriate\n * folder.\n *\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with a Map of contents, keyed by local file name\n */\n private async _getServerDirectory(path: string): Promise<Map<string, IModel>> {\n const content = this._serverContents.get(path) || new Map();\n\n if (!this._serverContents.has(path)) {\n const apiURL = URLExt.join(\n PageConfig.getBaseUrl(),\n 'api/contents',\n path,\n 'all.json',\n );\n\n try {\n const response = await fetch(apiURL);\n const json = JSON.parse(await response.text());\n for (const file of json['content'] as IModel[]) {\n content.set(file.name, file);\n }\n } catch (err) {\n console.warn(\n `don't worry, about ${err}... nothing's broken. If there had been a\n file at ${apiURL}, you might see some more files.`,\n );\n }\n this._serverContents.set(path, content);\n }\n\n return content;\n }\n\n /**\n * Increment the counter for a given file type.\n * Used to avoid collisions when creating new untitled files.\n *\n * @param type The file type to increment the counter for.\n */\n private async _incrementCounter(type: ServerContents.ContentType): Promise<number> {\n const counters = await this.counters;\n const current = ((await counters.getItem(type)) as number) ?? -1;\n const counter = current + 1;\n await counters.setItem(type, counter);\n return counter;\n }\n\n private _serverContents = new Map<string, Map<string, IModel>>();\n private _storageName: string = DEFAULT_STORAGE_NAME;\n private _storageDrivers: string[] | null = null;\n private _ready: PromiseDelegate<void>;\n private _storage: LocalForage | undefined;\n private _counters: LocalForage | undefined;\n private _checkpoints: LocalForage | undefined;\n private _localforage: typeof localforage;\n}\n\n/**\n * A namespace for contents information.\n */\nexport namespace Contents {\n export interface IOptions {\n /**\n * The name of the storage instance on e.g. IndexedDB, localStorage\n */\n storageName?: string | null;\n storageDrivers?: string[] | null;\n localforage: typeof localforage;\n }\n}\n\n/**\n * A namespace for private data.\n */\nnamespace Private {\n /**\n * The content for an empty notebook.\n */\n export const EMPTY_NB: INotebookContent = {\n metadata: {\n orig_nbformat: 4,\n },\n nbformat_minor: 5,\n nbformat: 4,\n cells: [],\n };\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n// Types and implementation inspired from https://github.com/jvilk/BrowserFS\n// LICENSE: https://github.com/jvilk/BrowserFS/blob/8977a704ea469d05daf857e4818bef1f4f498326/LICENSE\n// And from https://github.com/gzuidhof/starboard-notebook\n\n// LICENSE: https://github.com/gzuidhof/starboard-notebook/blob/cd8d3fc30af4bd29cdd8f6b8c207df8138f5d5dd/LICENSE\n\n/**\n * Types for Emscripten primitives.\n *\n * Ideally, much more of these would be taken from `@types/emscripten`.\n */\n\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"../../../node_modules/@types/emscripten/index.d.ts\" />\ntype EmscriptenFS = typeof FS;\n\nexport const DIR_MODE = 16895; // 040777\nexport const FILE_MODE = 33206; // 100666\nexport const SEEK_CUR = 1;\nexport const SEEK_END = 2;\n\nexport interface IStats {\n dev: number;\n ino?: number;\n mode?: number;\n nlink: number;\n uid: number;\n gid: number;\n rdev: number;\n size: number;\n blksize: number;\n blocks: number;\n atime: Date | string;\n mtime: Date | string;\n ctime: Date | string;\n timestamp?: number;\n}\n\nexport interface IEmscriptenFSNode {\n id: number;\n name: string;\n mode: number;\n parent: IEmscriptenFSNode;\n mount: { opts: { root: string } };\n stream_ops: IEmscriptenStreamOps;\n node_ops: IEmscriptenNodeOps;\n timestamp: number;\n}\n\nexport interface IEmscriptenStream {\n node: IEmscriptenFSNode;\n nfd: any;\n flags: string;\n position: number;\n}\n\nexport function instanceOfStream(\n nodeOrStream: IEmscriptenFSNode | IEmscriptenStream,\n): nodeOrStream is IEmscriptenStream {\n return 'node' in nodeOrStream;\n}\n\nexport interface IEmscriptenNodeOps {\n getattr(node: IEmscriptenFSNode | IEmscriptenStream): IStats;\n setattr(node: IEmscriptenFSNode | IEmscriptenStream, attr: IStats): void;\n lookup(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n name: string,\n ): IEmscriptenFSNode;\n mknod(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n name: string,\n mode: number,\n dev: number,\n ): IEmscriptenFSNode;\n rename(\n oldNode: IEmscriptenFSNode | IEmscriptenStream,\n newDir: IEmscriptenFSNode | IEmscriptenStream,\n newName: string,\n ): void;\n unlink(parent: IEmscriptenFSNode | IEmscriptenStream, name: string): void;\n rmdir(parent: IEmscriptenFSNode | IEmscriptenStream, name: string): void;\n readdir(node: IEmscriptenFSNode | IEmscriptenStream): string[];\n symlink(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n newName: string,\n oldPath: string,\n ): void;\n readlink(node: IEmscriptenFSNode | IEmscriptenStream): string;\n}\n\nexport interface IEmscriptenStreamOps {\n open(stream: IEmscriptenStream): void;\n close(stream: IEmscriptenStream): void;\n read(\n stream: IEmscriptenStream,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): number;\n write(\n stream: IEmscriptenStream,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): number;\n llseek(stream: IEmscriptenStream, offset: number, whence: number): number;\n}\n\n/**\n * The emscripten filesystem module API.\n */\nexport type FS = EmscriptenFS & {\n ErrnoError: any;\n createNode: (\n parent: IEmscriptenFSNode | null,\n name: string,\n mode: number,\n dev: number,\n ) => IEmscriptenFSNode;\n};\n\n/**\n * The emscripten filesystem error codes.\n */\nexport type ERRNO_CODES = any;\n\n/**\n * The emscripten FS Path API.\n */\nexport type PATH = {\n basename: (path: string) => string;\n dirname: (path: string) => string;\n join: (...parts: string[]) => string;\n join2: (l: string, r: string) => string;\n normalize: (path: string) => string;\n splitPath: (filename: string) => string;\n};\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n// Types and implementation inspired from https://github.com/jvilk/BrowserFS\n// LICENSE: https://github.com/jvilk/BrowserFS/blob/8977a704ea469d05daf857e4818bef1f4f498326/LICENSE\n// And from https://github.com/gzuidhof/starboard-notebook\n\n// LICENSE: https://github.com/gzuidhof/starboard-notebook/blob/cd8d3fc30af4bd29cdd8f6b8c207df8138f5d5dd/LICENSE\nimport { Contents } from '@jupyterlab/services';\n\nimport {\n FS,\n ERRNO_CODES,\n PATH,\n DIR_MODE,\n SEEK_CUR,\n SEEK_END,\n IEmscriptenStream,\n instanceOfStream,\n IEmscriptenStreamOps,\n IEmscriptenNodeOps,\n IEmscriptenFSNode,\n IStats,\n} from './emscripten';\n\nexport const DRIVE_SEPARATOR = ':';\nexport const DRIVE_API_PATH = '/api/drive.v1';\n\nexport const BLOCK_SIZE = 4096;\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8');\n\nexport type TDriveMethod =\n | 'readdir'\n | 'rmdir'\n | 'rename'\n | 'getmode'\n | 'lookup'\n | 'mknod'\n | 'getattr'\n | 'get'\n | 'put';\n\n/**\n * Type of the data argument for the drive request, based on the request name\n */\nexport type TDriveData = {\n rename: {\n /**\n * The new path for the file\n */\n newPath: string;\n };\n mknod: {\n /**\n * The mode of the file to create\n */\n mode: number;\n };\n put: {\n /**\n * The file content to write\n */\n data: any;\n\n /**\n * The file content format\n */\n format: Contents.FileFormat;\n };\n};\n\n/**\n * Drive request\n */\nexport type TDriveRequest<T extends TDriveMethod> = {\n /**\n * The method of the request (rmdir, readdir etc)\n */\n method: T;\n\n /**\n * The expected receiver of the request\n */\n receiver?: 'broadcast.ts';\n\n /**\n * The path to the file/directory for which the request was sent\n */\n path: string;\n} & (T extends keyof TDriveData ? { data: TDriveData[T] } : object);\n\ntype TDriveResponses = {\n readdir: string[];\n rmdir: null;\n rename: null;\n getmode: number;\n lookup: DriveFS.ILookup;\n mknod: null;\n getattr: IStats;\n get:\n | {\n /**\n * The returned file content\n */\n content: any;\n\n /**\n * The content format\n */\n format: Contents.FileFormat;\n }\n | undefined;\n put: null;\n};\n\n/**\n * Drive response\n */\nexport type TDriveResponse<T extends TDriveMethod> = TDriveResponses[T];\n\n// Mapping flag -> do we need to overwrite the file upon closing it\nconst flagNeedsWrite: { [flag: number]: boolean } = {\n 0 /*O_RDONLY*/: false,\n 1 /*O_WRONLY*/: true,\n 2 /*O_RDWR*/: true,\n 64 /*O_CREAT*/: true,\n 65 /*O_WRONLY|O_CREAT*/: true,\n 66 /*O_RDWR|O_CREAT*/: true,\n 129 /*O_WRONLY|O_EXCL*/: true,\n 193 /*O_WRONLY|O_CREAT|O_EXCL*/: true,\n 514 /*O_RDWR|O_TRUNC*/: true,\n 577 /*O_WRONLY|O_CREAT|O_TRUNC*/: true,\n 578 /*O_CREAT|O_RDWR|O_TRUNC*/: true,\n 705 /*O_WRONLY|O_CREAT|O_EXCL|O_TRUNC*/: true,\n 706 /*O_RDWR|O_CREAT|O_EXCL|O_TRUNC*/: true,\n 1024 /*O_APPEND*/: true,\n 1025 /*O_WRONLY|O_APPEND*/: true,\n 1026 /*O_RDWR|O_APPEND*/: true,\n 1089 /*O_WRONLY|O_CREAT|O_APPEND*/: true,\n 1090 /*O_RDWR|O_CREAT|O_APPEND*/: true,\n 1153 /*O_WRONLY|O_EXCL|O_APPEND*/: true,\n 1154 /*O_RDWR|O_EXCL|O_APPEND*/: true,\n 1217 /*O_WRONLY|O_CREAT|O_EXCL|O_APPEND*/: true,\n 1218 /*O_RDWR|O_CREAT|O_EXCL|O_APPEND*/: true,\n 4096 /*O_RDONLY|O_DSYNC*/: true,\n 4098 /*O_RDWR|O_DSYNC*/: true,\n};\n\n/** Implementation-specifc extension of an open stream, adding the file. */\nexport interface IDriveStream extends IEmscriptenStream {\n file?: DriveFS.IFile;\n}\n\nexport class DriveFSEmscriptenStreamOps implements IEmscriptenStreamOps {\n private fs: DriveFS;\n\n constructor(fs: DriveFS) {\n this.fs = fs;\n }\n\n open(stream: IDriveStream): void {\n const path = this.fs.realPath(stream.node);\n if (this.fs.FS.isFile(stream.node.mode)) {\n stream.file = this.fs.API.get(path);\n }\n }\n\n close(stream: IDriveStream): void {\n if (!this.fs.FS.isFile(stream.node.mode) || !stream.file) {\n return;\n }\n\n const path = this.fs.realPath(stream.node);\n\n const flags = stream.flags;\n let parsedFlags = typeof flags === 'string' ? parseInt(flags, 10) : flags;\n parsedFlags &= 0x1fff;\n\n let needsWrite = true;\n if (parsedFlags in flagNeedsWrite) {\n needsWrite = flagNeedsWrite[parsedFlags];\n }\n\n if (needsWrite) {\n this.fs.API.put(path, stream.file);\n }\n\n stream.file = undefined;\n }\n\n read(\n stream: IDriveStream,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): number {\n if (\n length <= 0 ||\n stream.file === undefined ||\n position >= (stream.file.data.length || 0)\n ) {\n return 0;\n }\n\n const size = Math.min(stream.file.data.length - position, length);\n buffer.set(stream.file.data.subarray(position, position + size), offset);\n return size;\n }\n\n write(\n stream: IDriveStream,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): number {\n if (length <= 0 || stream.file === undefined) {\n return 0;\n }\n\n stream.node.timestamp = Date.now();\n\n if (position + length > (stream.file?.data.length || 0)) {\n const oldData = stream.file.data ? stream.file.data : new Uint8Array();\n stream.file.data = new Uint8Array(position + length);\n stream.file.data.set(oldData);\n }\n\n stream.file.data.set(buffer.subarray(offset, offset + length), position);\n\n return length;\n }\n\n llseek(stream: IDriveStream, offset: number, whence: number): number {\n let position = offset;\n if (whence === SEEK_CUR) {\n position += stream.position;\n } else if (whence === SEEK_END) {\n if (this.fs.FS.isFile(stream.node.mode)) {\n if (stream.file !== undefined) {\n position += stream.file.data.length;\n } else {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EPERM);\n }\n }\n }\n\n if (position < 0) {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EINVAL);\n }\n\n return position;\n }\n}\n\nexport class DriveFSEmscriptenNodeOps implements IEmscriptenNodeOps {\n private fs: DriveFS;\n\n constructor(fs: DriveFS) {\n this.fs = fs;\n }\n\n protected node(\n nodeOrStream: IEmscriptenFSNode | IEmscriptenStream,\n ): IEmscriptenFSNode {\n if (instanceOfStream(nodeOrStream)) {\n return nodeOrStream.node;\n }\n return nodeOrStream;\n }\n\n getattr(value: IEmscriptenFSNode | IEmscriptenStream): IStats {\n const node = this.node(value);\n return {\n ...this.fs.API.getattr(this.fs.realPath(node)),\n mode: node.mode,\n ino: node.id,\n };\n }\n\n setattr(value: IEmscriptenFSNode | IEmscriptenStream, attr: IStats): void {\n const node = this.node(value);\n for (const [key, value] of Object.entries(attr)) {\n switch (key) {\n case 'mode':\n node.mode = value;\n break;\n case 'timestamp':\n node.timestamp = value;\n break;\n case 'size': {\n const size = value;\n const path = this.fs.realPath(node);\n if (this.fs.FS.isFile(node.mode) && size >= 0) {\n const file = this.fs.API.get(path);\n const oldData = file.data ? file.data : new Uint8Array();\n if (size !== oldData.length) {\n if (size < oldData.length) {\n file.data = file.data.slice(0, size);\n } else {\n file.data = new Uint8Array(size);\n file.data.set(oldData);\n }\n this.fs.API.put(path, file);\n }\n } else {\n console.warn('setattr size of', size, 'on', node, 'not yet implemented');\n }\n break;\n }\n default:\n console.warn('setattr', key, 'of', value, 'on', node, 'not yet implemented');\n break;\n }\n }\n }\n\n lookup(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n name: string,\n ): IEmscriptenFSNode {\n const node = this.node(parent);\n const path = this.fs.PATH.join2(this.fs.realPath(node), name);\n const result = this.fs.API.lookup(path);\n if (!result.ok) {\n throw this.fs.FS.genericErrors[this.fs.ERRNO_CODES['ENOENT']];\n }\n return this.fs.createNode(node, name, result.mode!, 0);\n }\n\n mknod(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n name: string,\n mode: number,\n dev: number,\n ): IEmscriptenFSNode {\n const node = this.node(parent);\n const path = this.fs.PATH.join2(this.fs.realPath(node), name);\n this.fs.API.mknod(path, mode);\n return this.fs.createNode(node, name, mode, dev);\n }\n\n rename(\n value: IEmscriptenFSNode | IEmscriptenStream,\n newDir: IEmscriptenFSNode | IEmscriptenStream,\n newName: string,\n ): void {\n const oldNode = this.node(value);\n const newDirNode = this.node(newDir);\n this.fs.API.rename(\n oldNode.parent\n ? this.fs.PATH.join2(this.fs.realPath(oldNode.parent), oldNode.name)\n : oldNode.name,\n this.fs.PATH.join2(this.fs.realPath(newDirNode), newName),\n );\n\n // Updating the in-memory node\n oldNode.name = newName;\n oldNode.parent = newDirNode;\n }\n\n unlink(parent: IEmscriptenFSNode | IEmscriptenStream, name: string): void {\n this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(this.node(parent)), name));\n }\n\n rmdir(parent: IEmscriptenFSNode | IEmscriptenStream, name: string) {\n this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(this.node(parent)), name));\n }\n\n readdir(value: IEmscriptenFSNode | IEmscriptenStream): string[] {\n return this.fs.API.readdir(this.fs.realPath(this.node(value)));\n }\n\n symlink(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n newName: string,\n oldPath: string,\n ): void {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);\n }\n\n readlink(node: IEmscriptenFSNode | IEmscriptenStream): string {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);\n }\n}\n\n/**\n * ContentsAPI base class\n */\nexport abstract class ContentsAPI {\n constructor(driveName: string, mountpoint: string, FS: FS, ERRNO_CODES: ERRNO_CODES) {\n this._driveName = driveName;\n this._mountpoint = mountpoint;\n\n this.FS = FS;\n this.ERRNO_CODES = ERRNO_CODES;\n }\n\n lookup(path: string): DriveFS.ILookup {\n return this.request({ method: 'lookup', path: this.normalizePath(path) });\n }\n\n getmode(path: string): number {\n return this.request({ method: 'getmode', path: this.normalizePath(path) });\n }\n\n mknod(path: string, mode: number): null {\n return this.request({\n method: 'mknod',\n path: this.normalizePath(path),\n data: { mode },\n });\n }\n\n rename(oldPath: string, newPath: string): null {\n return this.request({\n method: 'rename',\n path: this.normalizePath(oldPath),\n data: { newPath: this.normalizePath(newPath) },\n });\n }\n\n readdir(path: string): string[] {\n const dirlist = this.request({\n method: 'readdir',\n path: this.normalizePath(path),\n });\n dirlist.push('.');\n dirlist.push('..');\n return dirlist;\n }\n\n rmdir(path: string): null {\n return this.request({ method: 'rmdir', path: this.normalizePath(path) });\n }\n\n get(path: string): DriveFS.IFile {\n const response = this.request({\n method: 'get',\n path: this.normalizePath(path),\n });\n\n if (!response) {\n throw new this.FS.ErrnoError(this.ERRNO_CODES['ENOENT']);\n }\n\n const serializedContent = response.content;\n const format: 'json' | 'text' | 'base64' | null = response.format;\n\n switch (format) {\n case 'json':\n case 'text':\n return {\n data: encoder.encode(serializedContent),\n format,\n };\n case 'base64': {\n const binString = atob(serializedContent);\n const len = binString.length;\n const data = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n data[i] = binString.charCodeAt(i);\n }\n return {\n data,\n format,\n };\n }\n default:\n throw new this.FS.ErrnoError(this.ERRNO_CODES['ENOENT']);\n }\n }\n\n put(path: string, value: DriveFS.IFile): null {\n switch (value.format) {\n case 'json':\n case 'text':\n return this.request({\n method: 'put',\n path: this.normalizePath(path),\n data: {\n format: value.format,\n data: decoder.decode(value.data),\n },\n });\n case 'base64': {\n let binary = '';\n for (let i = 0; i < value.data.byteLength; i++) {\n binary += String.fromCharCode(value.data[i]);\n }\n return this.request({\n method: 'put',\n path: this.normalizePath(path),\n data: {\n format: value.format,\n data: btoa(binary),\n },\n });\n }\n }\n }\n\n getattr(path: string): IStats {\n const stats = this.request({\n method: 'getattr',\n path: this.normalizePath(path),\n });\n // Turn datetimes into proper objects\n if (stats.atime) {\n stats.atime = new Date(stats.atime);\n }\n if (stats.mtime) {\n stats.mtime = new Date(stats.mtime);\n }\n if (stats.ctime) {\n stats.ctime = new Date(stats.ctime);\n }\n // ensure a non-undefined size (0 isn't great, though)\n stats.size = stats.size || 0;\n return stats;\n }\n\n /**\n * Normalize a Path by making it compliant for the content manager\n *\n * @param path: the path relatively to the Emscripten drive\n */\n normalizePath(path: string): string {\n // Remove mountpoint prefix\n if (path.startsWith(this._mountpoint)) {\n path = path.slice(this._mountpoint.length);\n }\n\n // Add JupyterLab drive name\n if (this._driveName) {\n path = `${this._driveName}${DRIVE_SEPARATOR}${path}`;\n }\n\n return path;\n }\n\n abstract request<T extends TDriveMethod>(data: TDriveRequest<T>): TDriveResponse<T>;\n\n private _driveName: string;\n private _mountpoint: string;\n\n protected FS: FS;\n protected ERRNO_CODES: ERRNO_CODES;\n}\n\n/**\n * An Emscripten-compatible synchronous Contents API using the service worker.\n */\nexport class ServiceWorkerContentsAPI extends ContentsAPI {\n constructor(\n baseUrl: string,\n driveName: string,\n mountpoint: string,\n FS: FS,\n ERRNO_CODES: ERRNO_CODES,\n ) {\n super(driveName, mountpoint, FS, ERRNO_CODES);\n\n this._baseUrl = baseUrl;\n }\n\n request<T extends TDriveMethod>(data: TDriveRequest<T>): TDriveResponse<T> {\n const xhr = new XMLHttpRequest();\n xhr.open('POST', encodeURI(this.endpoint), false);\n\n try {\n xhr.send(JSON.stringify(data));\n } catch (e) {\n console.error(e);\n }\n\n if (xhr.status >= 400) {\n throw new this.FS.ErrnoError(this.ERRNO_CODES['EINVAL']);\n }\n\n return JSON.parse(xhr.responseText);\n }\n\n /**\n * Get the api/drive endpoint\n */\n get endpoint(): string {\n return `${this._baseUrl}api/drive`;\n }\n\n private _baseUrl: string;\n}\n\nexport class DriveFS {\n FS: FS;\n API: ContentsAPI;\n PATH: PATH;\n ERRNO_CODES: ERRNO_CODES;\n driveName: string;\n\n constructor(options: DriveFS.IOptions) {\n this.FS = options.FS;\n this.PATH = options.PATH;\n this.ERRNO_CODES = options.ERRNO_CODES;\n this.API = this.createAPI(options);\n\n this.driveName = options.driveName;\n\n this.node_ops = new DriveFSEmscriptenNodeOps(this);\n this.stream_ops = new DriveFSEmscriptenStreamOps(this);\n }\n\n node_ops: IEmscriptenNodeOps;\n stream_ops: IEmscriptenStreamOps;\n\n /**\n * Create the ContentsAPI.\n *\n * This is supposed to be overwritten if needed.\n */\n createAPI(options: DriveFS.IOptions): ContentsAPI {\n return new ServiceWorkerContentsAPI(\n options.baseUrl,\n options.driveName,\n options.mountpoint,\n options.FS,\n options.ERRNO_CODES,\n );\n }\n\n mount(mount: any): IEmscriptenFSNode {\n return this.createNode(null, mount.mountpoint, DIR_MODE | 511, 0);\n }\n\n createNode(\n parent: IEmscriptenFSNode | null,\n name: string,\n mode: number,\n dev: number,\n ): IEmscriptenFSNode {\n const FS = this.FS;\n if (!FS.isDir(mode) && !FS.isFile(mode)) {\n throw new FS.ErrnoError(this.ERRNO_CODES['EINVAL']);\n }\n const node = FS.createNode(parent, name, mode, dev);\n node.node_ops = this.node_ops;\n node.stream_ops = this.stream_ops;\n return node;\n }\n\n getMode(path: string): number {\n return this.API.getmode(path);\n }\n\n realPath(node: IEmscriptenFSNode): string {\n const parts: string[] = [];\n let currentNode: IEmscriptenFSNode = node;\n\n parts.push(currentNode.name);\n while (currentNode.parent !== currentNode) {\n currentNode = currentNode.parent;\n parts.push(currentNode.name);\n }\n parts.reverse();\n\n return this.PATH.join.apply(null, parts);\n }\n}\n\n/**\n * A namespace for DriveFS configurations, etc.\n */\nexport namespace DriveFS {\n /**\n * A file representation;\n */\n export interface IFile {\n data: Uint8Array;\n format: 'json' | 'text' | 'base64';\n }\n\n /**\n * The response to a lookup request;\n */\n export interface ILookup {\n ok: boolean;\n mode?: number;\n }\n\n /**\n * Initialization options for a drive;\n */\n export interface IOptions {\n FS: FS;\n PATH: PATH;\n ERRNO_CODES: ERRNO_CODES;\n baseUrl: string;\n driveName: string;\n mountpoint: string;\n }\n}\n", "import { PathExt } from '@jupyterlab/coreutils';\nimport { Contents } from '@jupyterlab/services';\nimport { BLOCK_SIZE, TDriveMethod, TDriveRequest, TDriveResponse } from './drivefs';\nimport { DIR_MODE, FILE_MODE } from './emscripten';\n\nexport interface IDriveContentsProcessor {\n /**\n * Process a content request\n *\n * @param request the request\n */\n processDriveRequest<T extends TDriveMethod>(\n request: TDriveRequest<T>,\n ): Promise<TDriveResponse<T>>;\n\n /**\n * Process the request to read a directory content\n *\n * @param request the request\n */\n readdir(request: TDriveRequest<'readdir'>): Promise<TDriveResponse<'readdir'>>;\n\n /**\n * Process the request to remove a directory\n *\n * @param request the request\n */\n rmdir(request: TDriveRequest<'rmdir'>): Promise<TDriveResponse<'rmdir'>>;\n\n /**\n * Process the request to rename a file or directory\n *\n * @param request the request\n */\n rename(request: TDriveRequest<'rename'>): Promise<TDriveResponse<'rename'>>;\n\n /**\n * Process the request to get the node mode (file or directory)\n *\n * @param request the request\n */\n getmode(request: TDriveRequest<'getmode'>): Promise<TDriveResponse<'getmode'>>;\n\n /**\n * Process the request to check if a node exist\n *\n * @param request the request\n */\n lookup(request: TDriveRequest<'lookup'>): Promise<TDriveResponse<'lookup'>>;\n\n /**\n * Process the request to create a directory/file\n *\n * @param request the request\n */\n mknod(request: TDriveRequest<'mknod'>): Promise<TDriveResponse<'mknod'>>;\n\n /**\n * Process the request to get a node stats\n *\n * @param request the request\n */\n getattr(request: TDriveRequest<'getattr'>): Promise<TDriveResponse<'getattr'>>;\n\n /**\n * Process the request to get the content of a file\n *\n * @param request the request\n */\n get(request: TDriveRequest<'get'>): Promise<TDriveResponse<'get'>>;\n\n /**\n * Process the request to write the content of a file\n *\n * @param request the request\n */\n put(request: TDriveRequest<'put'>): Promise<TDriveResponse<'put'>>;\n}\n\n/**\n * Class for processing a drive request from the DriveFS.\n */\nexport class DriveContentsProcessor implements IDriveContentsProcessor {\n private contentsManager: Contents.IManager;\n\n constructor(options: DriveContentsProcessor.IOptions) {\n this.contentsManager = options.contentsManager;\n }\n\n async processDriveRequest<T extends TDriveMethod>(\n request: TDriveRequest<T>,\n ): Promise<TDriveResponse<T>> {\n switch (request.method) {\n case 'readdir':\n return this.readdir(request as TDriveRequest<'readdir'>) as Promise<\n TDriveResponse<T>\n >;\n case 'rmdir':\n return this.rmdir(request as TDriveRequest<'rmdir'>) as Promise<\n TDriveResponse<T>\n >;\n case 'rename':\n return this.rename(request as TDriveRequest<'rename'>) as Promise<\n TDriveResponse<T>\n >;\n case 'getmode':\n return this.getmode(request as TDriveRequest<'getmode'>) as Promise<\n TDriveResponse<T>\n >;\n case 'lookup':\n return this.lookup(request as TDriveRequest<'lookup'>) as Promise<\n TDriveResponse<T>\n >;\n case 'mknod':\n return this.mknod(request as TDriveRequest<'mknod'>) as Promise<\n TDriveResponse<T>\n >;\n case 'getattr':\n return this.getattr(request as TDriveRequest<'getattr'>) as Promise<\n TDriveResponse<T>\n >;\n case 'get':\n return this.get(request as TDriveRequest<'get'>) as Promise<TDriveResponse<T>>;\n case 'put':\n return this.put(request as TDriveRequest<'put'>) as Promise<TDriveResponse<T>>;\n }\n\n throw `Drive request ${request.method} does not exist.`;\n }\n\n async readdir(request: TDriveRequest<'readdir'>): Promise<TDriveResponse<'readdir'>> {\n const model = await this.contentsManager.get(request.path, { content: true });\n let response: string[] = [];\n if (model.type === 'directory' && model.content) {\n response = model.content.map((subcontent: Contents.IModel) => subcontent.name);\n }\n return response;\n }\n\n async rmdir(request: TDriveRequest<'rmdir'>): Promise<TDriveResponse<'rmdir'>> {\n await this.contentsManager.delete(request.path);\n return null;\n }\n\n async rename(request: TDriveRequest<'rename'>): Promise<TDriveResponse<'rename'>> {\n await this.contentsManager.rename(request.path, request.data.newPath);\n return null;\n }\n\n async getmode(request: TDriveRequest<'getmode'>): Promise<TDriveResponse<'getmode'>> {\n const model = await this.contentsManager.get(request.path);\n let response: number;\n if (model.type === 'directory') {\n response = DIR_MODE;\n } else {\n response = FILE_MODE;\n }\n return response;\n }\n\n async lookup(request: TDriveRequest<'lookup'>): Promise<TDriveResponse<'lookup'>> {\n let response: TDriveResponse<'lookup'>;\n\n try {\n const model = await this.contentsManager.get(request.path);\n response = {\n ok: true,\n mode: model.type === 'directory' ? DIR_MODE : FILE_MODE,\n };\n } catch (e) {\n response = { ok: false };\n }\n\n return response;\n }\n\n async mknod(request: TDriveRequest<'mknod'>): Promise<TDriveResponse<'mknod'>> {\n const model = await this.contentsManager.newUntitled({\n path: PathExt.dirname(request.path),\n type: request.data.mode === DIR_MODE ? 'directory' : 'file',\n ext: PathExt.extname(request.path),\n });\n await this.contentsManager.rename(model.path, request.path);\n return null;\n }\n\n async getattr(request: TDriveRequest<'getattr'>): Promise<TDriveResponse<'getattr'>> {\n const model = await this.contentsManager.get(request.path);\n // create a default date for drives that send incomplete information\n // for nested foldes and files\n const defaultDate = new Date(0).toISOString();\n\n return {\n dev: 1,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n size: model.size || 0,\n blksize: BLOCK_SIZE,\n blocks: Math.ceil(model.size || 0 / BLOCK_SIZE),\n atime: model.last_modified || defaultDate, // TODO Get the proper atime?\n mtime: model.last_modified || defaultDate,\n ctime: model.created || defaultDate,\n timestamp: 0,\n };\n }\n\n async get(request: TDriveRequest<'get'>): Promise<TDriveResponse<'get'>> {\n const model = await this.contentsManager.get(request.path, { content: true });\n\n let response;\n\n if (model.type !== 'directory') {\n response = {\n content:\n model.format === 'json' ? JSON.stringify(model.content) : model.content,\n format: model.format,\n };\n }\n\n return response;\n }\n\n async put(request: TDriveRequest<'put'>): Promise<TDriveResponse<'put'>> {\n await this.contentsManager.save(request.path, {\n content:\n request.data.format === 'json'\n ? JSON.parse(request.data.data)\n : request.data.data,\n type: 'file',\n format: request.data.format as Contents.FileFormat,\n });\n return null;\n }\n}\n\n/**\n * A namespace for DriveContentsProcessor configurations, etc.\n */\nexport namespace DriveContentsProcessor {\n /**\n * Initialization options for a drive;\n */\n export interface IOptions {\n contentsManager: Contents.IManager;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { Contents as ServerContents } from '@jupyterlab/services';\n\nimport { TDriveRequest, DRIVE_API_PATH, TDriveMethod } from './drivefs';\n\nimport { IBroadcastChannelWrapper } from './tokens';\nimport { IDriveContentsProcessor, DriveContentsProcessor } from './drivecontents';\n\n/** A broadcaster for the ServiceWorker */\nexport class BroadcastChannelWrapper implements IBroadcastChannelWrapper {\n public isDisposed = false;\n\n constructor(options: BroadcastChannelWrapper.IOptions) {\n this._contents = options.contents;\n this._driveContentsProcessor = new DriveContentsProcessor({\n contentsManager: this._contents,\n });\n }\n\n get enabled() {\n return this._enabled;\n }\n\n enable() {\n if (this._channel) {\n console.warn('BroadcastChannel already created and enabled');\n return;\n }\n this._channel = new BroadcastChannel(DRIVE_API_PATH);\n this._channel.addEventListener('message', this._onMessage);\n this._enabled = true;\n }\n\n disable() {\n if (this._channel) {\n this._channel.removeEventListener('message', this._onMessage);\n this._channel = null;\n }\n this._enabled = false;\n }\n\n /** Clean up the broadcaster. */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this.disable();\n this.isDisposed = true;\n }\n\n /** Handle a message received on the BroadcastChannel */\n protected _onMessage = async <T extends TDriveMethod>(\n event: MessageEvent<TDriveRequest<T>>,\n ): Promise<void> => {\n if (!this._channel) {\n return;\n }\n\n const request = event.data;\n const receiver = request?.receiver;\n if (receiver !== 'broadcast.ts') {\n // Message is not meant for us\n return;\n }\n\n const response = await this._driveContentsProcessor.processDriveRequest(request);\n\n this._channel.postMessage(response);\n };\n\n protected _channel: BroadcastChannel | null = null;\n protected _contents: ServerContents.IManager;\n protected _driveContentsProcessor: IDriveContentsProcessor;\n protected _enabled = false;\n}\n\n/** A namespace for */\nexport namespace BroadcastChannelWrapper {\n export interface IOptions {\n contents: ServerContents.IManager;\n }\n export type TBroadcastResponse = any;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nexport * from './contents';\nexport * from './drivefs';\nexport * from './tokens';\nexport * from './broadcast';\nexport * from './emscripten';\nexport * from './drivecontents';\n", "export const ARRAY = 'array';\nexport const BIGINT = 'bigint';\nexport const BOOLEAN = 'boolean';\nexport const FUNCTION = 'function';\nexport const NULL = 'null';\nexport const NUMBER = 'number';\nexport const OBJECT = 'object';\nexport const STRING = 'string';\nexport const SYMBOL = 'symbol';\nexport const UNDEFINED = 'undefined';\n", "// \u26A0\uFE0F AUTOMATICALLY GENERATED - DO NOT CHANGE\nexport const CHANNEL = '64e10b34-2bf7-4616-9668-f99de5aa046e';\n\nexport const MAIN = 'M' + CHANNEL;\nexport const THREAD = 'T' + CHANNEL;\n", "export const APPLY = 'apply';\nexport const CONSTRUCT = 'construct';\nexport const DEFINE_PROPERTY = 'defineProperty';\nexport const DELETE_PROPERTY = 'deleteProperty';\nexport const GET = 'get';\nexport const GET_OWN_PROPERTY_DESCRIPTOR = 'getOwnPropertyDescriptor';\nexport const GET_PROTOTYPE_OF = 'getPrototypeOf';\nexport const HAS = 'has';\nexport const IS_EXTENSIBLE = 'isExtensible';\nexport const OWN_KEYS = 'ownKeys';\nexport const PREVENT_EXTENSION = 'preventExtensions';\nexport const SET = 'set';\nexport const SET_PROTOTYPE_OF = 'setPrototypeOf';\n", "// The goal of this file is to normalize SAB\n// at least in main -> worker() use cases.\n// This still cannot possibly solve the sync\n// worker -> main() use case if SharedArrayBuffer\n// is not available or usable.\n\nimport {CHANNEL} from './channel.js';\n\nconst {isArray} = Array;\n\nlet {SharedArrayBuffer, window} = globalThis;\nlet {notify, wait, waitAsync} = Atomics;\nlet postPatched = null;\n\n// This is needed for some version of Firefox\nif (!waitAsync) {\n waitAsync = buffer => ({\n value: new Promise(onmessage => {\n // encodeURIComponent('onmessage=({data:b})=>(Atomics.wait(b,0),postMessage(0))')\n let w = new Worker('data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))');\n w.onmessage = onmessage;\n w.postMessage(buffer);\n })\n });\n}\n\n// Monkey-patch SharedArrayBuffer if needed\ntry {\n new SharedArrayBuffer(4);\n}\ncatch (_) {\n SharedArrayBuffer = ArrayBuffer;\n\n const ids = new WeakMap;\n // patch only main -> worker():async use case\n if (window) {\n const resolvers = new Map;\n const {prototype: {postMessage}} = Worker;\n\n const listener = event => {\n const details = event.data?.[CHANNEL];\n if (!isArray(details)) {\n event.stopImmediatePropagation();\n const { id, sb } = details;\n resolvers.get(id)(sb);\n }\n };\n\n postPatched = function (data, ...rest) {\n const details = data?.[CHANNEL];\n if (isArray(details)) {\n const [id, sb] = details;\n ids.set(sb, id);\n this.addEventListener('message', listener);\n }\n return postMessage.call(this, data, ...rest);\n };\n\n waitAsync = sb => ({\n value: new Promise(resolve => {\n resolvers.set(ids.get(sb), resolve);\n }).then(buff => {\n resolvers.delete(ids.get(sb));\n ids.delete(sb);\n for (let i = 0; i < buff.length; i++) sb[i] = buff[i];\n return 'ok';\n })\n });\n }\n else {\n const as = (id, sb) => ({[CHANNEL]: { id, sb }});\n\n notify = sb => {\n postMessage(as(ids.get(sb), sb));\n };\n\n addEventListener('message', event => {\n const details = event.data?.[CHANNEL];\n if (isArray(details)) {\n const [id, sb] = details;\n ids.set(sb, id);\n }\n });\n }\n}\n\nexport {SharedArrayBuffer, isArray, notify, postPatched, wait, waitAsync};\n", "/*! (c) Andrea Giammarchi - ISC */\n\nimport {FUNCTION} from 'proxy-target/types';\n\nimport {CHANNEL} from './channel.js';\nimport {GET, HAS, SET} from './shared/traps.js';\n\nimport {SharedArrayBuffer, isArray, notify, postPatched, wait, waitAsync} from './bridge.js';\n\n// just minifier friendly for Blob Workers' cases\nconst {Int32Array, Map, Uint16Array} = globalThis;\n\n// common constants / utilities for repeated operations\nconst {BYTES_PER_ELEMENT: I32_BYTES} = Int32Array;\nconst {BYTES_PER_ELEMENT: UI16_BYTES} = Uint16Array;\n\nconst waitInterrupt = (sb, delay, handler) => {\n while (wait(sb, 0, 0, delay) === 'timed-out')\n handler();\n};\n\n// retain buffers to transfer\nconst buffers = new WeakSet;\n\n// retain either main threads or workers global context\nconst context = new WeakMap;\n\nconst syncResult = {value: {then: fn => fn()}};\n\n// used to generate a unique `id` per each worker `postMessage` \"transaction\"\nlet uid = 0;\n\n/**\n * @typedef {Object} Interrupt used to sanity-check interrupts while waiting synchronously.\n * @prop {function} [handler] a callback invoked every `delay` milliseconds.\n * @prop {number} [delay=42] define `handler` invokes in terms of milliseconds.\n */\n\n/**\n * Create once a `Proxy` able to orchestrate synchronous `postMessage` out of the box.\n * @param {globalThis | Worker} self the context in which code should run\n * @param {{parse: (serialized: string) => any, stringify: (serializable: any) => string, transform?: (value:any) => any, interrupt?: () => void | Interrupt}} [JSON] an optional `JSON` like interface to `parse` or `stringify` content with extra `transform` ability.\n * @returns {ProxyHandler<globalThis> | ProxyHandler<Worker>}\n */\nconst coincident = (self, {parse = JSON.parse, stringify = JSON.stringify, transform, interrupt} = JSON) => {\n // create a Proxy once for the given context (globalThis or Worker instance)\n if (!context.has(self)) {\n // ensure no SAB gets a chance to pass through this call\n const sendMessage = postPatched || self.postMessage;\n // ensure the CHANNEL and data are posted correctly\n const post = (transfer, ...args) => sendMessage.call(self, {[CHANNEL]: args}, {transfer});\n\n const handler = typeof interrupt === FUNCTION ? interrupt : interrupt?.handler;\n const delay = interrupt?.delay || 42;\n const decoder = new TextDecoder('utf-16');\n\n // automatically uses sync wait (worker -> main)\n // or fallback to async wait (main -> worker)\n const waitFor = (isAsync, sb) => isAsync ?\n waitAsync(sb, 0) :\n ((handler ? waitInterrupt(sb, delay, handler) : wait(sb, 0)), syncResult);\n\n // prevent Harakiri https://github.com/WebReflection/coincident/issues/18\n let seppuku = false;\n\n context.set(self, new Proxy(new Map, {\n // there is very little point in checking prop in proxy for this very specific case\n // and I don't want to orchestrate a whole roundtrip neither, as stuff would fail\n // regardless if from Worker we access non existent Main callback, and vice-versa.\n // This is here mostly to guarantee that if such check is performed, at least the\n // get trap goes through and then it's up to developers guarantee they are accessing\n // stuff that actually exists elsewhere.\n [HAS]: (_, action) => typeof action === 'string' && !action.startsWith('_'),\n\n // worker related: get any utility that should be available on the main thread\n [GET]: (_, action) => action === 'then' ? null : ((...args) => {\n // transaction id\n const id = uid++;\n\n // first contact: just ask for how big the buffer should be\n // the value would be stored at index [1] while [0] is just control\n let sb = new Int32Array(new SharedArrayBuffer(I32_BYTES * 2));\n\n // if a transfer list has been passed, drop it from args\n let transfer = [];\n if (buffers.has(args.at(-1) || transfer))\n buffers.delete(transfer = args.pop());\n\n // ask for invoke with arguments and wait for it\n post(transfer, id, sb, action, transform ? args.map(transform) : args);\n\n // helps deciding how to wait for results\n const isAsync = self !== globalThis;\n\n // warn users about possible deadlock still allowing them\n // to explicitly `proxy.invoke().then(...)` without blocking\n let deadlock = 0;\n if (seppuku && isAsync)\n deadlock = setTimeout(console.warn, 1000, `\uD83D\uDC80\uD83D\uDD12 - Possible deadlock if proxy.${action}(...args) is awaited`);\n\n return waitFor(isAsync, sb).value.then(() => {\n clearTimeout(deadlock);\n\n // commit transaction using the returned / needed buffer length\n const length = sb[1];\n\n // filter undefined results\n if (!length) return;\n\n // calculate the needed ui16 bytes length to store the result string\n const bytes = UI16_BYTES * length;\n\n // round up to the next amount of bytes divided by 4 to allow i32 operations\n sb = new Int32Array(new SharedArrayBuffer(bytes + (bytes % I32_BYTES)));\n\n // ask for results and wait for it\n post([], id, sb);\n return waitFor(isAsync, sb).value.then(() => parse(\n decoder.decode(new Uint16Array(sb.buffer).slice(0, length)))\n );\n });\n }),\n\n // main thread related: react to any utility a worker is asking for\n [SET](actions, action, callback) {\n const type = typeof callback;\n if (type !== FUNCTION)\n throw new Error(`Unable to assign ${action} as ${type}`);\n // lazy event listener and logic handling, triggered once by setters actions\n if (!actions.size) {\n // maps results by `id` as they are asked for\n const results = new Map;\n // add the event listener once (first defined setter, all others work the same)\n self.addEventListener('message', async (event) => {\n // grub the very same library CHANNEL; ignore otherwise\n const details = event.data?.[CHANNEL];\n if (isArray(details)) {\n // if early enough, avoid leaking data to other listeners\n event.stopImmediatePropagation();\n const [id, sb, ...rest] = details;\n let error;\n // action available: it must be defined/known on the main thread\n if (rest.length) {\n const [action, args] = rest;\n if (actions.has(action)) {\n seppuku = true;\n try {\n // await for result either sync or async and serialize it\n const result = await actions.get(action)(...args);\n if (result !== void 0) {\n const serialized = stringify(transform ? transform(result) : result);\n // store the result for \"the very next\" event listener call\n results.set(id, serialized);\n // communicate the required SharedArrayBuffer length out of the\n // resulting serialized string\n sb[1] = serialized.length;\n }\n }\n catch (_) {\n error = _;\n }\n finally {\n seppuku = false;\n }\n }\n // unknown action should be notified as missing on the main thread\n else {\n error = new Error(`Unsupported action: ${action}`);\n }\n // unlock the wait lock later on\n sb[0] = 1;\n }\n // no action means: get results out of the well known `id`\n // wait lock automatically unlocked here as no `0` value would\n // possibly ever land at index `0`\n else {\n const result = results.get(id);\n results.delete(id);\n // populate the SharedArrayBuffer with utf-16 chars code\n for (let ui16a = new Uint16Array(sb.buffer), i = 0; i < result.length; i++)\n ui16a[i] = result.charCodeAt(i);\n }\n // release te worker waiting either the length or the result\n notify(sb, 0);\n if (error) throw error;\n }\n });\n }\n // store this action callback allowing the setter in the process\n return !!actions.set(action, callback);\n }\n }));\n }\n return context.get(self);\n};\n\ncoincident.transfer = (...args) => (buffers.add(args), args);\n\nexport default coincident;\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n/**\n * A WebWorker entrypoint that uses coincident to handle postMessage details\n */\nimport coincident from 'coincident';\n\nimport {\n ContentsAPI,\n DriveFS,\n TDriveMethod,\n TDriveRequest,\n TDriveResponse,\n} from '@jupyterlite/contents';\n\nimport { IPyodideWorkerKernel } from './tokens';\n\nimport { PyodideRemoteKernel } from './worker';\n\nconst workerAPI = coincident(self) as IPyodideWorkerKernel;\n\n/**\n * An Emscripten-compatible synchronous Contents API using shared array buffers.\n */\nexport class SharedBufferContentsAPI extends ContentsAPI {\n request<T extends TDriveMethod>(data: TDriveRequest<T>): TDriveResponse<T> {\n return workerAPI.processDriveRequest(data);\n }\n}\n\n/**\n * A custom drive implementation which uses shared array buffers (via coincident) if available\n */\nclass PyodideDriveFS extends DriveFS {\n createAPI(options: DriveFS.IOptions): ContentsAPI {\n return new SharedBufferContentsAPI(\n options.driveName,\n options.mountpoint,\n options.FS,\n options.ERRNO_CODES,\n );\n }\n}\n\nexport class PyodideCoincidentKernel extends PyodideRemoteKernel {\n /**\n * Setup custom Emscripten FileSystem\n */\n protected async initFilesystem(\n options: IPyodideWorkerKernel.IOptions,\n ): Promise<void> {\n if (options.mountDrive) {\n const mountpoint = '/drive';\n const { FS, PATH, ERRNO_CODES } = this._pyodide;\n const { baseUrl } = options;\n\n const driveFS = new PyodideDriveFS({\n FS: FS as any,\n PATH,\n ERRNO_CODES,\n baseUrl,\n driveName: this._driveName,\n mountpoint,\n });\n FS.mkdirTree(mountpoint);\n FS.mount(driveFS, {}, mountpoint);\n FS.chdir(mountpoint);\n this._driveFS = driveFS;\n }\n }\n}\n\nconst worker = new PyodideCoincidentKernel();\n\nconst sendWorkerMessage = workerAPI.processWorkerMessage.bind(workerAPI);\nworker.registerCallback(sendWorkerMessage);\n\nworkerAPI.initialize = worker.initialize.bind(worker);\nworkerAPI.execute = worker.execute.bind(worker);\nworkerAPI.complete = worker.complete.bind(worker);\nworkerAPI.inspect = worker.inspect.bind(worker);\nworkerAPI.isComplete = worker.isComplete.bind(worker);\nworkerAPI.commInfo = worker.commInfo.bind(worker);\nworkerAPI.commOpen = worker.commOpen.bind(worker);\nworkerAPI.commMsg = worker.commMsg.bind(worker);\nworkerAPI.commClose = worker.commClose.bind(worker);\nworkerAPI.inputReply = worker.inputReply.bind(worker);\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport type Pyodide from 'pyodide';\n\nimport type { DriveFS } from '@jupyterlite/contents';\n\nimport { KernelMessage } from '@jupyterlab/services';\n\nimport type { IPyodideWorkerKernel } from './tokens';\n\nexport class PyodideRemoteKernel {\n constructor() {\n this._initialized = new Promise((resolve, reject) => {\n this._initializer = { resolve, reject };\n });\n }\n\n /**\n * Accept the URLs from the host\n **/\n async initialize(options: IPyodideWorkerKernel.IOptions): Promise<void> {\n this._options = options;\n\n if (options.location.includes(':')) {\n const parts = options.location.split(':');\n this._driveName = parts[0];\n this._localPath = parts[1];\n } else {\n this._driveName = '';\n this._localPath = options.location;\n }\n\n await this.initRuntime(options);\n await this.initFilesystem(options);\n await this.initPackageManager(options);\n await this.initKernel(options);\n await this.initGlobals(options);\n this._initializer?.resolve();\n }\n\n protected async initRuntime(options: IPyodideWorkerKernel.IOptions): Promise<void> {\n const { pyodideUrl, indexUrl } = options;\n let loadPyodide: typeof Pyodide.loadPyodide;\n if (pyodideUrl.endsWith('.mjs')) {\n // note: this does not work at all in firefox\n const pyodideModule: typeof Pyodide = await import(\n /* webpackIgnore: true */ pyodideUrl\n );\n loadPyodide = pyodideModule.loadPyodide;\n } else {\n importScripts(pyodideUrl);\n loadPyodide = (self as any).loadPyodide;\n }\n this._pyodide = await loadPyodide({\n indexURL: indexUrl,\n ...options.loadPyodideOptions,\n });\n }\n\n protected async initPackageManager(\n options: IPyodideWorkerKernel.IOptions,\n ): Promise<void> {\n if (!this._options) {\n throw new Error('Uninitialized');\n }\n\n const { pipliteWheelUrl, disablePyPIFallback, pipliteUrls, loadPyodideOptions } =\n this._options;\n\n const preloaded = (loadPyodideOptions || {}).packages || [];\n\n if (!preloaded.includes('micropip')) {\n await this._pyodide.loadPackage(['micropip']);\n }\n\n if (!preloaded.includes('piplite')) {\n await this._pyodide.runPythonAsync(`\n import micropip\n await micropip.install('${pipliteWheelUrl}', keep_going=True)\n `);\n }\n\n // get piplite early enough to impact pyodide-kernel dependencies\n await this._pyodide.runPythonAsync(`\n import piplite.piplite\n piplite.piplite._PIPLITE_DISABLE_PYPI = ${disablePyPIFallback ? 'True' : 'False'}\n piplite.piplite._PIPLITE_URLS = ${JSON.stringify(pipliteUrls)}\n `);\n }\n\n protected async initKernel(options: IPyodideWorkerKernel.IOptions): Promise<void> {\n const preloaded = (options.loadPyodideOptions || {}).packages || [];\n\n const toLoad = [\n 'ssl',\n 'sqlite3',\n 'ipykernel',\n 'comm',\n 'pyodide_kernel',\n 'jedi',\n 'ipython',\n ];\n\n const scriptLines: string[] = [];\n\n // use piplite for packages that weren't pre-loaded\n for (const pkgName of toLoad) {\n if (!preloaded.includes(pkgName)) {\n scriptLines.push(`await piplite.install('${pkgName}', keep_going=True)`);\n }\n }\n\n // import the kernel\n scriptLines.push('import pyodide_kernel');\n\n // cd to the kernel location\n if (options.mountDrive && this._localPath) {\n scriptLines.push('import os', `os.chdir(\"${this._localPath}\")`);\n }\n\n // from this point forward, only use piplite (but not %pip)\n await this._pyodide.runPythonAsync(scriptLines.join('\\n'));\n }\n\n protected async initGlobals(options: IPyodideWorkerKernel.IOptions): Promise<void> {\n const { globals } = this._pyodide;\n this._kernel = globals.get('pyodide_kernel').kernel_instance.copy();\n this._stdout_stream = globals.get('pyodide_kernel').stdout_stream.copy();\n this._stderr_stream = globals.get('pyodide_kernel').stderr_stream.copy();\n this._interpreter = this._kernel.interpreter.copy();\n this._interpreter.send_comm = this.sendComm.bind(this);\n }\n\n /**\n * Setup custom Emscripten FileSystem\n */\n protected async initFilesystem(\n options: IPyodideWorkerKernel.IOptions,\n ): Promise<void> {\n if (options.mountDrive) {\n const mountpoint = '/drive';\n const { FS, PATH, ERRNO_CODES } = this._pyodide;\n const { baseUrl } = options;\n const { DriveFS } = await import('@jupyterlite/contents');\n\n const driveFS = new DriveFS({\n FS: FS as any,\n PATH,\n ERRNO_CODES,\n baseUrl,\n driveName: this._driveName,\n mountpoint,\n });\n FS.mkdirTree(mountpoint);\n FS.mount(driveFS, {}, mountpoint);\n FS.chdir(mountpoint);\n this._driveFS = driveFS;\n }\n }\n\n /**\n * Recursively convert a Map to a JavaScript object\n * @param obj A Map, Array, or other object to convert\n */\n mapToObject(obj: any) {\n const out: any = obj instanceof Array ? [] : {};\n obj.forEach((value: any, key: string) => {\n out[key] =\n value instanceof Map || value instanceof Array\n ? this.mapToObject(value)\n : value;\n });\n return out;\n }\n\n /**\n * Format the response from the Pyodide evaluation.\n *\n * @param res The result object from the Pyodide evaluation\n */\n formatResult(res: any): any {\n if (!(res instanceof this._pyodide.ffi.PyProxy)) {\n return res;\n }\n // TODO: this is a bit brittle\n const m = res.toJs();\n const results = this.mapToObject(m);\n return results;\n }\n\n /**\n * Register the callback function to send messages from the worker back to the main thread.\n * @param callback the callback to register\n */\n registerCallback(callback: (msg: any) => void): void {\n this._sendWorkerMessage = callback;\n }\n\n /**\n * Makes sure pyodide is ready before continuing, and cache the parent message.\n */\n async setup(parent: any): Promise<void> {\n await this._initialized;\n this._kernel._parent_header = this._pyodide.toPy(parent);\n }\n\n /**\n * Execute code with the interpreter.\n *\n * @param content The incoming message with the code to execute.\n */\n async execute(content: any, parent: any) {\n await this.setup(parent);\n\n const publishExecutionResult = (\n prompt_count: any,\n data: any,\n metadata: any,\n ): void => {\n const bundle = {\n execution_count: prompt_count,\n data: this.formatResult(data),\n metadata: this.formatResult(metadata),\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'execute_result',\n });\n };\n\n const publishExecutionError = (ename: any, evalue: any, traceback: any): void => {\n const bundle = {\n ename: ename,\n evalue: evalue,\n traceback: traceback,\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'execute_error',\n });\n };\n\n const clearOutputCallback = (wait: boolean): void => {\n const bundle = {\n wait: this.formatResult(wait),\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'clear_output',\n });\n };\n\n const displayDataCallback = (data: any, metadata: any, transient: any): void => {\n const bundle = {\n data: this.formatResult(data),\n metadata: this.formatResult(metadata),\n transient: this.formatResult(transient),\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'display_data',\n });\n };\n\n const updateDisplayDataCallback = (\n data: any,\n metadata: any,\n transient: any,\n ): void => {\n const bundle = {\n data: this.formatResult(data),\n metadata: this.formatResult(metadata),\n transient: this.formatResult(transient),\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'update_display_data',\n });\n };\n\n const publishStreamCallback = (name: any, text: any): void => {\n const bundle = {\n name: this.formatResult(name),\n text: this.formatResult(text),\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'stream',\n });\n };\n\n this._stdout_stream.publish_stream_callback = publishStreamCallback;\n this._stderr_stream.publish_stream_callback = publishStreamCallback;\n this._interpreter.display_pub.clear_output_callback = clearOutputCallback;\n this._interpreter.display_pub.display_data_callback = displayDataCallback;\n this._interpreter.display_pub.update_display_data_callback =\n updateDisplayDataCallback;\n this._interpreter.displayhook.publish_execution_result = publishExecutionResult;\n this._interpreter.input = this.input.bind(this);\n this._interpreter.getpass = this.getpass.bind(this);\n\n const res = await this._kernel.run(content.code);\n const results = this.formatResult(res);\n\n if (results['status'] === 'error') {\n publishExecutionError(results['ename'], results['evalue'], results['traceback']);\n }\n\n return results;\n }\n\n /**\n * Complete the code submitted by a user.\n *\n * @param content The incoming message with the code to complete.\n */\n async complete(content: any, parent: any) {\n await this.setup(parent);\n\n const res = this._kernel.complete(content.code, content.cursor_pos);\n const results = this.formatResult(res);\n return results;\n }\n\n /**\n * Inspect the code submitted by a user.\n *\n * @param content The incoming message with the code to inspect.\n */\n async inspect(\n content: { code: string; cursor_pos: number; detail_level: 0 | 1 },\n parent: any,\n ) {\n await this.setup(parent);\n\n const res = this._kernel.inspect(\n content.code,\n content.cursor_pos,\n content.detail_level,\n );\n const results = this.formatResult(res);\n return results;\n }\n\n /**\n * Check code for completeness submitted by a user.\n *\n * @param content The incoming message with the code to check.\n */\n async isComplete(content: { code: string }, parent: any) {\n await this.setup(parent);\n\n const res = this._kernel.is_complete(content.code);\n const results = this.formatResult(res);\n return results;\n }\n\n /**\n * Respond to the commInfoRequest.\n *\n * @param content The incoming message with the comm target name.\n */\n async commInfo(\n content: any,\n parent: any,\n ): Promise<KernelMessage.ICommInfoReplyMsg['content']> {\n await this.setup(parent);\n\n const res = this._kernel.comm_info(content.target_name);\n const results = this.formatResult(res);\n\n return {\n comms: results,\n status: 'ok',\n };\n }\n\n /**\n * Respond to the commOpen.\n *\n * @param content The incoming message with the comm open.\n */\n async commOpen(content: any, parent: any) {\n await this.setup(parent);\n\n const res = this._kernel.comm_manager.comm_open(\n this._pyodide.toPy(null),\n this._pyodide.toPy(null),\n this._pyodide.toPy(content),\n );\n const results = this.formatResult(res);\n\n return results;\n }\n\n /**\n * Respond to the commMsg.\n *\n * @param content The incoming message with the comm msg.\n */\n async commMsg(content: any, parent: any) {\n await this.setup(parent);\n\n const res = this._kernel.comm_manager.comm_msg(\n this._pyodide.toPy(null),\n this._pyodide.toPy(null),\n this._pyodide.toPy(content),\n );\n const results = this.formatResult(res);\n\n return results;\n }\n\n /**\n * Respond to the commClose.\n *\n * @param content The incoming message with the comm close.\n */\n async commClose(content: any, parent: any) {\n await this.setup(parent);\n\n const res = this._kernel.comm_manager.comm_close(\n this._pyodide.toPy(null),\n this._pyodide.toPy(null),\n this._pyodide.toPy(content),\n );\n const results = this.formatResult(res);\n\n return results;\n }\n\n /**\n * Resolve the input request by getting back the reply from the main thread\n *\n * @param content The incoming message with the reply\n */\n async inputReply(content: any, parent: any) {\n await this.setup(parent);\n\n this._resolveInputReply(content);\n }\n\n /**\n * Send a input request to the front-end.\n *\n * @param prompt the text to show at the prompt\n * @param password Is the request for a password?\n */\n async sendInputRequest(prompt: string, password: boolean) {\n const content = {\n prompt,\n password,\n };\n\n this._sendWorkerMessage({\n type: 'input_request',\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n content,\n });\n }\n\n async getpass(prompt: string) {\n prompt = typeof prompt === 'undefined' ? '' : prompt;\n await this.sendInputRequest(prompt, true);\n const replyPromise = new Promise((resolve) => {\n this._resolveInputReply = resolve;\n });\n const result: any = await replyPromise;\n return result['value'];\n }\n\n async input(prompt: string) {\n prompt = typeof prompt === 'undefined' ? '' : prompt;\n await this.sendInputRequest(prompt, false);\n const replyPromise = new Promise((resolve) => {\n this._resolveInputReply = resolve;\n });\n const result: any = await replyPromise;\n return result['value'];\n }\n\n /**\n * Send a comm message to the front-end.\n *\n * @param type The type of the comm message.\n * @param content The content.\n * @param metadata The metadata.\n * @param ident The ident.\n * @param buffers The binary buffers.\n */\n async sendComm(type: string, content: any, metadata: any, ident: any, buffers: any) {\n this._sendWorkerMessage({\n type: type,\n content: this.formatResult(content),\n metadata: this.formatResult(metadata),\n ident: this.formatResult(ident),\n buffers: this.formatResult(buffers),\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n });\n }\n\n /**\n * Initialization options.\n */\n protected _options: IPyodideWorkerKernel.IOptions | null = null;\n /**\n * A promise that resolves when all initiaization is complete.\n */\n protected _initialized: Promise<void>;\n private _initializer: {\n reject: () => void;\n resolve: () => void;\n } | null = null;\n protected _pyodide: Pyodide.PyodideInterface = null as any;\n /** TODO: real typing */\n protected _localPath = '';\n protected _driveName = '';\n protected _kernel: any;\n protected _interpreter: any;\n protected _stdout_stream: any;\n protected _stderr_stream: any;\n protected _resolveInputReply: any;\n protected _driveFS: DriveFS | null = null;\n protected _sendWorkerMessage: (msg: any) => void = () => {};\n}\n"],
5
- "mappings": "k3BAaiBA,EAAAA,SAAAA,OAAjB,SAAiBA,EAAQ,CAyCvB,SAAgBC,EACdC,EACAC,EACAC,EAAQ,EACRC,EAAO,GAAE,CAET,IAAIC,EAAIJ,EAAM,OACd,GAAII,IAAM,EACR,MAAO,GAELF,EAAQ,EACVA,EAAQ,KAAK,IAAI,EAAGA,EAAQE,CAAC,EAE7BF,EAAQ,KAAK,IAAIA,EAAOE,EAAI,CAAC,EAE3BD,EAAO,EACTA,EAAO,KAAK,IAAI,EAAGA,EAAOC,CAAC,EAE3BD,EAAO,KAAK,IAAIA,EAAMC,EAAI,C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O,iBAAiBC,EAAiB,EAEzCjB,EAAU,WAAagB,EAAO,WAAW,KAAKA,CAAM,EACpDhB,EAAU,QAAUgB,EAAO,QAAQ,KAAKA,CAAM,EAC9ChB,EAAU,SAAWgB,EAAO,SAAS,KAAKA,CAAM,EAChDhB,EAAU,QAAUgB,EAAO,QAAQ,KAAKA,CAAM,EAC9ChB,EAAU,WAAagB,EAAO,WAAW,KAAKA,CAAM,EACpDhB,EAAU,SAAWgB,EAAO,SAAS,KAAKA,CAAM,EAChDhB,EAAU,SAAWgB,EAAO,SAAS,KAAKA,CAAM,EAChDhB,EAAU,QAAUgB,EAAO,QAAQ,KAAKA,CAAM,EAC9ChB,EAAU,UAAYgB,EAAO,UAAU,KAAKA,CAAM,EAClDhB,EAAU,WAAagB,EAAO,WAAW,KAAKA,CAAM",
6
- "names": ["ArrayExt", "firstIndexOf", "array", "value", "start", "stop", "n", "span", "i", "j", "lastIndexOf", "findFirstIndex", "fn", "findLastIndex", "d", "findFirstValue", "index", "findLastValue", "lowerBound", "begin", "half", "middle", "upperBound", "shallowEqual", "a", "b", "slice", "options", "step", "length", "result", "move", "fromIndex", "toIndex", "reverse", "rotate", "delta", "pivot", "fill", "insert", "removeAt", "removeFirstOf", "removeLastOf", "removeAllOf", "count", "removeFirstWhere", "removeLastWhere", "removeAllWhere", "chain", "objects", "object", "empty", "enumerate", "filter", "find", "findIndex", "min", "max", "minmax", "vmin", "vmax", "toArray", "toObject", "key", "each", "every", "some", "map", "range", "Private", "rangeLength", "reduce", "initial", "it", "first", "second", "accumulator", "next", "repeat", "once", "retro", "topologicSort", "edges", "sorted", "visited", "graph", "edge", "addEdge", "k", "visit", "fromNode", "toNode", "children", "node", "child", "stride", "StringExt", "findIndices", "source", "query", "indices", "matchSumOfSquares", "score", "matchSumOfDeltas", "last", "highlight", "cmp", "take", "item", "zip", "iters", "obj", "tuple", "JSONExt", "isPrimitive", "value", "isArray", "isObject", "deepEqual", "first", "second", "a1", "a2", "deepArrayEqual", "deepObjectEqual", "deepCopy", "deepArrayCopy", "deepObjectCopy", "i", "n", "key", "firstValue", "secondValue", "result", "subvalue", "MimeData", "mime", "data", "PluginRegistry", "options", "v", "id", "plugin", "_b", "_a", "Private", "plugins", "force", "required", "t", "optional", "services", "service", "error", "kind", "promises", "pluginId", "manifest", "downstream", "token", "reason", "PluginData", "_c", "_d", "a", "s", "p", "createPluginData", "ensureNoCycle", "dependencies", "visit", "visited", "trace", "findDependents", "edges", "add", "acc", "dep", "newEdges", "edge", "oldSize", "previousSize", "packagesOfInterest", "poi", "sorted", "topologicSort", "index", "candidate", "collectStartupPlugins", "collection", "PromiseDelegate", "resolve", "reject", "Token", "name", "description", "fallbackRandomValues", "buffer", "Random", "crypto", "uuid4Factory", "getRandomValues", "bytes", "lut", "UUID", "Signal", "sender", "slot", "thisArg", "Private", "args", "disconnectBetween", "receiver", "disconnectSender", "disconnectReceiver", "disconnectAll", "object", "clearData", "getExceptionHandler", "setExceptionHandler", "handler", "old", "Stream", "PromiseDelegate", "pending", "next", "err", "connect", "signal", "receivers", "receiversForSender", "findConnection", "senders", "sendersForReceiver", "connection", "disconnect", "scheduleCleanup", "emit", "i", "n", "invokeSlot", "dirtySet", "schedule", "connections", "find", "array", "cleanupDirtySet", "cleanupConnections", "ArrayExt", "isDeadConnection", "signaling_1", "ActivityMonitor", "options", "value", "sender", "args", "exports", "DEFAULT_MAX_SIZE", "LruCache", "options", "key", "item", "value", "exports", "MarkdownCodeBlocks", "markdownExtensions", "MarkdownCodeBlock", "startLine", "isMarkdown", "extension", "findMarkdownCodeBlocks", "text", "lines", "codeBlocks", "currentBlock", "lineIndex", "line", "lineContainsMarker", "constructingBlock", "firstIndex", "lastIndex", "exports", "require_minimist", "__commonJSMin", "exports", "module", "hasKey", "obj", "keys", "o", "key", "isNumber", "x", "isConstructorOrProto", "args", "opts", "flags", "aliases", "aliasIsBoolean", "y", "k", "defaults", "argv", "argDefined", "arg", "setKey", "value", "i", "lastKey", "setArg", "val", "notFlags", "next", "m", "letters", "broken", "j", "require_path_browserify", "__commonJSMin", "exports", "module", "assertPath", "path", "normalizeStringPosix", "allowAboveRoot", "res", "lastSegmentLength", "lastSlash", "dots", "code", "i", "lastSlashIndex", "_format", "sep", "pathObject", "dir", "base", "posix", "resolvedPath", "resolvedAbsolute", "cwd", "isAbsolute", "trailingSeparator", "joined", "arg", "from", "to", "fromStart", "fromEnd", "fromLen", "toStart", "toEnd", "toLen", "length", "lastCommonSep", "fromCode", "toCode", "out", "hasRoot", "end", "matchedSlash", "ext", "start", "extIdx", "firstNonSlashEnd", "startDot", "startPart", "preDotState", "ret", "require_requires_port", "__commonJSMin", "exports", "module", "port", "protocol", "require_querystringify", "__commonJSMin", "exports", "has", "undef", "decode", "input", "encode", "querystring", "query", "parser", "result", "part", "key", "value", "querystringify", "obj", "prefix", "pairs", "require_url_parse", "__commonJSMin", "exports", "module", "required", "qs", "controlOrWhitespace", "CRHTLF", "slashes", "port", "protocolre", "windowsDriveLetter", "trimLeft", "str", "rules", "address", "url", "isSpecial", "ignore", "lolcation", "loc", "globalVar", "location", "finaldestination", "type", "key", "Url", "scheme", "extractProtocol", "match", "protocol", "forwardSlashes", "otherSlashes", "slashesCount", "rest", "resolve", "relative", "base", "path", "last", "unshift", "up", "parser", "extracted", "parse", "instruction", "index", "instructions", "i", "set", "part", "value", "fn", "char", "ins", "toString", "stringify", "query", "host", "result", "path_1", "url_parse_1", "__importDefault", "URLExt", "parse", "url", "a", "getHostName", "normalize", "join", "parts", "u", "isSchemaLess", "prefix", "path", "encodeParts", "objectToQueryString", "value", "keys", "key", "content", "queryStringToObject", "acc", "val", "isLocal", "allowRoot", "protocol", "exports", "el", "e", "key", "name", "value", "last", "options", "path", "mode", "_a", "workspace", "_b", "labOrDoc", "_c", "treePath", "_d", "baseUrl", "wsUrl", "format", "download", "notebookPath", "url", "notebookVersion", "val", "Extension", "populate", "raw", "error", "isDeferred", "id", "separatorIndex", "extName", "isDisabled", "path_1", "PathExt", "join", "paths", "path", "removeSlash", "joinWithLeadingSlash", "basename", "ext", "dirname", "dir", "extname", "normalize", "resolve", "parts", "relative", "from", "to", "normalizeExtension", "extension", "exports", "coreutils_1", "signalToPromise", "signal", "timeout", "waitForSignal", "cleanup", "slot", "sender", "args", "exports", "Text", "HAS_SURROGATES", "jsIndexToCharIndex", "jsIdx", "text", "charIdx", "i", "charCode", "nextCharCode", "charIndexToJsIndex", "camelCase", "str", "upper", "match", "p1", "p2", "titleCase", "word", "exports", "UNITS", "Time", "formatHuman", "value", "format", "lang", "formatter", "delta", "unit", "amount", "exports", "__exportStar", "exports", "require_Mime", "__commonJSMin", "exports", "module", "Mime", "i", "typeMap", "force", "type", "extensions", "t", "ext", "path", "last", "hasPath", "require_standard", "__commonJSMin", "exports", "module", "require_other", "__commonJSMin", "exports", "module", "require_mime", "__commonJSMin", "exports", "module", "Mime", "import_coreutils", "import_mime", "IContents", "MIME", "FILE", "IBroadcastChannelWrapper", "init_tokens", "__esmMin", "TYPES", "getType", "ext", "defaultType", "fileType", "fileExt", "mime", "hasFormat", "fileFormat", "import_coreutils", "DEFAULT_STORAGE_NAME", "N_CHECKPOINTS", "encoder", "decoder", "Contents", "Private", "init_contents", "__esmMin", "init_tokens", "options", "data", "byte", "driver", "path", "_a", "type", "_b", "created", "dirname", "basename", "extname", "item", "name", "file", "counter", "MIME", "ext", "_c", "mimetype", "FILE", "format", "key", "toDir", "toPath", "storage", "serverItem", "model", "contentMap", "serverContents", "content", "oldLocalPath", "newLocalPath", "modified", "newFile", "child", "chunk", "appendChunk", "originalContent", "lastChunk", "contentBinaryString", "slashed", "toDelete", "checkpoints", "copies", "id", "checkpointID", "newContent", "newContentBinaryString", "binaryString", "bytes", "fileUrl", "response", "contentText", "contentBuffer", "contentBytes", "apiURL", "json", "err", "counters", "instanceOfStream", "nodeOrStream", "DIR_MODE", "FILE_MODE", "SEEK_CUR", "SEEK_END", "init_emscripten", "__esmMin", "DRIVE_SEPARATOR", "DRIVE_API_PATH", "BLOCK_SIZE", "encoder", "decoder", "flagNeedsWrite", "DriveFSEmscriptenStreamOps", "DriveFSEmscriptenNodeOps", "ContentsAPI", "ServiceWorkerContentsAPI", "DriveFS", "init_drivefs", "__esmMin", "init_emscripten", "fs", "stream", "path", "flags", "parsedFlags", "needsWrite", "buffer", "offset", "length", "position", "size", "_a", "oldData", "whence", "nodeOrStream", "instanceOfStream", "value", "node", "attr", "key", "file", "parent", "name", "result", "mode", "dev", "newDir", "newName", "oldNode", "newDirNode", "oldPath", "driveName", "mountpoint", "FS", "ERRNO_CODES", "newPath", "dirlist", "response", "serializedContent", "format", "binString", "len", "data", "i", "binary", "stats", "baseUrl", "xhr", "e", "options", "mount", "parts", "currentNode", "import_coreutils", "DriveContentsProcessor", "init_drivecontents", "__esmMin", "init_drivefs", "options", "request", "model", "response", "subcontent", "defaultDate", "BLOCK_SIZE", "BroadcastChannelWrapper", "init_broadcast", "__esmMin", "init_drivefs", "init_drivecontents", "options", "event", "request", "response", "DriveContentsProcessor", "DRIVE_API_PATH", "lib_exports", "__export", "BLOCK_SIZE", "BroadcastChannelWrapper", "Contents", "ContentsAPI", "DIR_MODE", "DRIVE_API_PATH", "DRIVE_SEPARATOR", "DriveContentsProcessor", "DriveFS", "DriveFSEmscriptenNodeOps", "DriveFSEmscriptenStreamOps", "FILE", "FILE_MODE", "IBroadcastChannelWrapper", "IContents", "MIME", "SEEK_CUR", "SEEK_END", "ServiceWorkerContentsAPI", "instanceOfStream", "init_lib", "__esmMin", "init_contents", "init_drivefs", "init_tokens", "init_broadcast", "init_emscripten", "init_drivecontents", "FUNCTION", "CHANNEL", "MAIN", "THREAD", "GET", "HAS", "SET", "isArray", "SharedArrayBuffer", "window", "notify", "wait", "waitAsync", "postPatched", "buffer", "onmessage", "w", "ids", "resolvers", "postMessage", "listener", "event", "_a", "details", "CHANNEL", "id", "sb", "data", "rest", "resolve", "buff", "i", "as", "Int32Array", "Map", "Uint16Array", "I32_BYTES", "UI16_BYTES", "waitInterrupt", "sb", "delay", "handler", "wait", "buffers", "context", "syncResult", "fn", "uid", "coincident", "self", "parse", "stringify", "transform", "interrupt", "sendMessage", "postPatched", "post", "transfer", "args", "CHANNEL", "FUNCTION", "decoder", "waitFor", "isAsync", "waitAsync", "seppuku", "HAS", "_", "action", "GET", "id", "SharedArrayBuffer", "deadlock", "length", "bytes", "SET", "actions", "callback", "type", "results", "event", "_a", "details", "isArray", "rest", "error", "result", "serialized", "ui16a", "i", "notify", "esm_default", "init_lib", "PyodideRemoteKernel", "resolve", "reject", "options", "_a", "parts", "pyodideUrl", "indexUrl", "loadPyodide", "pipliteWheelUrl", "disablePyPIFallback", "pipliteUrls", "loadPyodideOptions", "preloaded", "toLoad", "scriptLines", "pkgName", "globals", "mountpoint", "FS", "PATH", "ERRNO_CODES", "baseUrl", "DriveFS", "driveFS", "obj", "out", "value", "key", "res", "m", "callback", "parent", "content", "publishExecutionResult", "prompt_count", "data", "metadata", "bundle", "publishExecutionError", "ename", "evalue", "traceback", "clearOutputCallback", "wait", "displayDataCallback", "transient", "updateDisplayDataCallback", "publishStreamCallback", "name", "text", "results", "prompt", "password", "type", "ident", "buffers", "workerAPI", "esm_default", "SharedBufferContentsAPI", "ContentsAPI", "data", "PyodideDriveFS", "DriveFS", "options", "PyodideCoincidentKernel", "PyodideRemoteKernel", "mountpoint", "FS", "PATH", "ERRNO_CODES", "baseUrl", "driveFS", "worker", "sendWorkerMessage"]
3
+ "sources": ["../../../node_modules/@lumino/algorithm/src/array.ts", "../../../node_modules/@lumino/algorithm/src/chain.ts", "../../../node_modules/@lumino/algorithm/src/empty.ts", "../../../node_modules/@lumino/algorithm/src/enumerate.ts", "../../../node_modules/@lumino/algorithm/src/filter.ts", "../../../node_modules/@lumino/algorithm/src/find.ts", "../../../node_modules/@lumino/algorithm/src/iter.ts", "../../../node_modules/@lumino/algorithm/src/map.ts", "../../../node_modules/@lumino/algorithm/src/range.ts", "../../../node_modules/@lumino/algorithm/src/reduce.ts", "../../../node_modules/@lumino/algorithm/src/repeat.ts", "../../../node_modules/@lumino/algorithm/src/retro.ts", "../../../node_modules/@lumino/algorithm/src/sort.ts", "../../../node_modules/@lumino/algorithm/src/stride.ts", "../../../node_modules/@lumino/algorithm/src/string.ts", "../../../node_modules/@lumino/algorithm/src/take.ts", "../../../node_modules/@lumino/algorithm/src/zip.ts", "../../../node_modules/@lumino/coreutils/src/json.ts", "../../../node_modules/@lumino/coreutils/src/mime.ts", "../../../node_modules/@lumino/coreutils/src/plugins.ts", "../../../node_modules/@lumino/coreutils/src/promise.ts", "../../../node_modules/@lumino/coreutils/src/token.ts", "../../../node_modules/@lumino/coreutils/src/random.ts", "../../../node_modules/@lumino/coreutils/src/random.browser.ts", "../../../node_modules/@lumino/coreutils/src/uuid.ts", "../../../node_modules/@lumino/coreutils/src/uuid.browser.ts", "../../../node_modules/@lumino/signaling/src/index.ts", "../../../node_modules/@jupyterlab/coreutils/src/activitymonitor.ts", "../../../node_modules/@jupyterlab/coreutils/src/lru.ts", "../../../node_modules/@jupyterlab/coreutils/src/markdowncodeblocks.ts", "../../../node_modules/minimist/index.js", "../../../node_modules/path-browserify/index.js", "../../../node_modules/requires-port/index.js", "../../../node_modules/querystringify/index.js", "../../../node_modules/url-parse/index.js", "../../../node_modules/@jupyterlab/coreutils/src/url.ts", "../../../node_modules/@jupyterlab/coreutils/src/pageconfig.ts", "../../../node_modules/@jupyterlab/coreutils/src/path.ts", "../../../node_modules/@jupyterlab/coreutils/src/signal.ts", "../../../node_modules/@jupyterlab/coreutils/src/text.ts", "../../../node_modules/@jupyterlab/coreutils/src/time.ts", "../../../node_modules/@jupyterlab/coreutils/src/index.ts", "../../../node_modules/@jupyterlab/services/src/kernel/messages.ts", "../../../node_modules/@jupyterlab/services/src/kernel/serialize.ts", "../../../node_modules/@jupyterlab/services/src/shim/ws.ts", "../../../node_modules/@jupyterlab/services/src/serverconnection.ts", "../../../node_modules/@jupyterlab/services/src/basemanager.ts", "../../../node_modules/@jupyterlab/services/src/config/index.ts", "../../../node_modules/@jupyterlab/services/src/connectionstatus.ts", "../../../node_modules/@lumino/disposable/src/index.ts", "../../../node_modules/@jupyterlab/services/src/validate.ts", "../../../node_modules/@jupyterlab/services/src/contents/validate.ts", "../../../node_modules/@jupyterlab/services/src/contents/index.ts", "../../../node_modules/@lumino/polling/src/poll.ts", "../../../node_modules/@lumino/polling/src/ratelimiter.ts", "../../../node_modules/@jupyterlab/services/src/event/index.ts", "../../../node_modules/@jupyterlab/services/src/kernel/validate.ts", "../../../node_modules/@jupyterlab/services/src/kernel/restapi.ts", "../../../node_modules/@jupyterlab/services/src/kernel/comm.ts", "../../../node_modules/@jupyterlab/services/src/kernel/future.ts", "../../../node_modules/@jupyterlab/services/src/kernelspec/validate.ts", "../../../node_modules/@jupyterlab/services/src/kernelspec/restapi.ts", "../../../node_modules/@jupyterlab/services/src/kernelspec/manager.ts", "../../../node_modules/@jupyterlab/services/src/kernelspec/index.ts", "../../../node_modules/@jupyterlab/services/src/kernel/default.ts", "../../../node_modules/@jupyterlab/services/src/kernel/manager.ts", "../../../node_modules/@jupyterlab/services/src/kernel/index.ts", "../../../node_modules/@jupyterlab/services/src/builder/index.ts", "../../../node_modules/@jupyterlab/services/src/nbconvert/index.ts", "../../../node_modules/@jupyterlab/services/src/session/validate.ts", "../../../node_modules/@jupyterlab/services/src/session/restapi.ts", "../../../node_modules/@jupyterlab/services/src/session/default.ts", "../../../node_modules/@jupyterlab/services/src/session/manager.ts", "../../../node_modules/@jupyterlab/services/src/session/index.ts", "../../../node_modules/@jupyterlab/statedb/src/dataconnector.ts", "../../../node_modules/@lumino/properties/src/index.ts", "../../../node_modules/@jupyterlab/statedb/src/restorablepool.ts", "../../../node_modules/@jupyterlab/statedb/src/statedb.ts", "../../../node_modules/@jupyterlab/statedb/src/tokens.ts", "../../../node_modules/@jupyterlab/statedb/src/index.ts", "../../../node_modules/@jupyterlab/services/src/setting/index.ts", "../../../node_modules/@jupyterlab/services/src/terminal/restapi.ts", "../../../node_modules/@jupyterlab/services/src/terminal/terminal.ts", "../../../node_modules/@jupyterlab/services/src/terminal/default.ts", "../../../node_modules/@jupyterlab/services/src/terminal/manager.ts", "../../../node_modules/@jupyterlab/services/src/terminal/index.ts", "../../../node_modules/@jupyterlab/services/src/user/index.ts", "../../../node_modules/@jupyterlab/services/src/workspace/index.ts", "../../../node_modules/@jupyterlab/services/src/manager.ts", "../../../node_modules/@jupyterlab/services/src/tokens.ts", "../../../node_modules/@jupyterlab/services/src/index.ts", "../../../node_modules/mime/Mime.js", "../../../node_modules/mime/types/standard.js", "../../../node_modules/mime/types/other.js", "../../../node_modules/mime/index.js", "../../../node_modules/@jupyterlite/contents/src/tokens.ts", "../../../node_modules/@jupyterlite/contents/src/drive.ts", "../../../node_modules/@jupyterlite/contents/src/emscripten.ts", "../../../node_modules/@jupyterlite/contents/src/drivefs.ts", "../../../node_modules/@jupyterlite/contents/src/drivecontents.ts", "../../../node_modules/@jupyterlite/contents/src/broadcast.ts", "../../../node_modules/@jupyterlite/contents/src/index.ts", "../../../node_modules/proxy-target/esm/types.js", "../../../node_modules/coincident/esm/channel.js", "../../../node_modules/proxy-target/esm/traps.js", "../../../node_modules/coincident/esm/bridge.js", "../../../node_modules/coincident/esm/index.js", "../src/coincident.worker.ts", "../src/worker.ts"],
4
+ "sourcesContent": ["// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * The namespace for array-specific algorithms.\n */\nexport namespace ArrayExt {\n /**\n * Find the index of the first occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.firstIndexOf(data, 'red'); // -1\n * ArrayExt.firstIndexOf(data, 'one'); // 0\n * ArrayExt.firstIndexOf(data, 'one', 1); // 4\n * ArrayExt.firstIndexOf(data, 'two', 2); // -1\n * ArrayExt.firstIndexOf(data, 'two', 2, 1); // 1\n * ```\n */\n export function firstIndexOf<T>(\n array: ArrayLike<T>,\n value: T,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let span: number;\n if (stop < start) {\n span = stop + 1 + (n - start);\n } else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n\n /**\n * Find the index of the last occurrence of a value in an array.\n *\n * @param array - The array-like object to search.\n *\n * @param value - The value to locate in the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last occurrence of the value, or `-1`\n * if the value is not found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four', 'one'];\n * ArrayExt.lastIndexOf(data, 'red'); // -1\n * ArrayExt.lastIndexOf(data, 'one'); // 4\n * ArrayExt.lastIndexOf(data, 'one', 1); // 0\n * ArrayExt.lastIndexOf(data, 'two', 0); // -1\n * ArrayExt.lastIndexOf(data, 'two', 0, 1); // 1\n * ```\n */\n export function lastIndexOf<T>(\n array: ArrayLike<T>,\n value: T,\n start = -1,\n stop = 0\n ): number {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let span: number;\n if (start < stop) {\n span = start + 1 + (n - stop);\n } else {\n span = start - stop + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start - i + n) % n;\n if (array[j] === value) {\n return j;\n }\n }\n return -1;\n }\n\n /**\n * Find the index of the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstIndex(data, isEven); // 1\n * ArrayExt.findFirstIndex(data, isEven, 4); // 5\n * ArrayExt.findFirstIndex(data, isEven, 6); // -1\n * ArrayExt.findFirstIndex(data, isEven, 6, 5); // 1\n * ```\n */\n export function findFirstIndex<T>(\n array: ArrayLike<T>,\n fn: (value: T, index: number) => boolean,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let span: number;\n if (stop < start) {\n span = stop + 1 + (n - start);\n } else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n let j = (start + i) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n\n /**\n * Find the index of the last value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the last matching value, or `-1` if no\n * matching value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastIndex(data, isEven); // 5\n * ArrayExt.findLastIndex(data, isEven, 4); // 3\n * ArrayExt.findLastIndex(data, isEven, 0); // -1\n * ArrayExt.findLastIndex(data, isEven, 0, 1); // 5\n * ```\n */\n export function findLastIndex<T>(\n array: ArrayLike<T>,\n fn: (value: T, index: number) => boolean,\n start = -1,\n stop = 0\n ): number {\n let n = array.length;\n if (n === 0) {\n return -1;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let d: number;\n if (start < stop) {\n d = start + 1 + (n - stop);\n } else {\n d = start - stop + 1;\n }\n for (let i = 0; i < d; ++i) {\n let j = (start - i + n) % n;\n if (fn(array[j], j)) {\n return j;\n }\n }\n return -1;\n }\n\n /**\n * Find the first value which matches a predicate.\n *\n * @param array - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findFirstValue(data, isEven); // 2\n * ArrayExt.findFirstValue(data, isEven, 2); // 4\n * ArrayExt.findFirstValue(data, isEven, 6); // undefined\n * ArrayExt.findFirstValue(data, isEven, 6, 5); // 2\n * ```\n */\n export function findFirstValue<T>(\n array: ArrayLike<T>,\n fn: (value: T, index: number) => boolean,\n start = 0,\n stop = -1\n ): T | undefined {\n let index = findFirstIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n\n /**\n * Find the last value which matches a predicate.\n *\n * @param object - The array-like object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The last matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the front of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [1, 2, 3, 4, 3, 2, 1];\n * ArrayExt.findLastValue(data, isEven); // 2\n * ArrayExt.findLastValue(data, isEven, 4); // 4\n * ArrayExt.findLastValue(data, isEven, 0); // undefined\n * ArrayExt.findLastValue(data, isEven, 0, 1); // 2\n * ```\n */\n export function findLastValue<T>(\n array: ArrayLike<T>,\n fn: (value: T, index: number) => boolean,\n start = -1,\n stop = 0\n ): T | undefined {\n let index = findLastIndex(array, fn, start, stop);\n return index !== -1 ? array[index] : undefined;\n }\n\n /**\n * Find the index of the first element which compares `>=` to a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>=` to the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.lowerBound(data, 0, numberCmp); // 0\n * ArrayExt.lowerBound(data, 6, numberCmp); // 3\n * ArrayExt.lowerBound(data, 7, numberCmp); // 3\n * ArrayExt.lowerBound(data, -1, numberCmp); // 0\n * ArrayExt.lowerBound(data, 10, numberCmp); // 6\n * ```\n */\n export function lowerBound<T, U>(\n array: ArrayLike<T>,\n value: U,\n fn: (element: T, value: U) => number,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) < 0) {\n begin = middle + 1;\n span -= half + 1;\n } else {\n span = half;\n }\n }\n return begin;\n }\n\n /**\n * Find the index of the first element which compares `>` than a value.\n *\n * @param array - The sorted array-like object to search.\n *\n * @param value - The value to locate in the array.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if an element is less than a value, `0` if\n * an element is equal to a value, or `> 0` if an element is greater\n * than a value.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the first element which compares `>` than the\n * value, or `length` if there is no such element. If the computed\n * index for `stop` is less than `start`, then the computed index\n * for `start` is returned.\n *\n * #### Notes\n * The array must already be sorted in ascending order according to\n * the comparison function.\n *\n * #### Complexity\n * Logarithmic.\n *\n * #### Undefined Behavior\n * Searching a range which is not sorted in ascending order.\n *\n * A `start` or `stop` which is non-integral.\n *\n * Modifying the length of the array while searching.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.upperBound(data, 0, numberCmp); // 1\n * ArrayExt.upperBound(data, 6, numberCmp); // 3\n * ArrayExt.upperBound(data, 7, numberCmp); // 5\n * ArrayExt.upperBound(data, -1, numberCmp); // 0\n * ArrayExt.upperBound(data, 10, numberCmp); // 6\n * ```\n */\n export function upperBound<T, U>(\n array: ArrayLike<T>,\n value: U,\n fn: (element: T, value: U) => number,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let begin = start;\n let span = stop - start + 1;\n while (span > 0) {\n let half = span >> 1;\n let middle = begin + half;\n if (fn(array[middle], value) > 0) {\n span = half;\n } else {\n begin = middle + 1;\n span -= half + 1;\n }\n }\n return begin;\n }\n\n /**\n * Test whether two arrays are shallowly equal.\n *\n * @param a - The first array-like object to compare.\n *\n * @param b - The second array-like object to compare.\n *\n * @param fn - The comparison function to apply to the elements. It\n * should return `true` if the elements are \"equal\". The default\n * compares elements using strict `===` equality.\n *\n * @returns Whether the two arrays are shallowly equal.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * Modifying the length of the arrays while comparing.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let d1 = [0, 3, 4, 7, 7, 9];\n * let d2 = [0, 3, 4, 7, 7, 9];\n * let d3 = [42];\n * ArrayExt.shallowEqual(d1, d2); // true\n * ArrayExt.shallowEqual(d2, d3); // false\n * ```\n */\n export function shallowEqual<T>(\n a: ArrayLike<T>,\n b: ArrayLike<T>,\n fn?: (a: T, b: T) => boolean\n ): boolean {\n // Check for object identity first.\n if (a === b) {\n return true;\n }\n\n // Bail early if the lengths are different.\n if (a.length !== b.length) {\n return false;\n }\n\n // Compare each element for equality.\n for (let i = 0, n = a.length; i < n; ++i) {\n if (fn ? !fn(a[i], b[i]) : a[i] !== b[i]) {\n return false;\n }\n }\n\n // The array are shallowly equal.\n return true;\n }\n\n /**\n * Create a slice of an array subject to an optional step.\n *\n * @param array - The array-like object of interest.\n *\n * @param options - The options for configuring the slice.\n *\n * @returns A new array with the specified values.\n *\n * @throws An exception if the slice `step` is `0`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start`, `stop`, or `step` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 3, 4, 7, 7, 9];\n * ArrayExt.slice(data); // [0, 3, 4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 2 }); // [4, 7, 7, 9]\n * ArrayExt.slice(data, { start: 0, stop: 4 }); // [0, 3, 4, 7]\n * ArrayExt.slice(data, { step: 2 }); // [0, 4, 7]\n * ArrayExt.slice(data, { step: -1 }); // [9, 7, 7, 4, 3, 0]\n * ```\n */\n export function slice<T>(\n array: ArrayLike<T>,\n options: slice.IOptions = {}\n ): T[] {\n // Extract the options.\n let { start, stop, step } = options;\n\n // Set up the `step` value.\n if (step === undefined) {\n step = 1;\n }\n\n // Validate the step size.\n if (step === 0) {\n throw new Error('Slice `step` cannot be zero.');\n }\n\n // Look up the length of the array.\n let n = array.length;\n\n // Set up the `start` value.\n if (start === undefined) {\n start = step < 0 ? n - 1 : 0;\n } else if (start < 0) {\n start = Math.max(start + n, step < 0 ? -1 : 0);\n } else if (start >= n) {\n start = step < 0 ? n - 1 : n;\n }\n\n // Set up the `stop` value.\n if (stop === undefined) {\n stop = step < 0 ? -1 : n;\n } else if (stop < 0) {\n stop = Math.max(stop + n, step < 0 ? -1 : 0);\n } else if (stop >= n) {\n stop = step < 0 ? n - 1 : n;\n }\n\n // Compute the slice length.\n let length;\n if ((step < 0 && stop >= start) || (step > 0 && start >= stop)) {\n length = 0;\n } else if (step < 0) {\n length = Math.floor((stop - start + 1) / step + 1);\n } else {\n length = Math.floor((stop - start - 1) / step + 1);\n }\n\n // Compute the sliced result.\n let result: T[] = [];\n for (let i = 0; i < length; ++i) {\n result[i] = array[start + i * step];\n }\n\n // Return the result.\n return result;\n }\n\n /**\n * The namespace for the `slice` function statics.\n */\n export namespace slice {\n /**\n * The options for the `slice` function.\n */\n export interface IOptions {\n /**\n * The starting index of the slice, inclusive.\n *\n * Negative values are taken as an offset from the end\n * of the array.\n *\n * The default is `0` if `step > 0` else `n - 1`.\n */\n start?: number;\n\n /**\n * The stopping index of the slice, exclusive.\n *\n * Negative values are taken as an offset from the end\n * of the array.\n *\n * The default is `n` if `step > 0` else `-n - 1`.\n */\n stop?: number;\n\n /**\n * The step value for the slice.\n *\n * This must not be `0`.\n *\n * The default is `1`.\n */\n step?: number;\n }\n }\n\n /**\n * An array-like object which supports item assignment.\n */\n export type MutableArrayLike<T> = {\n readonly length: number;\n [index: number]: T;\n };\n\n /**\n * Move an element in an array from one index to another.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param fromIndex - The index of the element to move. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param toIndex - The target index of the element. Negative\n * values are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `fromIndex` or `toIndex` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.move(data, 1, 2); // [0, 2, 1, 3, 4]\n * ArrayExt.move(data, 4, 2); // [0, 2, 4, 1, 3]\n * ```\n */\n export function move<T>(\n array: MutableArrayLike<T>,\n fromIndex: number,\n toIndex: number\n ): void {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (fromIndex < 0) {\n fromIndex = Math.max(0, fromIndex + n);\n } else {\n fromIndex = Math.min(fromIndex, n - 1);\n }\n if (toIndex < 0) {\n toIndex = Math.max(0, toIndex + n);\n } else {\n toIndex = Math.min(toIndex, n - 1);\n }\n if (fromIndex === toIndex) {\n return;\n }\n let value = array[fromIndex];\n let d = fromIndex < toIndex ? 1 : -1;\n for (let i = fromIndex; i !== toIndex; i += d) {\n array[i] = array[i + d];\n }\n array[toIndex] = value;\n }\n\n /**\n * Reverse an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param start - The index of the first element in the range to be\n * reversed, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * reversed, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` index which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.reverse(data, 1, 3); // [0, 3, 2, 1, 4]\n * ArrayExt.reverse(data, 3); // [0, 3, 2, 4, 1]\n * ArrayExt.reverse(data); // [1, 4, 2, 3, 0]\n * ```\n */\n export function reverse<T>(\n array: MutableArrayLike<T>,\n start = 0,\n stop = -1\n ): void {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n while (start < stop) {\n let a = array[start];\n let b = array[stop];\n array[start++] = b;\n array[stop--] = a;\n }\n }\n\n /**\n * Rotate the elements of an array in-place.\n *\n * @param array - The mutable array-like object of interest.\n *\n * @param delta - The amount of rotation to apply to the elements. A\n * positive value will rotate the elements to the left. A negative\n * value will rotate the elements to the right.\n *\n * @param start - The index of the first element in the range to be\n * rotated, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * rotated, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `delta`, `start`, or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2, 3, 4];\n * ArrayExt.rotate(data, 2); // [2, 3, 4, 0, 1]\n * ArrayExt.rotate(data, -2); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 10); // [0, 1, 2, 3, 4]\n * ArrayExt.rotate(data, 9); // [4, 0, 1, 2, 3]\n * ArrayExt.rotate(data, 2, 1, 3); // [4, 2, 0, 1, 3]\n * ```\n */\n export function rotate<T>(\n array: MutableArrayLike<T>,\n delta: number,\n start = 0,\n stop = -1\n ): void {\n let n = array.length;\n if (n <= 1) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n if (start >= stop) {\n return;\n }\n let length = stop - start + 1;\n if (delta > 0) {\n delta = delta % length;\n } else if (delta < 0) {\n delta = ((delta % length) + length) % length;\n }\n if (delta === 0) {\n return;\n }\n let pivot = start + delta;\n reverse(array, start, pivot - 1);\n reverse(array, pivot, stop);\n reverse(array, start, stop);\n }\n\n /**\n * Fill an array with a static value.\n *\n * @param array - The mutable array-like object to fill.\n *\n * @param value - The static value to use to fill the array.\n *\n * @param start - The index of the first element in the range to be\n * filled, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * filled, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * #### Notes\n * If `stop < start` the fill will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * A `start` or `stop` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = ['one', 'two', 'three', 'four'];\n * ArrayExt.fill(data, 'r'); // ['r', 'r', 'r', 'r']\n * ArrayExt.fill(data, 'g', 1); // ['r', 'g', 'g', 'g']\n * ArrayExt.fill(data, 'b', 2, 3); // ['r', 'g', 'b', 'b']\n * ArrayExt.fill(data, 'z', 3, 1); // ['z', 'z', 'b', 'z']\n * ```\n */\n export function fill<T>(\n array: MutableArrayLike<T>,\n value: T,\n start = 0,\n stop = -1\n ): void {\n let n = array.length;\n if (n === 0) {\n return;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let span: number;\n if (stop < start) {\n span = stop + 1 + (n - start);\n } else {\n span = stop - start + 1;\n }\n for (let i = 0; i < span; ++i) {\n array[(start + i) % n] = value;\n }\n }\n\n /**\n * Insert a value into an array at a specific index.\n *\n * @param array - The array of interest.\n *\n * @param index - The index at which to insert the value. Negative\n * values are taken as an offset from the end of the array.\n *\n * @param value - The value to set at the specified index.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 1, 2];\n * ArrayExt.insert(data, 0, -1); // [-1, 0, 1, 2]\n * ArrayExt.insert(data, 2, 12); // [-1, 0, 12, 1, 2]\n * ArrayExt.insert(data, -1, 7); // [-1, 0, 12, 1, 7, 2]\n * ArrayExt.insert(data, 6, 19); // [-1, 0, 12, 1, 7, 2, 19]\n * ```\n */\n export function insert<T>(array: Array<T>, index: number, value: T): void {\n let n = array.length;\n if (index < 0) {\n index = Math.max(0, index + n);\n } else {\n index = Math.min(index, n);\n }\n for (let i = n; i > index; --i) {\n array[i] = array[i - 1];\n }\n array[index] = value;\n }\n\n /**\n * Remove and return a value at a specific index in an array.\n *\n * @param array - The array of interest.\n *\n * @param index - The index of the value to remove. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The value at the specified index, or `undefined` if the\n * index is out of range.\n *\n * #### Complexity\n * Linear.\n *\n * #### Undefined Behavior\n * An `index` which is non-integral.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeAt(data, 2); // 23\n * ArrayExt.removeAt(data, -2); // 12\n * ArrayExt.removeAt(data, 10); // undefined;\n * ```\n */\n export function removeAt<T>(array: Array<T>, index: number): T | undefined {\n let n = array.length;\n if (index < 0) {\n index += n;\n }\n if (index < 0 || index >= n) {\n return undefined;\n }\n let value = array[index];\n for (let i = index + 1; i < n; ++i) {\n array[i - 1] = array[i];\n }\n array.length = n - 1;\n return value;\n }\n\n /**\n * Remove the first occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstOf(data, 12); // 1\n * ArrayExt.removeFirstOf(data, 17); // -1\n * ArrayExt.removeFirstOf(data, 39, 3); // -1\n * ArrayExt.removeFirstOf(data, 39, 3, 2); // 2\n * ```\n */\n export function removeFirstOf<T>(\n array: Array<T>,\n value: T,\n start = 0,\n stop = -1\n ): number {\n let index = firstIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n\n /**\n * Remove the last occurrence of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The index of the removed value, or `-1` if the value\n * is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastOf(data, 12); // 5\n * ArrayExt.removeLastOf(data, 17); // -1\n * ArrayExt.removeLastOf(data, 39, 2); // -1\n * ArrayExt.removeLastOf(data, 39, 2, 3); // 3\n * ```\n */\n export function removeLastOf<T>(\n array: Array<T>,\n value: T,\n start = -1,\n stop = 0\n ): number {\n let index = lastIndexOf(array, value, start, stop);\n if (index !== -1) {\n removeAt(array, index);\n }\n return index;\n }\n\n /**\n * Remove all occurrences of a value from an array.\n *\n * @param array - The array of interest.\n *\n * @param value - The value to remove from the array. Values are\n * compared using strict `===` equality.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * let data = [14, 12, 23, 39, 14, 12, 19, 14];\n * ArrayExt.removeAllOf(data, 12); // 2\n * ArrayExt.removeAllOf(data, 17); // 0\n * ArrayExt.removeAllOf(data, 14, 1, 4); // 1\n * ```\n */\n export function removeAllOf<T>(\n array: Array<T>,\n value: T,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && array[i] === value) {\n count++;\n } else if (\n stop < start &&\n (i <= stop || i >= start) &&\n array[i] === value\n ) {\n count++;\n } else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n\n /**\n * Remove the first occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `stop < start` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeFirstWhere(data, isEven); // { index: 0, value: 0 }\n * ArrayExt.removeFirstWhere(data, isEven, 2); // { index: 3, value: 14 }\n * ArrayExt.removeFirstWhere(data, isEven, 4); // { index: -1, value: undefined }\n * ```\n */\n export function removeFirstWhere<T>(\n array: Array<T>,\n fn: (value: T, index: number) => boolean,\n start = 0,\n stop = -1\n ): { index: number; value: T | undefined } {\n let value: T | undefined;\n let index = findFirstIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n\n /**\n * Remove the last occurrence of a value which matches a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The removed `{ index, value }`, which will be `-1` and\n * `undefined` if the value is not contained in the array.\n *\n * #### Notes\n * If `start < stop` the search will wrap at the end of the array.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * let data = [0, 12, 23, 39, 14, 12, 75];\n * ArrayExt.removeLastWhere(data, isEven); // { index: 5, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2); // { index: 1, value: 12 }\n * ArrayExt.removeLastWhere(data, isEven, 2, 1); // { index: -1, value: undefined }\n * ```\n */\n export function removeLastWhere<T>(\n array: Array<T>,\n fn: (value: T, index: number) => boolean,\n start = -1,\n stop = 0\n ): { index: number; value: T | undefined } {\n let value: T | undefined;\n let index = findLastIndex(array, fn, start, stop);\n if (index !== -1) {\n value = removeAt(array, index);\n }\n return { index, value };\n }\n\n /**\n * Remove all occurrences of values which match a predicate.\n *\n * @param array - The array of interest.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @param start - The index of the first element in the range to be\n * searched, inclusive. The default value is `0`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @param stop - The index of the last element in the range to be\n * searched, inclusive. The default value is `-1`. Negative values\n * are taken as an offset from the end of the array.\n *\n * @returns The number of elements removed from the array.\n *\n * #### Notes\n * If `stop < start` the search will conceptually wrap at the end of\n * the array, however the array will be traversed front-to-back.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { ArrayExt } from '@lumino/algorithm';\n *\n * function isEven(value: number): boolean {\n * return value % 2 === 0;\n * }\n *\n * function isNegative(value: number): boolean {\n * return value < 0;\n * }\n *\n * let data = [0, 12, -13, -9, 23, 39, 14, -15, 12, 75];\n * ArrayExt.removeAllWhere(data, isEven); // 4\n * ArrayExt.removeAllWhere(data, isNegative, 0, 3); // 2\n * ```\n */\n export function removeAllWhere<T>(\n array: Array<T>,\n fn: (value: T, index: number) => boolean,\n start = 0,\n stop = -1\n ): number {\n let n = array.length;\n if (n === 0) {\n return 0;\n }\n if (start < 0) {\n start = Math.max(0, start + n);\n } else {\n start = Math.min(start, n - 1);\n }\n if (stop < 0) {\n stop = Math.max(0, stop + n);\n } else {\n stop = Math.min(stop, n - 1);\n }\n let count = 0;\n for (let i = 0; i < n; ++i) {\n if (start <= stop && i >= start && i <= stop && fn(array[i], i)) {\n count++;\n } else if (stop < start && (i <= stop || i >= start) && fn(array[i], i)) {\n count++;\n } else if (count > 0) {\n array[i - count] = array[i];\n }\n }\n if (count > 0) {\n array.length = n - count;\n }\n return count;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Chain together several iterables.\n *\n * @deprecated\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields the values of the iterables\n * in the order in which they are supplied.\n *\n * #### Example\n * ```typescript\n * import { chain } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = chain(data1, data2);\n *\n * Array.from(stream); // [1, 2, 3, 4, 5, 6]\n * ```\n */\nexport function* chain<T>(...objects: Iterable<T>[]): IterableIterator<T> {\n for (const object of objects) {\n yield* object;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Create an empty iterator.\n *\n * @returns A new iterator which yields nothing.\n *\n * #### Example\n * ```typescript\n * import { empty } from '@lumino/algorithm';\n *\n * let stream = empty<number>();\n *\n * Array.from(stream); // []\n * ```\n */\n// eslint-disable-next-line require-yield\nexport function* empty<T>(): IterableIterator<T> {\n return;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Enumerate an iterable object.\n *\n * @param object - The iterable object of interest.\n *\n * @param start - The starting enum value. The default is `0`.\n *\n * @returns An iterator which yields the enumerated values.\n *\n * #### Example\n * ```typescript\n * import { enumerate } from '@lumino/algorithm';\n *\n * let data = ['foo', 'bar', 'baz'];\n *\n * let stream = enumerate(data, 1);\n *\n * Array.from(stream); // [[1, 'foo'], [2, 'bar'], [3, 'baz']]\n * ```\n */\nexport function* enumerate<T>(\n object: Iterable<T>,\n start = 0\n): IterableIterator<[number, T]> {\n for (const value of object) {\n yield [start++, value];\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Filter an iterable for values which pass a test.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns An iterator which yields the values which pass the test.\n *\n * #### Example\n * ```typescript\n * import { filter } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = filter(data, value => value % 2 === 0);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nexport function* filter<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean\n): IterableIterator<T> {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n yield value;\n }\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Find the first value in an iterable which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The first matching value, or `undefined` if no matching\n * value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { find } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * find(data, isCat).name; // 'fluffy'\n * ```\n */\nexport function find<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean\n): T | undefined {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return value;\n }\n }\n return undefined;\n}\n\n/**\n * Find the index of the first value which matches a predicate.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The predicate function to apply to the values.\n *\n * @returns The index of the first matching value, or `-1` if no\n * matching value is found.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { findIndex } from '@lumino/algorithm';\n *\n * interface IAnimal { species: string, name: string };\n *\n * function isCat(value: IAnimal): boolean {\n * return value.species === 'cat';\n * }\n *\n * let data: IAnimal[] = [\n * { species: 'dog', name: 'spot' },\n * { species: 'cat', name: 'fluffy' },\n * { species: 'alligator', name: 'pocho' }\n * ];\n *\n * findIndex(data, isCat); // 1\n * ```\n */\nexport function findIndex<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean\n): number {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return index - 1;\n }\n }\n return -1;\n}\n\n/**\n * Find the minimum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The minimum value in the iterable. If multiple values are\n * equivalent to the minimum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { min } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * min([7, 4, 0, 3, 9, 4], numberCmp); // 0\n * ```\n */\nexport function min<T>(\n object: Iterable<T>,\n fn: (first: T, second: T) => number\n): T | undefined {\n let result: T | undefined = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) < 0) {\n result = value;\n }\n }\n return result;\n}\n\n/**\n * Find the maximum value in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns The maximum value in the iterable. If multiple values are\n * equivalent to the maximum, the left-most value is returned. If\n * the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { max } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * max([7, 4, 0, 3, 9, 4], numberCmp); // 9\n * ```\n */\nexport function max<T>(\n object: Iterable<T>,\n fn: (first: T, second: T) => number\n): T | undefined {\n let result: T | undefined = undefined;\n for (const value of object) {\n if (result === undefined) {\n result = value;\n continue;\n }\n if (fn(value, result) > 0) {\n result = value;\n }\n }\n return result;\n}\n\n/**\n * Find the minimum and maximum values in an iterable.\n *\n * @param object - The iterable object to search.\n *\n * @param fn - The 3-way comparison function to apply to the values.\n * It should return `< 0` if the first value is less than the second.\n * `0` if the values are equivalent, or `> 0` if the first value is\n * greater than the second.\n *\n * @returns A 2-tuple of the `[min, max]` values in the iterable. If\n * multiple values are equivalent, the left-most values are returned.\n * If the iterable is empty, this returns `undefined`.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { minmax } from '@lumino/algorithm';\n *\n * function numberCmp(a: number, b: number): number {\n * return a - b;\n * }\n *\n * minmax([7, 4, 0, 3, 9, 4], numberCmp); // [0, 9]\n * ```\n */\nexport function minmax<T>(\n object: Iterable<T>,\n fn: (first: T, second: T) => number\n): [T, T] | undefined {\n let empty = true;\n let vmin: T;\n let vmax: T;\n for (const value of object) {\n if (empty) {\n vmin = value;\n vmax = value;\n empty = false;\n } else if (fn(value, vmin!) < 0) {\n vmin = value;\n } else if (fn(value, vmax!) > 0) {\n vmax = value;\n }\n }\n return empty ? undefined : [vmin!, vmax!];\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Create an array from an iterable of values.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new array of values from the given object.\n *\n * #### Example\n * ```typescript\n * import { toArray } from '@lumino/algorithm';\n *\n * let stream = [1, 2, 3, 4, 5, 6][Symbol.iterator]();\n *\n * toArray(stream); // [1, 2, 3, 4, 5, 6];\n * ```\n */\nexport function toArray<T>(object: Iterable<T>): T[] {\n return Array.from(object);\n}\n\n/**\n * Create an object from an iterable of key/value pairs.\n *\n * @param object - The iterable object of interest.\n *\n * @returns A new object mapping keys to values.\n *\n * #### Example\n * ```typescript\n * import { toObject } from '@lumino/algorithm';\n *\n * let data: [string, number][] = [['one', 1], ['two', 2], ['three', 3]];\n *\n * toObject(data); // { one: 1, two: 2, three: 3 }\n * ```\n */\nexport function toObject<T>(object: Iterable<[string, T]>): {\n [key: string]: T;\n} {\n const result: { [key: string]: T } = {};\n for (const [key, value] of object) {\n result[key] = value;\n }\n return result;\n}\n\n/**\n * Invoke a function for each value in an iterable.\n *\n * @deprecated\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The callback function to invoke for each value.\n *\n * #### Notes\n * Iteration can be terminated early by returning `false` from the\n * callback function.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { each } from '@lumino/algorithm';\n *\n * let data = [5, 7, 0, -2, 9];\n *\n * each(data, value => { console.log(value); });\n * ```\n */\nexport function each<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean | void\n): void {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return;\n }\n }\n}\n\n/**\n * Test whether all values in an iterable satisfy a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if all values pass the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `false` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { every } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * every(data, value => value % 2 === 0); // false\n * every(data, value => value % 2 === 1); // true\n * ```\n */\nexport function every<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean\n): boolean {\n let index = 0;\n for (const value of object) {\n if (false === fn(value, index++)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Test whether any value in an iterable satisfies a predicate.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The predicate function to invoke for each value.\n *\n * @returns `true` if any value passes the test, `false` otherwise.\n *\n * #### Notes\n * Iteration terminates on the first `true` predicate result.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { some } from '@lumino/algorithm';\n *\n * let data = [5, 7, 1];\n *\n * some(data, value => value === 7); // true\n * some(data, value => value === 3); // false\n * ```\n */\nexport function some<T>(\n object: Iterable<T>,\n fn: (value: T, index: number) => boolean\n): boolean {\n let index = 0;\n for (const value of object) {\n if (fn(value, index++)) {\n return true;\n }\n }\n return false;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Transform the values of an iterable with a mapping function.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The mapping function to invoke for each value.\n *\n * @returns An iterator which yields the transformed values.\n *\n * #### Example\n * ```typescript\n * import { map } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3];\n *\n * let stream = map(data, value => value * 2);\n *\n * Array.from(stream); // [2, 4, 6]\n * ```\n */\nexport function* map<T, U>(\n object: Iterable<T>,\n fn: (value: T, index: number) => U\n): IterableIterator<U> {\n let index = 0;\n for (const value of object) {\n yield fn(value, index++);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * Create an iterator of evenly spaced values.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns An iterator which produces evenly spaced values.\n *\n * #### Notes\n * In the single argument form of `range(stop)`, `start` defaults to\n * `0` and `step` defaults to `1`.\n *\n * In the two argument form of `range(start, stop)`, `step` defaults\n * to `1`.\n *\n * #### Example\n * ```typescript\n * import { range } from '@lumino/algorithm';\n *\n * let stream = range(2, 4);\n *\n * Array.from(stream); // [2, 3]\n * ```\n */\nexport function* range(\n start: number,\n stop?: number,\n step?: number\n): IterableIterator<number> {\n if (stop === undefined) {\n stop = start;\n start = 0;\n step = 1;\n } else if (step === undefined) {\n step = 1;\n }\n const length = Private.rangeLength(start, stop, step);\n for (let index = 0; index < length; index++) {\n yield start + step * index;\n }\n}\n\n/**\n * The namespace for the module implementation details.\n */\nnamespace Private {\n /**\n * Compute the effective length of a range.\n *\n * @param start - The starting value for the range, inclusive.\n *\n * @param stop - The stopping value for the range, exclusive.\n *\n * @param step - The distance between each value.\n *\n * @returns The number of steps need to traverse the range.\n */\n export function rangeLength(\n start: number,\n stop: number,\n step: number\n ): number {\n if (step === 0) {\n return Infinity;\n }\n if (start > stop && step > 0) {\n return 0;\n }\n if (start < stop && step < 0) {\n return 0;\n }\n return Math.ceil((stop - start) / step);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Summarize all values in an iterable using a reducer function.\n *\n * @param object - The iterable object of interest.\n *\n * @param fn - The reducer function to invoke for each value.\n *\n * @param initial - The initial value to start accumulation.\n *\n * @returns The final accumulated value.\n *\n * #### Notes\n * The `reduce` function follows the conventions of `Array#reduce`.\n *\n * If the iterator is empty, an initial value is required. That value\n * will be used as the return value. If no initial value is provided,\n * an error will be thrown.\n *\n * If the iterator contains a single item and no initial value is\n * provided, the single item is used as the return value.\n *\n * Otherwise, the reducer is invoked for each element in the iterable.\n * If an initial value is not provided, the first element will be used\n * as the initial accumulated value.\n *\n * #### Complexity\n * Linear.\n *\n * #### Example\n * ```typescript\n * import { reduce } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5];\n *\n * let sum = reduce(data, (a, value) => a + value); // 15\n * ```\n */\nexport function reduce<T>(\n object: Iterable<T>,\n fn: (accumulator: T, value: T, index: number) => T\n): T;\nexport function reduce<T, U>(\n object: Iterable<T>,\n fn: (accumulator: U, value: T, index: number) => U,\n initial: U\n): U;\nexport function reduce<T>(\n object: Iterable<T>,\n fn: (accumulator: any, value: T, index: number) => any,\n initial?: unknown\n): any {\n // Setup the iterator and fetch the first value.\n const it = object[Symbol.iterator]();\n let index = 0;\n let first = it.next();\n\n // An empty iterator and no initial value is an error.\n if (first.done && initial === undefined) {\n throw new TypeError('Reduce of empty iterable with no initial value.');\n }\n\n // If the iterator is empty, return the initial value.\n if (first.done) {\n return initial;\n }\n\n // If the iterator has a single item and no initial value, the\n // reducer is not invoked and the first item is the return value.\n let second = it.next();\n if (second.done && initial === undefined) {\n return first.value;\n }\n\n // If iterator has a single item and an initial value is provided,\n // the reducer is invoked and that result is the return value.\n if (second.done) {\n return fn(initial, first.value, index++);\n }\n\n // Setup the initial accumlated value.\n let accumulator: any;\n if (initial === undefined) {\n accumulator = fn(first.value, second.value, index++);\n } else {\n accumulator = fn(fn(initial, first.value, index++), second.value, index++);\n }\n\n // Iterate the rest of the values, updating the accumulator.\n let next: IteratorResult<T>;\n while (!(next = it.next()).done) {\n accumulator = fn(accumulator, next.value, index++);\n }\n\n // Return the final accumulated value.\n return accumulator;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Create an iterator which repeats a value a number of times.\n *\n * @deprecated\n *\n * @param value - The value to repeat.\n *\n * @param count - The number of times to repeat the value.\n *\n * @returns A new iterator which repeats the specified value.\n *\n * #### Example\n * ```typescript\n * import { repeat } from '@lumino/algorithm';\n *\n * let stream = repeat(7, 3);\n *\n * Array.from(stream); // [7, 7, 7]\n * ```\n */\nexport function* repeat<T>(value: T, count: number): IterableIterator<T> {\n while (0 < count--) {\n yield value;\n }\n}\n\n/**\n * Create an iterator which yields a value a single time.\n *\n * @deprecated\n *\n * @param value - The value to wrap in an iterator.\n *\n * @returns A new iterator which yields the value a single time.\n *\n * #### Example\n * ```typescript\n * import { once } from '@lumino/algorithm';\n *\n * let stream = once(7);\n *\n * Array.from(stream); // [7]\n * ```\n */\nexport function* once<T>(value: T): IterableIterator<T> {\n yield value;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * An object which can produce a reverse iterator over its values.\n */\nexport interface IRetroable<T> {\n /**\n * Get a reverse iterator over the object's values.\n *\n * @returns An iterator which yields the object's values in reverse.\n */\n retro(): IterableIterator<T>;\n}\n\n/**\n * Create an iterator for a retroable object.\n *\n * @param object - The retroable or array-like object of interest.\n *\n * @returns An iterator which traverses the object's values in reverse.\n *\n * #### Example\n * ```typescript\n * import { retro } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = retro(data);\n *\n * Array.from(stream); // [6, 5, 4, 3, 2, 1]\n * ```\n */\nexport function* retro<T>(\n object: IRetroable<T> | ArrayLike<T>\n): IterableIterator<T> {\n if (typeof (object as IRetroable<T>).retro === 'function') {\n yield* (object as IRetroable<T>).retro();\n } else {\n for (let index = (object as ArrayLike<T>).length - 1; index > -1; index--) {\n yield (object as ArrayLike<T>)[index];\n }\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Topologically sort an iterable of edges.\n *\n * @param edges - The iterable object of edges to sort.\n * An edge is represented as a 2-tuple of `[fromNode, toNode]`.\n *\n * @returns The topologically sorted array of nodes.\n *\n * #### Notes\n * If a cycle is present in the graph, the cycle will be ignored and\n * the return value will be only approximately sorted.\n *\n * #### Example\n * ```typescript\n * import { topologicSort } from '@lumino/algorithm';\n *\n * let data = [\n * ['d', 'e'],\n * ['c', 'd'],\n * ['a', 'b'],\n * ['b', 'c']\n * ];\n *\n * topologicSort(data); // ['a', 'b', 'c', 'd', 'e']\n * ```\n */\nexport function topologicSort<T>(edges: Iterable<[T, T]>): T[] {\n // Setup the shared sorting state.\n let sorted: T[] = [];\n let visited = new Set<T>();\n let graph = new Map<T, T[]>();\n\n // Add the edges to the graph.\n for (const edge of edges) {\n addEdge(edge);\n }\n\n // Visit each node in the graph.\n for (const [k] of graph) {\n visit(k);\n }\n\n // Return the sorted results.\n return sorted;\n\n // Add an edge to the graph.\n function addEdge(edge: [T, T]): void {\n let [fromNode, toNode] = edge;\n let children = graph.get(toNode);\n if (children) {\n children.push(fromNode);\n } else {\n graph.set(toNode, [fromNode]);\n }\n }\n\n // Recursively visit the node.\n function visit(node: T): void {\n if (visited.has(node)) {\n return;\n }\n visited.add(node);\n let children = graph.get(node);\n if (children) {\n for (const child of children) {\n visit(child);\n }\n }\n sorted.push(node);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Iterate over an iterable using a stepped increment.\n *\n * @param object - The iterable object of interest.\n *\n * @param step - The distance to step on each iteration. A value\n * of less than `1` will behave the same as a value of `1`.\n *\n * @returns An iterator which traverses the iterable step-wise.\n *\n * #### Example\n * ```typescript\n * import { stride } from '@lumino/algorithm';\n *\n * let data = [1, 2, 3, 4, 5, 6];\n *\n * let stream = stride(data, 2);\n *\n * Array.from(stream); // [1, 3, 5];\n * ```\n */\nexport function* stride<T>(\n object: Iterable<T>,\n step: number\n): IterableIterator<T> {\n let count = 0;\n for (const value of object) {\n if (0 === count++ % step) {\n yield value;\n }\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * The namespace for string-specific algorithms.\n */\nexport namespace StringExt {\n /**\n * Find the indices of characters in a source text.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The matched indices, or `null` if there is no match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * In order for there to be a match, all of the characters in `query`\n * **must** appear in `source` in the order given by `query`.\n *\n * Characters are matched using strict `===` equality.\n */\n export function findIndices(\n source: string,\n query: string,\n start = 0\n ): number[] | null {\n let indices = new Array<number>(query.length);\n for (let i = 0, j = start, n = query.length; i < n; ++i, ++j) {\n j = source.indexOf(query[i], j);\n if (j === -1) {\n return null;\n }\n indices[i] = j;\n }\n return indices;\n }\n\n /**\n * The result of a string match function.\n */\n export interface IMatchResult {\n /**\n * A score which indicates the strength of the match.\n *\n * The documentation of a given match function should specify\n * whether a lower or higher score is a stronger match.\n */\n score: number;\n\n /**\n * The indices of the matched characters in the source text.\n *\n * The indices will appear in increasing order.\n */\n indices: number[];\n }\n\n /**\n * A string matcher which uses a sum-of-squares algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-squares approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The index of each\n * matching character is squared and added to the score. This means\n * that early and consecutive character matches are preferred, while\n * late matches are heavily penalized.\n */\n export function matchSumOfSquares(\n source: string,\n query: string,\n start = 0\n ): IMatchResult | null {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i] - start;\n score += j * j;\n }\n return { score, indices };\n }\n\n /**\n * A string matcher which uses a sum-of-deltas algorithm.\n *\n * @param source - The source text which should be searched.\n *\n * @param query - The characters to locate in the source text.\n *\n * @param start - The index to start the search.\n *\n * @returns The match result, or `null` if there is no match.\n * A lower `score` represents a stronger match.\n *\n * #### Complexity\n * Linear on `sourceText`.\n *\n * #### Notes\n * This scoring algorithm uses a sum-of-deltas approach to determine\n * the score. In order for there to be a match, all of the characters\n * in `query` **must** appear in `source` in order. The delta between\n * the indices are summed to create the score. This means that groups\n * of matched characters are preferred, while fragmented matches are\n * penalized.\n */\n export function matchSumOfDeltas(\n source: string,\n query: string,\n start = 0\n ): IMatchResult | null {\n let indices = findIndices(source, query, start);\n if (!indices) {\n return null;\n }\n let score = 0;\n let last = start - 1;\n for (let i = 0, n = indices.length; i < n; ++i) {\n let j = indices[i];\n score += j - last - 1;\n last = j;\n }\n return { score, indices };\n }\n\n /**\n * Highlight the matched characters of a source text.\n *\n * @param source - The text which should be highlighted.\n *\n * @param indices - The indices of the matched characters. They must\n * appear in increasing order and must be in bounds of the source.\n *\n * @param fn - The function to apply to the matched chunks.\n *\n * @returns An array of unmatched and highlighted chunks.\n */\n export function highlight<T>(\n source: string,\n indices: ReadonlyArray<number>,\n fn: (chunk: string) => T\n ): Array<string | T> {\n // Set up the result array.\n let result: Array<string | T> = [];\n\n // Set up the counter variables.\n let k = 0;\n let last = 0;\n let n = indices.length;\n\n // Iterator over each index.\n while (k < n) {\n // Set up the chunk indices.\n let i = indices[k];\n let j = indices[k];\n\n // Advance the right chunk index until it's non-contiguous.\n while (++k < n && indices[k] === j + 1) {\n j++;\n }\n\n // Extract the unmatched text.\n if (last < i) {\n result.push(source.slice(last, i));\n }\n\n // Extract and highlight the matched text.\n if (i < j + 1) {\n result.push(fn(source.slice(i, j + 1)));\n }\n\n // Update the last visited index.\n last = j + 1;\n }\n\n // Extract any remaining unmatched text.\n if (last < source.length) {\n result.push(source.slice(last));\n }\n\n // Return the highlighted result.\n return result;\n }\n\n /**\n * A 3-way string comparison function.\n *\n * @param a - The first string of interest.\n *\n * @param b - The second string of interest.\n *\n * @returns `-1` if `a < b`, else `1` if `a > b`, else `0`.\n */\n export function cmp(a: string, b: string): number {\n return a < b ? -1 : a > b ? 1 : 0;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * Take a fixed number of items from an iterable.\n *\n * @param object - The iterable object of interest.\n *\n * @param count - The number of items to take from the iterable.\n *\n * @returns An iterator which yields the specified number of items\n * from the source iterable.\n *\n * #### Notes\n * The returned iterator will exhaust early if the source iterable\n * contains an insufficient number of items.\n *\n * #### Example\n * ```typescript\n * import { take } from '@lumino/algorithm';\n *\n * let stream = take([5, 4, 3, 2, 1, 0, -1], 3);\n *\n * Array.from(stream); // [5, 4, 3]\n * ```\n */\nexport function* take<T>(\n object: Iterable<T>,\n count: number\n): IterableIterator<T> {\n if (count < 1) {\n return;\n }\n const it = object[Symbol.iterator]();\n let item: IteratorResult<T>;\n while (0 < count-- && !(item = it.next()).done) {\n yield item.value;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nimport { every } from './iter';\n\n/**\n * Iterate several iterables in lockstep.\n *\n * @param objects - The iterable objects of interest.\n *\n * @returns An iterator which yields successive tuples of values where\n * each value is taken in turn from the provided iterables. It will\n * be as long as the shortest provided iterable.\n *\n * #### Example\n * ```typescript\n * import { zip } from '@lumino/algorithm';\n *\n * let data1 = [1, 2, 3];\n * let data2 = [4, 5, 6];\n *\n * let stream = zip(data1, data2);\n *\n * Array.from(stream); // [[1, 4], [2, 5], [3, 6]]\n * ```\n */\nexport function* zip<T>(...objects: Iterable<T>[]): IterableIterator<T[]> {\n const iters = objects.map(obj => obj[Symbol.iterator]());\n let tuple = iters.map(it => it.next());\n for (; every(tuple, item => !item.done); tuple = iters.map(it => it.next())) {\n yield tuple.map(item => item.value);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * A type alias for a JSON primitive.\n */\nexport type JSONPrimitive = boolean | number | string | null;\n\n/**\n * A type alias for a JSON value.\n */\nexport type JSONValue = JSONPrimitive | JSONObject | JSONArray;\n\n/**\n * A type definition for a JSON object.\n */\nexport interface JSONObject {\n [key: string]: JSONValue;\n}\n\n/**\n * A type definition for a JSON array.\n */\nexport interface JSONArray extends Array<JSONValue> {}\n\n/**\n * A type definition for a readonly JSON object.\n */\nexport interface ReadonlyJSONObject {\n readonly [key: string]: ReadonlyJSONValue;\n}\n\n/**\n * A type definition for a readonly JSON array.\n */\nexport interface ReadonlyJSONArray extends ReadonlyArray<ReadonlyJSONValue> {}\n\n/**\n * A type alias for a readonly JSON value.\n */\nexport type ReadonlyJSONValue =\n | JSONPrimitive\n | ReadonlyJSONObject\n | ReadonlyJSONArray;\n\n/**\n * A type alias for a partial JSON value.\n *\n * Note: Partial here means that JSON object attributes can be `undefined`.\n */\nexport type PartialJSONValue =\n | JSONPrimitive\n | PartialJSONObject\n | PartialJSONArray;\n\n/**\n * A type definition for a partial JSON object.\n *\n * Note: Partial here means that the JSON object attributes can be `undefined`.\n */\nexport interface PartialJSONObject {\n [key: string]: PartialJSONValue | undefined;\n}\n\n/**\n * A type definition for a partial JSON array.\n *\n * Note: Partial here means that JSON object attributes can be `undefined`.\n */\nexport interface PartialJSONArray extends Array<PartialJSONValue> {}\n\n/**\n * A type definition for a readonly partial JSON object.\n *\n * Note: Partial here means that JSON object attributes can be `undefined`.\n */\nexport interface ReadonlyPartialJSONObject {\n readonly [key: string]: ReadonlyPartialJSONValue | undefined;\n}\n\n/**\n * A type definition for a readonly partial JSON array.\n *\n * Note: Partial here means that JSON object attributes can be `undefined`.\n */\nexport interface ReadonlyPartialJSONArray\n extends ReadonlyArray<ReadonlyPartialJSONValue> {}\n\n/**\n * A type alias for a readonly partial JSON value.\n *\n * Note: Partial here means that JSON object attributes can be `undefined`.\n */\nexport type ReadonlyPartialJSONValue =\n | JSONPrimitive\n | ReadonlyPartialJSONObject\n | ReadonlyPartialJSONArray;\n\n/**\n * The namespace for JSON-specific functions.\n */\nexport namespace JSONExt {\n /**\n * A shared frozen empty JSONObject\n */\n export const emptyObject = Object.freeze({}) as ReadonlyJSONObject;\n\n /**\n * A shared frozen empty JSONArray\n */\n export const emptyArray = Object.freeze([]) as ReadonlyJSONArray;\n\n /**\n * Test whether a JSON value is a primitive.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a primitive,`false` otherwise.\n */\n export function isPrimitive(\n value: ReadonlyPartialJSONValue\n ): value is JSONPrimitive {\n return (\n value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string'\n );\n }\n\n /**\n * Test whether a JSON value is an array.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a an array, `false` otherwise.\n */\n export function isArray(value: JSONValue): value is JSONArray;\n export function isArray(value: ReadonlyJSONValue): value is ReadonlyJSONArray;\n export function isArray(value: PartialJSONValue): value is PartialJSONArray;\n export function isArray(\n value: ReadonlyPartialJSONValue\n ): value is ReadonlyPartialJSONArray;\n export function isArray(value: ReadonlyPartialJSONValue): boolean {\n return Array.isArray(value);\n }\n\n /**\n * Test whether a JSON value is an object.\n *\n * @param value - The JSON value of interest.\n *\n * @returns `true` if the value is a an object, `false` otherwise.\n */\n export function isObject(value: JSONValue): value is JSONObject;\n export function isObject(\n value: ReadonlyJSONValue\n ): value is ReadonlyJSONObject;\n export function isObject(value: PartialJSONValue): value is PartialJSONObject;\n export function isObject(\n value: ReadonlyPartialJSONValue\n ): value is ReadonlyPartialJSONObject;\n export function isObject(value: ReadonlyPartialJSONValue): boolean {\n return !isPrimitive(value) && !isArray(value);\n }\n\n /**\n * Compare two JSON values for deep equality.\n *\n * @param first - The first JSON value of interest.\n *\n * @param second - The second JSON value of interest.\n *\n * @returns `true` if the values are equivalent, `false` otherwise.\n */\n export function deepEqual(\n first: ReadonlyPartialJSONValue,\n second: ReadonlyPartialJSONValue\n ): boolean {\n // Check referential and primitive equality first.\n if (first === second) {\n return true;\n }\n\n // If one is a primitive, the `===` check ruled out the other.\n if (isPrimitive(first) || isPrimitive(second)) {\n return false;\n }\n\n // Test whether they are arrays.\n let a1 = isArray(first);\n let a2 = isArray(second);\n\n // Bail if the types are different.\n if (a1 !== a2) {\n return false;\n }\n\n // If they are both arrays, compare them.\n if (a1 && a2) {\n return deepArrayEqual(\n first as ReadonlyPartialJSONArray,\n second as ReadonlyPartialJSONArray\n );\n }\n\n // At this point, they must both be objects.\n return deepObjectEqual(\n first as ReadonlyPartialJSONObject,\n second as ReadonlyPartialJSONObject\n );\n }\n\n /**\n * Create a deep copy of a JSON value.\n *\n * @param value - The JSON value to copy.\n *\n * @returns A deep copy of the given JSON value.\n */\n export function deepCopy<T extends ReadonlyPartialJSONValue>(value: T): T {\n // Do nothing for primitive values.\n if (isPrimitive(value)) {\n return value;\n }\n\n // Deep copy an array.\n if (isArray(value)) {\n return deepArrayCopy(value);\n }\n\n // Deep copy an object.\n return deepObjectCopy(value);\n }\n\n /**\n * Compare two JSON arrays for deep equality.\n */\n function deepArrayEqual(\n first: ReadonlyPartialJSONArray,\n second: ReadonlyPartialJSONArray\n ): boolean {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n\n // Test the arrays for equal length.\n if (first.length !== second.length) {\n return false;\n }\n\n // Compare the values for equality.\n for (let i = 0, n = first.length; i < n; ++i) {\n if (!deepEqual(first[i], second[i])) {\n return false;\n }\n }\n\n // At this point, the arrays are equal.\n return true;\n }\n\n /**\n * Compare two JSON objects for deep equality.\n */\n function deepObjectEqual(\n first: ReadonlyPartialJSONObject,\n second: ReadonlyPartialJSONObject\n ): boolean {\n // Check referential equality first.\n if (first === second) {\n return true;\n }\n\n // Check for the first object's keys in the second object.\n for (let key in first) {\n if (first[key] !== undefined && !(key in second)) {\n return false;\n }\n }\n\n // Check for the second object's keys in the first object.\n for (let key in second) {\n if (second[key] !== undefined && !(key in first)) {\n return false;\n }\n }\n\n // Compare the values for equality.\n for (let key in first) {\n // Get the values.\n let firstValue = first[key];\n let secondValue = second[key];\n\n // If both are undefined, ignore the key.\n if (firstValue === undefined && secondValue === undefined) {\n continue;\n }\n\n // If only one value is undefined, the objects are not equal.\n if (firstValue === undefined || secondValue === undefined) {\n return false;\n }\n\n // Compare the values.\n if (!deepEqual(firstValue, secondValue)) {\n return false;\n }\n }\n\n // At this point, the objects are equal.\n return true;\n }\n\n /**\n * Create a deep copy of a JSON array.\n */\n function deepArrayCopy(value: any): any {\n let result = new Array<any>(value.length);\n for (let i = 0, n = value.length; i < n; ++i) {\n result[i] = deepCopy(value[i]);\n }\n return result;\n }\n\n /**\n * Create a deep copy of a JSON object.\n */\n function deepObjectCopy(value: any): any {\n let result: any = {};\n for (let key in value) {\n // Ignore undefined values.\n let subvalue = value[key];\n if (subvalue === undefined) {\n continue;\n }\n result[key] = deepCopy(subvalue);\n }\n return result;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * An object which stores MIME data for general application use.\n *\n * #### Notes\n * This class does not attempt to enforce \"correctness\" of MIME types\n * and their associated data. Since this class is designed to transfer\n * arbitrary data and objects within the same application, it assumes\n * that the user provides correct and accurate data.\n */\nexport class MimeData {\n /**\n * Get an array of the MIME types contained within the dataset.\n *\n * @returns A new array of the MIME types, in order of insertion.\n */\n types(): string[] {\n return this._types.slice();\n }\n\n /**\n * Test whether the dataset has an entry for the given type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns `true` if the dataset contains a value for the given\n * MIME type, `false` otherwise.\n */\n hasData(mime: string): boolean {\n return this._types.indexOf(mime) !== -1;\n }\n\n /**\n * Get the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @returns The value for the given MIME type, or `undefined` if\n * the dataset does not contain a value for the type.\n */\n getData(mime: string): any | undefined {\n let i = this._types.indexOf(mime);\n return i !== -1 ? this._values[i] : undefined;\n }\n\n /**\n * Set the data value for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * @param data - The data value for the given MIME type.\n *\n * #### Notes\n * This will overwrite any previous entry for the MIME type.\n */\n setData(mime: string, data: unknown): void {\n this.clearData(mime);\n this._types.push(mime);\n this._values.push(data);\n }\n\n /**\n * Remove the data entry for the given MIME type.\n *\n * @param mime - The MIME type of interest.\n *\n * #### Notes\n * This is a no-op if there is no entry for the given MIME type.\n */\n clearData(mime: string): void {\n let i = this._types.indexOf(mime);\n if (i !== -1) {\n this._types.splice(i, 1);\n this._values.splice(i, 1);\n }\n }\n\n /**\n * Remove all data entries from the dataset.\n */\n clear(): void {\n this._types.length = 0;\n this._values.length = 0;\n }\n\n private _types: string[] = [];\n private _values: any[] = [];\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\nimport { topologicSort } from '@lumino/algorithm';\n\nimport { Token } from './token';\n\n/**\n * A user-defined application plugin.\n *\n * @typeParam T - The type for the application.\n *\n * @typeParam U - The service type, if the plugin `provides` one.\n *\n * #### Notes\n * Plugins are the foundation for building an extensible application.\n *\n * Plugins consume and provide \"services\", which are nothing more than\n * concrete implementations of interfaces and/or abstract types.\n *\n * Unlike regular imports and exports, which tie the service consumer\n * to a particular implementation of the service, plugins decouple the\n * service producer from the service consumer, allowing an application\n * to be easily customized by third parties in a type-safe fashion.\n */\nexport interface IPlugin<T, U> {\n /**\n * The human readable ID of the plugin.\n *\n * #### Notes\n * This must be unique within an application.\n */\n id: string;\n\n /**\n * Plugin description.\n *\n * #### Notes\n * This can be used to provide user documentation on the feature\n * brought by a plugin.\n */\n description?: string;\n\n /**\n * Whether the plugin should be activated on application start or waiting for being\n * required. If the value is 'defer' then the plugin should be activated only after\n * the application is started.\n *\n * #### Notes\n * The default is `false`.\n */\n autoStart?: boolean | 'defer';\n\n /**\n * The types of required services for the plugin, if any.\n *\n * #### Notes\n * These tokens correspond to the services that are required by\n * the plugin for correct operation.\n *\n * When the plugin is activated, a concrete instance of each type\n * will be passed to the `activate()` function, in the order they\n * are specified in the `requires` array.\n */\n requires?: Token<any>[];\n\n /**\n * The types of optional services for the plugin, if any.\n *\n * #### Notes\n * These tokens correspond to the services that can be used by the\n * plugin if available, but are not necessarily required.\n *\n * The optional services will be passed to the `activate()` function\n * following all required services. If an optional service cannot be\n * resolved, `null` will be passed in its place.\n */\n optional?: Token<any>[];\n\n /**\n * The type of service provided by the plugin, if any.\n *\n * #### Notes\n * This token corresponds to the service exported by the plugin.\n *\n * When the plugin is activated, the return value of `activate()`\n * is used as the concrete instance of the type.\n */\n provides?: Token<U> | null;\n\n /**\n * A function invoked to activate the plugin.\n *\n * @param app - The application provided by {@link PluginRegistry.application} .\n *\n * @param args - The services specified by the `requires` property.\n *\n * @returns The provided service, or a promise to the service.\n *\n * #### Notes\n * This function will be called whenever the plugin is manually\n * activated, or when another plugin being activated requires\n * the service it provides.\n *\n * This function will not be called unless all of its required\n * services can be fulfilled.\n */\n activate: (app: T, ...args: any[]) => U | Promise<U>;\n\n /**\n * A function invoked to deactivate the plugin.\n *\n * @param app - The application {@link PluginRegistry.application} .\n *\n * @param args - The services specified by the `requires` property.\n */\n deactivate?: ((app: T, ...args: any[]) => void | Promise<void>) | null;\n}\n\n/**\n * Plugin registry.\n */\nexport class PluginRegistry<T = any> {\n constructor(options: PluginRegistry.IOptions = {}) {\n if (options.validatePlugin) {\n console.info(\n 'Plugins may be rejected by the custom validation plugin method.'\n );\n this._validatePlugin = options.validatePlugin;\n }\n }\n\n /**\n * The application object.\n *\n * It will be provided as first argument to the\n * plugins activation and deactivation functions.\n *\n * It can only be set once.\n *\n * By default, it is `null`.\n */\n get application(): T {\n return this._application;\n }\n set application(v: T) {\n if (this._application !== null) {\n throw Error(\n 'PluginRegistry.application is already set. It cannot be overridden.'\n );\n }\n\n this._application = v;\n }\n\n /**\n * The list of all the deferred plugins.\n */\n get deferredPlugins(): string[] {\n return Array.from(this._plugins)\n .filter(([id, plugin]) => plugin.autoStart === 'defer')\n .map(([id, plugin]) => id);\n }\n\n /**\n * Get a plugin description.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns The plugin description.\n */\n getPluginDescription(id: string): string {\n return this._plugins.get(id)?.description ?? '';\n }\n\n /**\n * Test whether a plugin is registered with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns `true` if the plugin is registered, `false` otherwise.\n */\n hasPlugin(id: string): boolean {\n return this._plugins.has(id);\n }\n\n /**\n * Test whether a plugin is activated with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns `true` if the plugin is activated, `false` otherwise.\n */\n isPluginActivated(id: string): boolean {\n return this._plugins.get(id)?.activated ?? false;\n }\n\n /**\n * List the IDs of the plugins registered with the application.\n *\n * @returns A new array of the registered plugin IDs.\n */\n listPlugins(): string[] {\n return Array.from(this._plugins.keys());\n }\n\n /**\n * Register a plugin with the application.\n *\n * @param plugin - The plugin to register.\n *\n * #### Notes\n * An error will be thrown if a plugin with the same ID is already\n * registered, or if the plugin has a circular dependency.\n *\n * If the plugin provides a service which has already been provided\n * by another plugin, the new service will override the old service.\n */\n registerPlugin(plugin: IPlugin<T, any>): void {\n // Throw an error if the plugin ID is already registered.\n if (this._plugins.has(plugin.id)) {\n throw new TypeError(`Plugin '${plugin.id}' is already registered.`);\n }\n\n if (!this._validatePlugin(plugin)) {\n throw new Error(`Plugin '${plugin.id}' is not valid.`);\n }\n\n // Create the normalized plugin data.\n const data = Private.createPluginData(plugin);\n\n // Ensure the plugin does not cause a cyclic dependency.\n Private.ensureNoCycle(data, this._plugins, this._services);\n\n // Add the service token to the service map.\n if (data.provides) {\n this._services.set(data.provides, data.id);\n }\n\n // Add the plugin to the plugin map.\n this._plugins.set(data.id, data);\n }\n\n /**\n * Register multiple plugins with the application.\n *\n * @param plugins - The plugins to register.\n *\n * #### Notes\n * This calls `registerPlugin()` for each of the given plugins.\n */\n registerPlugins(plugins: IPlugin<T, any>[]): void {\n for (const plugin of plugins) {\n this.registerPlugin(plugin);\n }\n }\n\n /**\n * Deregister a plugin with the application.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @param force - Whether to deregister the plugin even if it is active.\n */\n deregisterPlugin(id: string, force?: boolean): void {\n const plugin = this._plugins.get(id);\n if (!plugin) {\n return;\n }\n\n if (plugin.activated && !force) {\n throw new Error(`Plugin '${id}' is still active.`);\n }\n\n this._plugins.delete(id);\n }\n\n /**\n * Activate the plugin with the given ID.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns A promise which resolves when the plugin is activated\n * or rejects with an error if it cannot be activated.\n */\n async activatePlugin(id: string): Promise<void> {\n // Reject the promise if the plugin is not registered.\n const plugin = this._plugins.get(id);\n if (!plugin) {\n throw new ReferenceError(`Plugin '${id}' is not registered.`);\n }\n\n // Resolve immediately if the plugin is already activated.\n if (plugin.activated) {\n return;\n }\n\n // Return the pending resolver promise if it exists.\n if (plugin.promise) {\n return plugin.promise;\n }\n\n // Resolve the required services for the plugin.\n const required = plugin.requires.map(t => this.resolveRequiredService(t));\n\n // Resolve the optional services for the plugin.\n const optional = plugin.optional.map(t => this.resolveOptionalService(t));\n\n // Setup the resolver promise for the plugin.\n plugin.promise = Promise.all([...required, ...optional])\n .then(services =>\n plugin!.activate.apply(undefined, [this.application, ...services])\n )\n .then(service => {\n plugin!.service = service;\n plugin!.activated = true;\n plugin!.promise = null;\n })\n .catch(error => {\n plugin!.promise = null;\n throw error;\n });\n\n // Return the pending resolver promise.\n return plugin.promise;\n }\n\n /**\n * Activate all the deferred plugins.\n *\n * @returns A promise which will resolve when each plugin is activated\n * or rejects with an error if one cannot be activated.\n */\n async activatePlugins(\n kind: 'startUp' | 'defer',\n options: PluginRegistry.IStartOptions = {}\n ): Promise<void> {\n switch (kind) {\n case 'defer': {\n const promises = this.deferredPlugins\n .filter(pluginId => this._plugins.get(pluginId)!.autoStart)\n .map(pluginId => {\n return this.activatePlugin(pluginId);\n });\n await Promise.all(promises);\n break;\n }\n case 'startUp': {\n // Collect the ids of the startup plugins.\n const startups = Private.collectStartupPlugins(this._plugins, options);\n\n // Generate the activation promises.\n const promises = startups.map(async id => {\n try {\n return await this.activatePlugin(id);\n } catch (error) {\n console.error(`Plugin '${id}' failed to activate.`, error);\n }\n });\n await Promise.all(promises);\n break;\n }\n }\n }\n\n /**\n * Deactivate the plugin and its downstream dependents if and only if the\n * plugin and its dependents all support `deactivate`.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @returns A list of IDs of downstream plugins deactivated with this one.\n */\n async deactivatePlugin(id: string): Promise<string[]> {\n // Reject the promise if the plugin is not registered.\n const plugin = this._plugins.get(id);\n if (!plugin) {\n throw new ReferenceError(`Plugin '${id}' is not registered.`);\n }\n\n // Bail early if the plugin is not activated.\n if (!plugin.activated) {\n return [];\n }\n\n // Check that this plugin can deactivate.\n if (!plugin.deactivate) {\n throw new TypeError(`Plugin '${id}'#deactivate() method missing`);\n }\n\n // Find the optimal deactivation order for plugins downstream of this one.\n const manifest = Private.findDependents(id, this._plugins, this._services);\n const downstream = manifest.map(id => this._plugins.get(id)!);\n\n // Check that all downstream plugins can deactivate.\n for (const plugin of downstream) {\n if (!plugin.deactivate) {\n throw new TypeError(\n `Plugin ${plugin.id}#deactivate() method missing (depends on ${id})`\n );\n }\n }\n\n // Deactivate all downstream plugins.\n for (const plugin of downstream) {\n const services = [...plugin.requires, ...plugin.optional].map(service => {\n const id = this._services.get(service);\n return id ? this._plugins.get(id)!.service : null;\n });\n\n // Await deactivation so the next plugins only receive active services.\n await plugin.deactivate!(this.application, ...services);\n plugin.service = null;\n plugin.activated = false;\n }\n\n // Remove plugin ID and return manifest of deactivated plugins.\n manifest.pop();\n return manifest;\n }\n\n /**\n * Resolve a required service of a given type.\n *\n * @param token - The token for the service type of interest.\n *\n * @returns A promise which resolves to an instance of the requested\n * service, or rejects with an error if it cannot be resolved.\n *\n * #### Notes\n * Services are singletons. The same instance will be returned each\n * time a given service token is resolved.\n *\n * If the plugin which provides the service has not been activated,\n * resolving the service will automatically activate the plugin.\n *\n * User code will not typically call this method directly. Instead,\n * the required services for the user's plugins will be resolved\n * automatically when the plugin is activated.\n */\n async resolveRequiredService<U>(token: Token<U>): Promise<U> {\n // Reject the promise if there is no provider for the type.\n const id = this._services.get(token);\n if (!id) {\n throw new TypeError(`No provider for: ${token.name}.`);\n }\n\n // Activate the plugin if necessary.\n const plugin = this._plugins.get(id)!;\n if (!plugin.activated) {\n await this.activatePlugin(id);\n }\n\n return plugin.service;\n }\n\n /**\n * Resolve an optional service of a given type.\n *\n * @param token - The token for the service type of interest.\n *\n * @returns A promise which resolves to an instance of the requested\n * service, or `null` if it cannot be resolved.\n *\n * #### Notes\n * Services are singletons. The same instance will be returned each\n * time a given service token is resolved.\n *\n * If the plugin which provides the service has not been activated,\n * resolving the service will automatically activate the plugin.\n *\n * User code will not typically call this method directly. Instead,\n * the optional services for the user's plugins will be resolved\n * automatically when the plugin is activated.\n */\n async resolveOptionalService<U>(token: Token<U>): Promise<U | null> {\n // Resolve with `null` if there is no provider for the type.\n const id = this._services.get(token);\n if (!id) {\n return null;\n }\n\n // Activate the plugin if necessary.\n const plugin = this._plugins.get(id)!;\n if (!plugin.activated) {\n try {\n await this.activatePlugin(id);\n } catch (reason) {\n console.error(reason);\n return null;\n }\n }\n\n return plugin.service;\n }\n\n private _application: any = null;\n private _validatePlugin: (plugin: IPlugin<any, any>) => boolean = () => true;\n private _plugins = new Map<string, Private.IPluginData<T>>();\n private _services = new Map<Token<any>, string>();\n}\n\n/**\n * PluginRegistry namespace\n */\nexport namespace PluginRegistry {\n /**\n * PluginRegistry constructor options.\n */\n export interface IOptions {\n /**\n * Validate that a plugin is allowed to be registered.\n *\n * Default is `() => true`.\n *\n * @param plugin The plugin to validate\n * @returns Whether the plugin can be registered or not.\n *\n * #### Notes\n * We recommend you print a console message with the reason\n * a plugin is invalid.\n */\n validatePlugin?: (plugin: IPlugin<any, any>) => boolean;\n }\n\n /**\n * An options object for application startup.\n */\n export interface IStartOptions {\n /**\n * The plugins to activate on startup.\n *\n * #### Notes\n * These will be *in addition* to any `autoStart` plugins.\n */\n startPlugins?: string[];\n\n /**\n * The plugins to **not** activate on startup.\n *\n * #### Notes\n * This will override `startPlugins` and any `autoStart` plugins.\n */\n ignorePlugins?: string[];\n }\n}\n\n/**\n * The namespace for the module implementation details.\n */\nnamespace Private {\n /**\n * An object which holds the full application state for a plugin.\n */\n export interface IPluginData<T = any> {\n /**\n * The human readable ID of the plugin.\n */\n readonly id: string;\n\n /**\n * The description of the plugin.\n */\n readonly description: string;\n\n /**\n * Whether the plugin should be activated on application start or waiting for being\n * required. If the value is 'defer' then the plugin should be activated only after\n * the application is started.\n */\n readonly autoStart: boolean | 'defer';\n\n /**\n * The types of required services for the plugin, or `[]`.\n */\n readonly requires: Token<any>[];\n\n /**\n * The types of optional services for the the plugin, or `[]`.\n */\n readonly optional: Token<any>[];\n\n /**\n * The type of service provided by the plugin, or `null`.\n */\n readonly provides: Token<any> | null;\n\n /**\n * The function which activates the plugin.\n */\n readonly activate: (app: T, ...args: any[]) => any;\n\n /**\n * The optional function which deactivates the plugin.\n */\n readonly deactivate:\n | ((app: T, ...args: any[]) => void | Promise<void>)\n | null;\n\n /**\n * Whether the plugin has been activated.\n */\n activated: boolean;\n\n /**\n * The resolved service for the plugin, or `null`.\n */\n service: any | null;\n\n /**\n * The pending resolver promise, or `null`.\n */\n promise: Promise<void> | null;\n }\n\n class PluginData<T = any, U = any> implements IPluginData<T> {\n private _activated = false;\n private _promise: Promise<void> | null = null;\n private _service: U | null = null;\n\n constructor(plugin: IPlugin<T, U>) {\n this.id = plugin.id;\n this.description = plugin.description ?? '';\n this.activate = plugin.activate;\n this.deactivate = plugin.deactivate ?? null;\n this.provides = plugin.provides ?? null;\n this.autoStart = plugin.autoStart ?? false;\n this.requires = plugin.requires ? plugin.requires.slice() : [];\n this.optional = plugin.optional ? plugin.optional.slice() : [];\n }\n\n /**\n * The human readable ID of the plugin.\n */\n readonly id: string;\n\n /**\n * The description of the plugin.\n */\n readonly description: string;\n\n /**\n * Whether the plugin should be activated on application start or waiting for being\n * required. If the value is 'defer' then the plugin should be activated only after\n * the application is started.\n */\n readonly autoStart: boolean | 'defer';\n\n /**\n * The types of required services for the plugin, or `[]`.\n */\n readonly requires: Token<any>[];\n\n /**\n * The types of optional services for the the plugin, or `[]`.\n */\n readonly optional: Token<any>[];\n\n /**\n * The type of service provided by the plugin, or `null`.\n */\n readonly provides: Token<any> | null;\n\n /**\n * The function which activates the plugin.\n */\n readonly activate: (app: T, ...args: any[]) => any;\n\n /**\n * The optional function which deactivates the plugin.\n */\n readonly deactivate:\n | ((app: T, ...args: any[]) => void | Promise<void>)\n | null;\n\n /**\n * Whether the plugin has been activated.\n */\n get activated(): boolean {\n return this._activated;\n }\n set activated(a: boolean) {\n this._activated = a;\n }\n\n /**\n * The resolved service for the plugin, or `null`.\n */\n get service(): U | null {\n return this._service;\n }\n set service(s: U | null) {\n this._service = s;\n }\n\n /**\n * The pending resolver promise, or `null`.\n */\n get promise(): Promise<void> | null {\n return this._promise;\n }\n set promise(p: Promise<void> | null) {\n this._promise = p;\n }\n }\n\n /**\n * Create a normalized plugin data object for the given plugin.\n */\n export function createPluginData<T>(\n plugin: IPlugin<any, any>\n ): IPluginData<T> {\n return new PluginData(plugin);\n }\n\n /**\n * Ensure no cycle is present in the plugin resolution graph.\n *\n * If a cycle is detected, an error will be thrown.\n */\n export function ensureNoCycle(\n plugin: IPluginData,\n plugins: Map<string, IPluginData>,\n services: Map<Token<any>, string>\n ): void {\n const dependencies = [...plugin.requires, ...plugin.optional];\n const visit = (token: Token<any>): boolean => {\n if (token === plugin.provides) {\n return true;\n }\n const id = services.get(token);\n if (!id) {\n return false;\n }\n const visited = plugins.get(id)!;\n const dependencies = [...visited.requires, ...visited.optional];\n if (dependencies.length === 0) {\n return false;\n }\n trace.push(id);\n if (dependencies.some(visit)) {\n return true;\n }\n trace.pop();\n return false;\n };\n\n // Bail early if there cannot be a cycle.\n if (!plugin.provides || dependencies.length === 0) {\n return;\n }\n\n // Setup a stack to trace service resolution.\n const trace = [plugin.id];\n\n // Throw an exception if a cycle is present.\n if (dependencies.some(visit)) {\n throw new ReferenceError(`Cycle detected: ${trace.join(' -> ')}.`);\n }\n }\n\n /**\n * Find dependents in deactivation order.\n *\n * @param id - The ID of the plugin of interest.\n *\n * @param plugins - The map containing all plugins.\n *\n * @param services - The map containing all services.\n *\n * @returns A list of dependent plugin IDs in order of deactivation\n *\n * #### Notes\n * The final item of the returned list is always the plugin of interest.\n */\n export function findDependents(\n id: string,\n plugins: Map<string, IPluginData>,\n services: Map<Token<any>, string>\n ): string[] {\n const edges = new Array<[string, string]>();\n const add = (id: string): void => {\n const plugin = plugins.get(id)!;\n // FIXME In the case of missing optional dependencies, we may consider\n // deactivating and reactivating the plugin without the missing service.\n const dependencies = [...plugin.requires, ...plugin.optional];\n edges.push(\n ...dependencies.reduce<[string, string][]>((acc, dep) => {\n const service = services.get(dep);\n if (service) {\n // An edge is oriented from dependent to provider.\n acc.push([id, service]);\n }\n return acc;\n }, [])\n );\n };\n\n for (const id of plugins.keys()) {\n add(id);\n }\n\n // Filter edges\n // - Get all packages that dependent on the package to be deactivated\n const newEdges = edges.filter(edge => edge[1] === id);\n let oldSize = 0;\n while (newEdges.length > oldSize) {\n const previousSize = newEdges.length;\n // Get all packages that dependent on packages that will be deactivated\n const packagesOfInterest = new Set(newEdges.map(edge => edge[0]));\n for (const poi of packagesOfInterest) {\n edges\n .filter(edge => edge[1] === poi)\n .forEach(edge => {\n // We check it is not already included to deal with circular dependencies\n if (!newEdges.includes(edge)) {\n newEdges.push(edge);\n }\n });\n }\n oldSize = previousSize;\n }\n\n const sorted = topologicSort(newEdges);\n const index = sorted.findIndex(candidate => candidate === id);\n\n if (index === -1) {\n return [id];\n }\n\n return sorted.slice(0, index + 1);\n }\n\n /**\n * Collect the IDs of the plugins to activate on startup.\n */\n export function collectStartupPlugins(\n plugins: Map<string, IPluginData>,\n options: PluginRegistry.IStartOptions\n ): string[] {\n // Create a set to hold the plugin IDs.\n const collection = new Set<string>();\n\n // Collect the auto-start (non deferred) plugins.\n for (const id of plugins.keys()) {\n if (plugins.get(id)!.autoStart === true) {\n collection.add(id);\n }\n }\n\n // Add the startup plugins.\n if (options.startPlugins) {\n for (const id of options.startPlugins) {\n collection.add(id);\n }\n }\n\n // Remove the ignored plugins.\n if (options.ignorePlugins) {\n for (const id of options.ignorePlugins) {\n collection.delete(id);\n }\n }\n\n // Return the collected startup plugins.\n return Array.from(collection);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * A class which wraps a promise into a delegate object.\n *\n * #### Notes\n * This class is useful when the logic to resolve or reject a promise\n * cannot be defined at the point where the promise is created.\n */\nexport class PromiseDelegate<T> {\n /**\n * Construct a new promise delegate.\n */\n constructor() {\n this.promise = new Promise<T>((resolve, reject) => {\n this._resolve = resolve;\n this._reject = reject;\n });\n }\n\n /**\n * The promise wrapped by the delegate.\n */\n readonly promise: Promise<T>;\n\n /**\n * Resolve the wrapped promise with the given value.\n *\n * @param value - The value to use for resolving the promise.\n */\n resolve(value: T | PromiseLike<T>): void {\n let resolve = this._resolve;\n resolve(value);\n }\n\n /**\n * Reject the wrapped promise with the given value.\n *\n * @reason - The reason for rejecting the promise.\n */\n reject(reason: unknown): void {\n let reject = this._reject;\n reject(reason);\n }\n\n private _resolve: (value: T | PromiseLike<T>) => void;\n private _reject: (reason: any) => void;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * A runtime object which captures compile-time type information.\n *\n * #### Notes\n * A token captures the compile-time type of an interface or class in\n * an object which can be used at runtime in a type-safe fashion.\n */\nexport class Token<T> {\n /**\n * Construct a new token.\n *\n * @param name - A human readable name for the token.\n * @param description - Token purpose description for documentation.\n */\n constructor(name: string, description?: string) {\n this.name = name;\n this.description = description ?? '';\n this._tokenStructuralPropertyT = null!;\n }\n\n /**\n * Token purpose description.\n */\n readonly description?: string; // FIXME remove `?` for the next major version\n\n /**\n * The human readable name for the token.\n *\n * #### Notes\n * This can be useful for debugging and logging.\n */\n readonly name: string;\n\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n private _tokenStructuralPropertyT: T;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n// Fallback\nexport function fallbackRandomValues(buffer: Uint8Array): void {\n let value = 0;\n for (let i = 0, n = buffer.length; i < n; ++i) {\n if (i % 4 === 0) {\n value = (Math.random() * 0xffffffff) >>> 0;\n }\n buffer[i] = value & 0xff;\n value >>>= 8;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\nimport { fallbackRandomValues } from './random';\n\n// Declare ambient variables for `window` and `require` to avoid a\n// hard dependency on both. This package must run on node.\ndeclare let window: any;\n\n/**\n * The namespace for random number related functionality.\n */\nexport namespace Random {\n /**\n * A function which generates random bytes.\n *\n * @param buffer - The `Uint8Array` to fill with random bytes.\n *\n * #### Notes\n * A cryptographically strong random number generator will be used if\n * available. Otherwise, `Math.random` will be used as a fallback for\n * randomness.\n *\n * The following RNGs are supported, listed in order of precedence:\n * - `window.crypto.getRandomValues`\n * - `window.msCrypto.getRandomValues`\n * - `require('crypto').randomFillSync\n * - `require('crypto').randomBytes\n * - `Math.random`\n */\n export const getRandomValues = (() => {\n // Look up the crypto module if available.\n const crypto: any =\n (typeof window !== 'undefined' && (window.crypto || window.msCrypto)) ||\n null;\n\n // Modern browsers and IE 11\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return function getRandomValues(buffer: Uint8Array): void {\n return crypto.getRandomValues(buffer);\n };\n }\n\n // Fallback\n return fallbackRandomValues;\n })();\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * A function which creates a function that generates UUID v4 identifiers.\n *\n * @returns A new function that creates a UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\nexport function uuid4Factory(\n getRandomValues: (bytes: Uint8Array) => void\n): () => string {\n // Create a 16 byte array to hold the random values.\n const bytes = new Uint8Array(16);\n\n // Create a look up table from bytes to hex strings.\n const lut = new Array<string>(256);\n\n // Pad the single character hex digits with a leading zero.\n for (let i = 0; i < 16; ++i) {\n lut[i] = '0' + i.toString(16);\n }\n\n // Populate the rest of the hex digits.\n for (let i = 16; i < 256; ++i) {\n lut[i] = i.toString(16);\n }\n\n // Return a function which generates the UUID.\n return function uuid4(): string {\n // Get a new batch of random values.\n getRandomValues(bytes);\n\n // Set the UUID version number to 4.\n bytes[6] = 0x40 | (bytes[6] & 0x0f);\n\n // Set the clock sequence bit to the RFC spec.\n bytes[8] = 0x80 | (bytes[8] & 0x3f);\n\n // Assemble the UUID string.\n return (\n lut[bytes[0]] +\n lut[bytes[1]] +\n lut[bytes[2]] +\n lut[bytes[3]] +\n '-' +\n lut[bytes[4]] +\n lut[bytes[5]] +\n '-' +\n lut[bytes[6]] +\n lut[bytes[7]] +\n '-' +\n lut[bytes[8]] +\n lut[bytes[9]] +\n '-' +\n lut[bytes[10]] +\n lut[bytes[11]] +\n lut[bytes[12]] +\n lut[bytes[13]] +\n lut[bytes[14]] +\n lut[bytes[15]]\n );\n };\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\nimport { Random } from './random.browser';\nimport { uuid4Factory } from './uuid';\n\n/**\n * The namespace for UUID related functionality.\n */\nexport namespace UUID {\n /**\n * A function which generates UUID v4 identifiers.\n *\n * @returns A new UUID v4 string.\n *\n * #### Notes\n * This implementation complies with RFC 4122.\n *\n * This uses `Random.getRandomValues()` for random bytes, which in\n * turn will use the underlying `crypto` module of the platform if\n * it is available. The fallback for randomness is `Math.random`.\n */\n export const uuid4 = uuid4Factory(Random.getRandomValues);\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module signaling\n */\nimport { ArrayExt, find } from '@lumino/algorithm';\nimport { PromiseDelegate } from '@lumino/coreutils';\n\n/**\n * A type alias for a slot function.\n *\n * @param sender - The object emitting the signal.\n *\n * @param args - The args object emitted with the signal.\n *\n * #### Notes\n * A slot is invoked when a signal to which it is connected is emitted.\n */\nexport type Slot<T, U> = (sender: T, args: U) => void;\n\n/**\n * An object used for type-safe inter-object communication.\n *\n * #### Notes\n * Signals provide a type-safe implementation of the publish-subscribe\n * pattern. An object (publisher) declares which signals it will emit,\n * and consumers connect callbacks (subscribers) to those signals. The\n * subscribers are invoked whenever the publisher emits the signal.\n */\nexport interface ISignal<T, U> {\n /**\n * Connect a slot to the signal.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n *\n * #### Notes\n * Slots are invoked in the order in which they are connected.\n *\n * Signal connections are unique. If a connection already exists for\n * the given `slot` and `thisArg`, this method returns `false`.\n *\n * A newly connected slot will not be invoked until the next time the\n * signal is emitted, even if the slot is connected while the signal\n * is dispatching.\n */\n connect(slot: Slot<T, U>, thisArg?: any): boolean;\n\n /**\n * Disconnect a slot from the signal.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n *\n * #### Notes\n * If no connection exists for the given `slot` and `thisArg`, this\n * method returns `false`.\n *\n * A disconnected slot will no longer be invoked, even if the slot\n * is disconnected while the signal is dispatching.\n */\n disconnect(slot: Slot<T, U>, thisArg?: any): boolean;\n}\n\n/**\n * An object that is both a signal and an async iterable.\n */\nexport interface IStream<T, U> extends ISignal<T, U>, AsyncIterable<U> {}\n\n/**\n * A concrete implementation of `ISignal`.\n *\n * #### Example\n * ```typescript\n * import { ISignal, Signal } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get valueChanged: ISignal<this, number> {\n * return this._valueChanged;\n * }\n *\n * get value(): number {\n * return this._value;\n * }\n *\n * set value(value: number) {\n * if (value === this._value) {\n * return;\n * }\n * this._value = value;\n * this._valueChanged.emit(value);\n * }\n *\n * private _value = 0;\n * private _valueChanged = new Signal<this, number>(this);\n * }\n *\n * function logger(sender: SomeClass, value: number): void {\n * console.log(sender.name, value);\n * }\n *\n * let m1 = new SomeClass('foo');\n * let m2 = new SomeClass('bar');\n *\n * m1.valueChanged.connect(logger);\n * m2.valueChanged.connect(logger);\n *\n * m1.value = 42; // logs: foo 42\n * m2.value = 17; // logs: bar 17\n * ```\n */\nexport class Signal<T, U> implements ISignal<T, U> {\n /**\n * Construct a new signal.\n *\n * @param sender - The sender which owns the signal.\n */\n constructor(sender: T) {\n this.sender = sender;\n }\n\n /**\n * The sender which owns the signal.\n */\n readonly sender: T;\n\n /**\n * Connect a slot to the signal.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n connect(slot: Slot<T, U>, thisArg?: unknown): boolean {\n return Private.connect(this, slot, thisArg);\n }\n\n /**\n * Disconnect a slot from the signal.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n disconnect(slot: Slot<T, U>, thisArg?: unknown): boolean {\n return Private.disconnect(this, slot, thisArg);\n }\n\n /**\n * Emit the signal and invoke the connected slots.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n emit(args: U): void {\n Private.emit(this, args);\n }\n}\n\n/**\n * The namespace for the `Signal` class statics.\n */\nexport namespace Signal {\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n export function disconnectBetween(sender: unknown, receiver: unknown): void {\n Private.disconnectBetween(sender, receiver);\n }\n\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n export function disconnectSender(sender: unknown): void {\n Private.disconnectSender(sender);\n }\n\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n export function disconnectReceiver(receiver: unknown): void {\n Private.disconnectReceiver(receiver);\n }\n\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n *\n * #### Notes\n * If a `thisArg` is provided when connecting a signal, that object\n * is considered the receiver. Otherwise, the `slot` is considered\n * the receiver.\n */\n export function disconnectAll(object: unknown): void {\n Private.disconnectAll(object);\n }\n\n /**\n * Clear all signal data associated with the given object.\n *\n * @param object - The object for which the data should be cleared.\n *\n * #### Notes\n * This removes all signal connections and any other signal data\n * associated with the object.\n */\n export function clearData(object: unknown): void {\n Private.disconnectAll(object);\n }\n\n /**\n * A type alias for the exception handler function.\n */\n export type ExceptionHandler = (err: Error) => void;\n\n /**\n * Get the signal exception handler.\n *\n * @returns The current exception handler.\n *\n * #### Notes\n * The default exception handler is `console.error`.\n */\n export function getExceptionHandler(): ExceptionHandler {\n return Private.exceptionHandler;\n }\n\n /**\n * Set the signal exception handler.\n *\n * @param handler - The function to use as the exception handler.\n *\n * @returns The old exception handler.\n *\n * #### Notes\n * The exception handler is invoked when a slot throws an exception.\n */\n export function setExceptionHandler(\n handler: ExceptionHandler\n ): ExceptionHandler {\n let old = Private.exceptionHandler;\n Private.exceptionHandler = handler;\n return old;\n }\n}\n\n/**\n * A concrete implementation of `IStream`.\n *\n * #### Example\n * ```typescript\n * import { IStream, Stream } from '@lumino/signaling';\n *\n * class SomeClass {\n *\n * constructor(name: string) {\n * this.name = name;\n * }\n *\n * readonly name: string;\n *\n * get pings(): IStream<this, string> {\n * return this._pings;\n * }\n *\n * ping(value: string) {\n * this._pings.emit(value);\n * }\n *\n * private _pings = new Stream<this, string>(this);\n * }\n *\n * let m1 = new SomeClass('foo');\n *\n * m1.pings.connect((_, value: string) => {\n * console.log('connect', value);\n * });\n *\n * void (async () => {\n * for await (const ping of m1.pings) {\n * console.log('iterator', ping);\n * }\n * })();\n *\n * m1.ping('alpha'); // logs: connect alpha\n * // logs: iterator alpha\n * m1.ping('beta'); // logs: connect beta\n * // logs: iterator beta\n * ```\n */\nexport class Stream<T, U> extends Signal<T, U> implements IStream<T, U> {\n /**\n * Return an async iterator that yields every emission.\n */\n async *[Symbol.asyncIterator](): AsyncIterableIterator<U> {\n let pending = this._pending;\n while (true) {\n try {\n const { args, next } = await pending.promise;\n pending = next;\n yield args;\n } catch (_) {\n return; // Any promise rejection stops the iterator.\n }\n }\n }\n\n /**\n * Emit the signal, invoke the connected slots, and yield the emission.\n *\n * @param args - The args to pass to the connected slots.\n */\n emit(args: U): void {\n const pending = this._pending;\n const next = (this._pending = new PromiseDelegate());\n pending.resolve({ args, next });\n super.emit(args);\n }\n\n /**\n * Stop the stream's async iteration.\n */\n stop(): void {\n this._pending.promise.catch(() => undefined);\n this._pending.reject('stop');\n this._pending = new PromiseDelegate();\n }\n\n private _pending: Private.Pending<U> = new PromiseDelegate();\n}\n\n/**\n * The namespace for the module implementation details.\n */\nnamespace Private {\n /**\n * A pending promise in a promise chain underlying a stream.\n */\n export type Pending<U> = PromiseDelegate<{ args: U; next: Pending<U> }>;\n\n /**\n * The signal exception handler function.\n */\n export let exceptionHandler: Signal.ExceptionHandler = (err: Error) => {\n console.error(err);\n };\n\n /**\n * Connect a slot to a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to invoke when the signal is emitted.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection succeeds, `false` otherwise.\n */\n export function connect<T, U>(\n signal: Signal<T, U>,\n slot: Slot<T, U>,\n thisArg?: unknown\n ): boolean {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n\n // Ensure the sender's array of receivers is created.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers) {\n receivers = [];\n receiversForSender.set(signal.sender, receivers);\n }\n\n // Bail if a matching connection already exists.\n if (findConnection(receivers, signal, slot, thisArg)) {\n return false;\n }\n\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n\n // Ensure the receiver's array of senders is created.\n let senders = sendersForReceiver.get(receiver);\n if (!senders) {\n senders = [];\n sendersForReceiver.set(receiver, senders);\n }\n\n // Create a new connection and add it to the end of each array.\n let connection = { signal, slot, thisArg };\n receivers.push(connection);\n senders.push(connection);\n\n // Indicate a successful connection.\n return true;\n }\n\n /**\n * Disconnect a slot from a signal.\n *\n * @param signal - The signal of interest.\n *\n * @param slot - The slot to disconnect from the signal.\n *\n * @param thisArg - The `this` context for the slot. If provided,\n * this must be a non-primitive object.\n *\n * @returns `true` if the connection is removed, `false` otherwise.\n */\n export function disconnect<T, U>(\n signal: Signal<T, U>,\n slot: Slot<T, U>,\n thisArg?: unknown\n ): boolean {\n // Coerce a `null` `thisArg` to `undefined`.\n thisArg = thisArg || undefined;\n\n // Lookup the list of receivers, and bail if none exist.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return false;\n }\n\n // Bail if no matching connection exits.\n let connection = findConnection(receivers, signal, slot, thisArg);\n if (!connection) {\n return false;\n }\n\n // Choose the best object for the receiver.\n let receiver = thisArg || slot;\n\n // Lookup the array of senders, which is now known to exist.\n let senders = sendersForReceiver.get(receiver)!;\n\n // Clear the connection and schedule cleanup of the arrays.\n connection.signal = null;\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n\n // Indicate a successful disconnection.\n return true;\n }\n\n /**\n * Remove all connections between a sender and receiver.\n *\n * @param sender - The sender object of interest.\n *\n * @param receiver - The receiver object of interest.\n */\n export function disconnectBetween(sender: unknown, receiver: unknown): void {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n\n // Clear each connection between the sender and receiver.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n\n // Clear the connection if it matches the sender.\n if (connection.signal.sender === sender) {\n connection.signal = null;\n }\n }\n\n // Schedule a cleanup of the senders and receivers.\n scheduleCleanup(receivers);\n scheduleCleanup(senders);\n }\n\n /**\n * Remove all connections where the given object is the sender.\n *\n * @param sender - The sender object of interest.\n */\n export function disconnectSender(sender: unknown): void {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n\n // Clear each receiver connection.\n for (const connection of receivers) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n\n // Choose the best object for the receiver.\n let receiver = connection.thisArg || connection.slot;\n\n // Clear the connection.\n connection.signal = null;\n\n // Cleanup the array of senders, which is now known to exist.\n scheduleCleanup(sendersForReceiver.get(receiver)!);\n }\n\n // Schedule a cleanup of the receivers.\n scheduleCleanup(receivers);\n }\n\n /**\n * Remove all connections where the given object is the receiver.\n *\n * @param receiver - The receiver object of interest.\n */\n export function disconnectReceiver(receiver: unknown): void {\n // If there are no senders, there is nothing to do.\n let senders = sendersForReceiver.get(receiver);\n if (!senders || senders.length === 0) {\n return;\n }\n\n // Clear each sender connection.\n for (const connection of senders) {\n // Skip connections which have already been cleared.\n if (!connection.signal) {\n continue;\n }\n\n // Lookup the sender for the connection.\n let sender = connection.signal.sender;\n\n // Clear the connection.\n connection.signal = null;\n\n // Cleanup the array of receivers, which is now known to exist.\n scheduleCleanup(receiversForSender.get(sender)!);\n }\n\n // Schedule a cleanup of the list of senders.\n scheduleCleanup(senders);\n }\n\n /**\n * Remove all connections where an object is the sender or receiver.\n *\n * @param object - The object of interest.\n */\n export function disconnectAll(object: unknown): void {\n // Remove all connections where the given object is the sender.\n disconnectSender(object);\n // Remove all connections where the given object is the receiver.\n disconnectReceiver(object);\n }\n\n /**\n * Emit a signal and invoke its connected slots.\n *\n * @param signal - The signal of interest.\n *\n * @param args - The args to pass to the connected slots.\n *\n * #### Notes\n * Slots are invoked synchronously in connection order.\n *\n * Exceptions thrown by connected slots will be caught and logged.\n */\n export function emit<T, U>(signal: Signal<T, U>, args: U): void {\n // If there are no receivers, there is nothing to do.\n let receivers = receiversForSender.get(signal.sender);\n if (!receivers || receivers.length === 0) {\n return;\n }\n\n // Invoke the slots for connections with a matching signal.\n // Any connections added during emission are not invoked.\n for (let i = 0, n = receivers.length; i < n; ++i) {\n let connection = receivers[i];\n if (connection.signal === signal) {\n invokeSlot(connection, args);\n }\n }\n }\n\n /**\n * An object which holds connection data.\n */\n interface IConnection {\n /**\n * The signal for the connection.\n *\n * A `null` signal indicates a cleared connection.\n */\n signal: Signal<any, any> | null;\n\n /**\n * The slot connected to the signal.\n */\n readonly slot: Slot<any, any>;\n\n /**\n * The `this` context for the slot.\n */\n readonly thisArg: any;\n }\n\n /**\n * A weak mapping of sender to array of receiver connections.\n */\n const receiversForSender = new WeakMap<any, IConnection[]>();\n\n /**\n * A weak mapping of receiver to array of sender connections.\n */\n const sendersForReceiver = new WeakMap<any, IConnection[]>();\n\n /**\n * A set of connection arrays which are pending cleanup.\n */\n const dirtySet = new Set<IConnection[]>();\n\n /**\n * A function to schedule an event loop callback.\n */\n const schedule = (() => {\n let ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n\n /**\n * Find a connection which matches the given parameters.\n */\n function findConnection(\n connections: IConnection[],\n signal: Signal<any, any>,\n slot: Slot<any, any>,\n thisArg: any\n ): IConnection | undefined {\n return find(\n connections,\n connection =>\n connection.signal === signal &&\n connection.slot === slot &&\n connection.thisArg === thisArg\n );\n }\n\n /**\n * Invoke a slot with the given parameters.\n *\n * The connection is assumed to be valid.\n *\n * Exceptions in the slot will be caught and logged.\n */\n function invokeSlot(connection: IConnection, args: any): void {\n let { signal, slot, thisArg } = connection;\n try {\n slot.call(thisArg, signal!.sender, args);\n } catch (err) {\n exceptionHandler(err);\n }\n }\n\n /**\n * Schedule a cleanup of a connection array.\n *\n * This will add the array to the dirty set and schedule a deferred\n * cleanup of the array contents. On cleanup, any connection with a\n * `null` signal will be removed from the array.\n */\n function scheduleCleanup(array: IConnection[]): void {\n if (dirtySet.size === 0) {\n schedule(cleanupDirtySet);\n }\n dirtySet.add(array);\n }\n\n /**\n * Cleanup the connection lists in the dirty set.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupDirtySet(): void {\n dirtySet.forEach(cleanupConnections);\n dirtySet.clear();\n }\n\n /**\n * Cleanup the dirty connections in a connections array.\n *\n * This will remove any connection with a `null` signal.\n *\n * This function should only be invoked asynchronously, when the\n * stack frame is guaranteed to not be on the path of user code.\n */\n function cleanupConnections(connections: IConnection[]): void {\n ArrayExt.removeAllWhere(connections, isDeadConnection);\n }\n\n /**\n * Test whether a connection is dead.\n *\n * A dead connection has a `null` signal.\n */\n function isDeadConnection(connection: IConnection): boolean {\n return connection.signal === null;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { IDisposable } from '@lumino/disposable';\nimport { ISignal, Signal } from '@lumino/signaling';\n\n/**\n * A class that monitors activity on a signal.\n */\nexport class ActivityMonitor<Sender, Args> implements IDisposable {\n /**\n * Construct a new activity monitor.\n */\n constructor(options: ActivityMonitor.IOptions<Sender, Args>) {\n options.signal.connect(this._onSignalFired, this);\n this._timeout = options.timeout || 1000;\n }\n\n /**\n * A signal emitted when activity has ceased.\n */\n get activityStopped(): ISignal<\n this,\n ActivityMonitor.IArguments<Sender, Args>\n > {\n return this._activityStopped;\n }\n\n /**\n * The timeout associated with the monitor, in milliseconds.\n */\n get timeout(): number {\n return this._timeout;\n }\n set timeout(value: number) {\n this._timeout = value;\n }\n\n /**\n * Test whether the monitor has been disposed.\n *\n * #### Notes\n * This is a read-only property.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * Dispose of the resources used by the activity monitor.\n */\n dispose(): void {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n Signal.clearData(this);\n }\n\n /**\n * A signal handler for the monitored signal.\n */\n private _onSignalFired(sender: Sender, args: Args): void {\n clearTimeout(this._timer);\n this._sender = sender;\n this._args = args;\n this._timer = setTimeout(() => {\n this._activityStopped.emit({\n sender: this._sender,\n args: this._args\n });\n }, this._timeout);\n }\n\n private _timer: any = -1;\n private _timeout = -1;\n private _sender: Sender;\n private _args: Args;\n private _isDisposed = false;\n private _activityStopped = new Signal<\n this,\n ActivityMonitor.IArguments<Sender, Args>\n >(this);\n}\n\n/**\n * The namespace for `ActivityMonitor` statics.\n */\nexport namespace ActivityMonitor {\n /**\n * The options used to construct a new `ActivityMonitor`.\n */\n export interface IOptions<Sender, Args> {\n /**\n * The signal to monitor.\n */\n signal: ISignal<Sender, Args>;\n\n /**\n * The activity timeout in milliseconds.\n *\n * The default is 1 second.\n */\n timeout?: number;\n }\n\n /**\n * The argument object for an activity timeout.\n *\n */\n export interface IArguments<Sender, Args> {\n /**\n * The most recent sender object.\n */\n sender: Sender;\n\n /**\n * The most recent argument object.\n */\n args: Args;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nconst DEFAULT_MAX_SIZE = 128;\n\n/** A least-recently-used cache. */\nexport class LruCache<T, U> {\n protected _map = new Map<T, U>();\n protected _maxSize: number;\n\n constructor(options: LruCache.IOptions = {}) {\n this._maxSize = options?.maxSize || DEFAULT_MAX_SIZE;\n }\n\n /**\n * Return the current size of the cache.\n */\n get size() {\n return this._map.size;\n }\n\n /**\n * Clear the values in the cache.\n */\n clear() {\n this._map.clear();\n }\n\n /**\n * Get a value (or null) from the cache, pushing the item to the front of the cache.\n */\n get(key: T): U | null {\n const item = this._map.get(key) || null;\n if (item != null) {\n this._map.delete(key);\n this._map.set(key, item);\n }\n return item;\n }\n\n /**\n * Set a value in the cache, potentially evicting an old item.\n */\n set(key: T, value: U): void {\n if (this._map.size >= this._maxSize) {\n this._map.delete(this._map.keys().next().value);\n }\n this._map.set(key, value);\n }\n}\n\nexport namespace LruCache {\n export interface IOptions {\n maxSize?: number | null;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n/**\n * The namespace for code block functions which help\n * in extract code from markdown text\n */\nexport namespace MarkdownCodeBlocks {\n export const CODE_BLOCK_MARKER = '```';\n const markdownExtensions: string[] = [\n '.markdown',\n '.mdown',\n '.mkdn',\n '.md',\n '.mkd',\n '.mdwn',\n '.mdtxt',\n '.mdtext',\n '.text',\n '.txt',\n '.Rmd'\n ];\n\n export class MarkdownCodeBlock {\n startLine: number;\n endLine: number;\n code: string;\n constructor(startLine: number) {\n this.startLine = startLine;\n this.code = '';\n this.endLine = -1;\n }\n }\n\n /**\n * Check whether the given file extension is a markdown extension\n * @param extension - A file extension\n *\n * @returns true/false depending on whether this is a supported markdown extension\n */\n export function isMarkdown(extension: string): boolean {\n return markdownExtensions.indexOf(extension) > -1;\n }\n\n /**\n * Construct all code snippets from current text\n * (this could be potentially optimized if we can cache and detect differences)\n * @param text - A string to parse codeblocks from\n *\n * @returns An array of MarkdownCodeBlocks.\n */\n export function findMarkdownCodeBlocks(text: string): MarkdownCodeBlock[] {\n if (!text || text === '') {\n return [];\n }\n\n const lines = text.split('\\n');\n const codeBlocks: MarkdownCodeBlock[] = [];\n let currentBlock = null;\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n const lineContainsMarker = line.indexOf(CODE_BLOCK_MARKER) === 0;\n const constructingBlock = currentBlock != null;\n // Skip this line if it is not part of any code block and doesn't contain a marker.\n if (!lineContainsMarker && !constructingBlock) {\n continue;\n }\n\n // Check if we are already constructing a code block.\n if (!constructingBlock) {\n // Start constructing a new code block.\n currentBlock = new MarkdownCodeBlock(lineIndex);\n\n // Check whether this is a single line code block of the form ```a = 10```.\n const firstIndex = line.indexOf(CODE_BLOCK_MARKER);\n const lastIndex = line.lastIndexOf(CODE_BLOCK_MARKER);\n const isSingleLine = firstIndex !== lastIndex;\n if (isSingleLine) {\n currentBlock.code = line.substring(\n firstIndex + CODE_BLOCK_MARKER.length,\n lastIndex\n );\n currentBlock.endLine = lineIndex;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n }\n } else if (currentBlock) {\n if (lineContainsMarker) {\n // End of block, finish it up.\n currentBlock.endLine = lineIndex - 1;\n codeBlocks.push(currentBlock);\n currentBlock = null;\n } else {\n // Append the current line.\n currentBlock.code += line + '\\n';\n }\n }\n }\n return codeBlocks;\n }\n}\n", "'use strict';\n\nfunction hasKey(obj, keys) {\n\tvar o = obj;\n\tkeys.slice(0, -1).forEach(function (key) {\n\t\to = o[key] || {};\n\t});\n\n\tvar key = keys[keys.length - 1];\n\treturn key in o;\n}\n\nfunction isNumber(x) {\n\tif (typeof x === 'number') { return true; }\n\tif ((/^0x[0-9a-f]+$/i).test(x)) { return true; }\n\treturn (/^[-+]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(e[-+]?\\d+)?$/).test(x);\n}\n\nfunction isConstructorOrProto(obj, key) {\n\treturn (key === 'constructor' && typeof obj[key] === 'function') || key === '__proto__';\n}\n\nmodule.exports = function (args, opts) {\n\tif (!opts) { opts = {}; }\n\n\tvar flags = {\n\t\tbools: {},\n\t\tstrings: {},\n\t\tunknownFn: null,\n\t};\n\n\tif (typeof opts.unknown === 'function') {\n\t\tflags.unknownFn = opts.unknown;\n\t}\n\n\tif (typeof opts.boolean === 'boolean' && opts.boolean) {\n\t\tflags.allBools = true;\n\t} else {\n\t\t[].concat(opts.boolean).filter(Boolean).forEach(function (key) {\n\t\t\tflags.bools[key] = true;\n\t\t});\n\t}\n\n\tvar aliases = {};\n\n\tfunction aliasIsBoolean(key) {\n\t\treturn aliases[key].some(function (x) {\n\t\t\treturn flags.bools[x];\n\t\t});\n\t}\n\n\tObject.keys(opts.alias || {}).forEach(function (key) {\n\t\taliases[key] = [].concat(opts.alias[key]);\n\t\taliases[key].forEach(function (x) {\n\t\t\taliases[x] = [key].concat(aliases[key].filter(function (y) {\n\t\t\t\treturn x !== y;\n\t\t\t}));\n\t\t});\n\t});\n\n\t[].concat(opts.string).filter(Boolean).forEach(function (key) {\n\t\tflags.strings[key] = true;\n\t\tif (aliases[key]) {\n\t\t\t[].concat(aliases[key]).forEach(function (k) {\n\t\t\t\tflags.strings[k] = true;\n\t\t\t});\n\t\t}\n\t});\n\n\tvar defaults = opts.default || {};\n\n\tvar argv = { _: [] };\n\n\tfunction argDefined(key, arg) {\n\t\treturn (flags.allBools && (/^--[^=]+$/).test(arg))\n\t\t\t|| flags.strings[key]\n\t\t\t|| flags.bools[key]\n\t\t\t|| aliases[key];\n\t}\n\n\tfunction setKey(obj, keys, value) {\n\t\tvar o = obj;\n\t\tfor (var i = 0; i < keys.length - 1; i++) {\n\t\t\tvar key = keys[i];\n\t\t\tif (isConstructorOrProto(o, key)) { return; }\n\t\t\tif (o[key] === undefined) { o[key] = {}; }\n\t\t\tif (\n\t\t\t\to[key] === Object.prototype\n\t\t\t\t|| o[key] === Number.prototype\n\t\t\t\t|| o[key] === String.prototype\n\t\t\t) {\n\t\t\t\to[key] = {};\n\t\t\t}\n\t\t\tif (o[key] === Array.prototype) { o[key] = []; }\n\t\t\to = o[key];\n\t\t}\n\n\t\tvar lastKey = keys[keys.length - 1];\n\t\tif (isConstructorOrProto(o, lastKey)) { return; }\n\t\tif (\n\t\t\to === Object.prototype\n\t\t\t|| o === Number.prototype\n\t\t\t|| o === String.prototype\n\t\t) {\n\t\t\to = {};\n\t\t}\n\t\tif (o === Array.prototype) { o = []; }\n\t\tif (o[lastKey] === undefined || flags.bools[lastKey] || typeof o[lastKey] === 'boolean') {\n\t\t\to[lastKey] = value;\n\t\t} else if (Array.isArray(o[lastKey])) {\n\t\t\to[lastKey].push(value);\n\t\t} else {\n\t\t\to[lastKey] = [o[lastKey], value];\n\t\t}\n\t}\n\n\tfunction setArg(key, val, arg) {\n\t\tif (arg && flags.unknownFn && !argDefined(key, arg)) {\n\t\t\tif (flags.unknownFn(arg) === false) { return; }\n\t\t}\n\n\t\tvar value = !flags.strings[key] && isNumber(val)\n\t\t\t? Number(val)\n\t\t\t: val;\n\t\tsetKey(argv, key.split('.'), value);\n\n\t\t(aliases[key] || []).forEach(function (x) {\n\t\t\tsetKey(argv, x.split('.'), value);\n\t\t});\n\t}\n\n\tObject.keys(flags.bools).forEach(function (key) {\n\t\tsetArg(key, defaults[key] === undefined ? false : defaults[key]);\n\t});\n\n\tvar notFlags = [];\n\n\tif (args.indexOf('--') !== -1) {\n\t\tnotFlags = args.slice(args.indexOf('--') + 1);\n\t\targs = args.slice(0, args.indexOf('--'));\n\t}\n\n\tfor (var i = 0; i < args.length; i++) {\n\t\tvar arg = args[i];\n\t\tvar key;\n\t\tvar next;\n\n\t\tif ((/^--.+=/).test(arg)) {\n\t\t\t// Using [\\s\\S] instead of . because js doesn't support the\n\t\t\t// 'dotall' regex modifier. See:\n\t\t\t// http://stackoverflow.com/a/1068308/13216\n\t\t\tvar m = arg.match(/^--([^=]+)=([\\s\\S]*)$/);\n\t\t\tkey = m[1];\n\t\t\tvar value = m[2];\n\t\t\tif (flags.bools[key]) {\n\t\t\t\tvalue = value !== 'false';\n\t\t\t}\n\t\t\tsetArg(key, value, arg);\n\t\t} else if ((/^--no-.+/).test(arg)) {\n\t\t\tkey = arg.match(/^--no-(.+)/)[1];\n\t\t\tsetArg(key, false, arg);\n\t\t} else if ((/^--.+/).test(arg)) {\n\t\t\tkey = arg.match(/^--(.+)/)[1];\n\t\t\tnext = args[i + 1];\n\t\t\tif (\n\t\t\t\tnext !== undefined\n\t\t\t\t&& !(/^(-|--)[^-]/).test(next)\n\t\t\t\t&& !flags.bools[key]\n\t\t\t\t&& !flags.allBools\n\t\t\t\t&& (aliases[key] ? !aliasIsBoolean(key) : true)\n\t\t\t) {\n\t\t\t\tsetArg(key, next, arg);\n\t\t\t\ti += 1;\n\t\t\t} else if ((/^(true|false)$/).test(next)) {\n\t\t\t\tsetArg(key, next === 'true', arg);\n\t\t\t\ti += 1;\n\t\t\t} else {\n\t\t\t\tsetArg(key, flags.strings[key] ? '' : true, arg);\n\t\t\t}\n\t\t} else if ((/^-[^-]+/).test(arg)) {\n\t\t\tvar letters = arg.slice(1, -1).split('');\n\n\t\t\tvar broken = false;\n\t\t\tfor (var j = 0; j < letters.length; j++) {\n\t\t\t\tnext = arg.slice(j + 2);\n\n\t\t\t\tif (next === '-') {\n\t\t\t\t\tsetArg(letters[j], next, arg);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif ((/[A-Za-z]/).test(letters[j]) && next[0] === '=') {\n\t\t\t\t\tsetArg(letters[j], next.slice(1), arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t(/[A-Za-z]/).test(letters[j])\n\t\t\t\t\t&& (/-?\\d+(\\.\\d*)?(e-?\\d+)?$/).test(next)\n\t\t\t\t) {\n\t\t\t\t\tsetArg(letters[j], next, arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tif (letters[j + 1] && letters[j + 1].match(/\\W/)) {\n\t\t\t\t\tsetArg(letters[j], arg.slice(j + 2), arg);\n\t\t\t\t\tbroken = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else {\n\t\t\t\t\tsetArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tkey = arg.slice(-1)[0];\n\t\t\tif (!broken && key !== '-') {\n\t\t\t\tif (\n\t\t\t\t\targs[i + 1]\n\t\t\t\t\t&& !(/^(-|--)[^-]/).test(args[i + 1])\n\t\t\t\t\t&& !flags.bools[key]\n\t\t\t\t\t&& (aliases[key] ? !aliasIsBoolean(key) : true)\n\t\t\t\t) {\n\t\t\t\t\tsetArg(key, args[i + 1], arg);\n\t\t\t\t\ti += 1;\n\t\t\t\t} else if (args[i + 1] && (/^(true|false)$/).test(args[i + 1])) {\n\t\t\t\t\tsetArg(key, args[i + 1] === 'true', arg);\n\t\t\t\t\ti += 1;\n\t\t\t\t} else {\n\t\t\t\t\tsetArg(key, flags.strings[key] ? '' : true, arg);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (!flags.unknownFn || flags.unknownFn(arg) !== false) {\n\t\t\t\targv._.push(flags.strings._ || !isNumber(arg) ? arg : Number(arg));\n\t\t\t}\n\t\t\tif (opts.stopEarly) {\n\t\t\t\targv._.push.apply(argv._, args.slice(i + 1));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tObject.keys(defaults).forEach(function (k) {\n\t\tif (!hasKey(argv, k.split('.'))) {\n\t\t\tsetKey(argv, k.split('.'), defaults[k]);\n\n\t\t\t(aliases[k] || []).forEach(function (x) {\n\t\t\t\tsetKey(argv, x.split('.'), defaults[k]);\n\t\t\t});\n\t\t}\n\t});\n\n\tif (opts['--']) {\n\t\targv['--'] = notFlags.slice();\n\t} else {\n\t\tnotFlags.forEach(function (k) {\n\t\t\targv._.push(k);\n\t\t});\n\t}\n\n\treturn argv;\n};\n", "// 'path' module extracted from Node.js v8.11.1 (only the posix part)\n// transplited with Babel\n\n// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nfunction assertPath(path) {\n if (typeof path !== 'string') {\n throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));\n }\n}\n\n// Resolves . and .. elements in a path with directory names\nfunction normalizeStringPosix(path, allowAboveRoot) {\n var res = '';\n var lastSegmentLength = 0;\n var lastSlash = -1;\n var dots = 0;\n var code;\n for (var i = 0; i <= path.length; ++i) {\n if (i < path.length)\n code = path.charCodeAt(i);\n else if (code === 47 /*/*/)\n break;\n else\n code = 47 /*/*/;\n if (code === 47 /*/*/) {\n if (lastSlash === i - 1 || dots === 1) {\n // NOOP\n } else if (lastSlash !== i - 1 && dots === 2) {\n if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {\n if (res.length > 2) {\n var lastSlashIndex = res.lastIndexOf('/');\n if (lastSlashIndex !== res.length - 1) {\n if (lastSlashIndex === -1) {\n res = '';\n lastSegmentLength = 0;\n } else {\n res = res.slice(0, lastSlashIndex);\n lastSegmentLength = res.length - 1 - res.lastIndexOf('/');\n }\n lastSlash = i;\n dots = 0;\n continue;\n }\n } else if (res.length === 2 || res.length === 1) {\n res = '';\n lastSegmentLength = 0;\n lastSlash = i;\n dots = 0;\n continue;\n }\n }\n if (allowAboveRoot) {\n if (res.length > 0)\n res += '/..';\n else\n res = '..';\n lastSegmentLength = 2;\n }\n } else {\n if (res.length > 0)\n res += '/' + path.slice(lastSlash + 1, i);\n else\n res = path.slice(lastSlash + 1, i);\n lastSegmentLength = i - lastSlash - 1;\n }\n lastSlash = i;\n dots = 0;\n } else if (code === 46 /*.*/ && dots !== -1) {\n ++dots;\n } else {\n dots = -1;\n }\n }\n return res;\n}\n\nfunction _format(sep, pathObject) {\n var dir = pathObject.dir || pathObject.root;\n var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');\n if (!dir) {\n return base;\n }\n if (dir === pathObject.root) {\n return dir + base;\n }\n return dir + sep + base;\n}\n\nvar posix = {\n // path.resolve([from ...], to)\n resolve: function resolve() {\n var resolvedPath = '';\n var resolvedAbsolute = false;\n var cwd;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path;\n if (i >= 0)\n path = arguments[i];\n else {\n if (cwd === undefined)\n cwd = process.cwd();\n path = cwd;\n }\n\n assertPath(path);\n\n // Skip empty entries\n if (path.length === 0) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);\n\n if (resolvedAbsolute) {\n if (resolvedPath.length > 0)\n return '/' + resolvedPath;\n else\n return '/';\n } else if (resolvedPath.length > 0) {\n return resolvedPath;\n } else {\n return '.';\n }\n },\n\n normalize: function normalize(path) {\n assertPath(path);\n\n if (path.length === 0) return '.';\n\n var isAbsolute = path.charCodeAt(0) === 47 /*/*/;\n var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;\n\n // Normalize the path\n path = normalizeStringPosix(path, !isAbsolute);\n\n if (path.length === 0 && !isAbsolute) path = '.';\n if (path.length > 0 && trailingSeparator) path += '/';\n\n if (isAbsolute) return '/' + path;\n return path;\n },\n\n isAbsolute: function isAbsolute(path) {\n assertPath(path);\n return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;\n },\n\n join: function join() {\n if (arguments.length === 0)\n return '.';\n var joined;\n for (var i = 0; i < arguments.length; ++i) {\n var arg = arguments[i];\n assertPath(arg);\n if (arg.length > 0) {\n if (joined === undefined)\n joined = arg;\n else\n joined += '/' + arg;\n }\n }\n if (joined === undefined)\n return '.';\n return posix.normalize(joined);\n },\n\n relative: function relative(from, to) {\n assertPath(from);\n assertPath(to);\n\n if (from === to) return '';\n\n from = posix.resolve(from);\n to = posix.resolve(to);\n\n if (from === to) return '';\n\n // Trim any leading backslashes\n var fromStart = 1;\n for (; fromStart < from.length; ++fromStart) {\n if (from.charCodeAt(fromStart) !== 47 /*/*/)\n break;\n }\n var fromEnd = from.length;\n var fromLen = fromEnd - fromStart;\n\n // Trim any leading backslashes\n var toStart = 1;\n for (; toStart < to.length; ++toStart) {\n if (to.charCodeAt(toStart) !== 47 /*/*/)\n break;\n }\n var toEnd = to.length;\n var toLen = toEnd - toStart;\n\n // Compare paths to find the longest common path from root\n var length = fromLen < toLen ? fromLen : toLen;\n var lastCommonSep = -1;\n var i = 0;\n for (; i <= length; ++i) {\n if (i === length) {\n if (toLen > length) {\n if (to.charCodeAt(toStart + i) === 47 /*/*/) {\n // We get here if `from` is the exact base path for `to`.\n // For example: from='/foo/bar'; to='/foo/bar/baz'\n return to.slice(toStart + i + 1);\n } else if (i === 0) {\n // We get here if `from` is the root\n // For example: from='/'; to='/foo'\n return to.slice(toStart + i);\n }\n } else if (fromLen > length) {\n if (from.charCodeAt(fromStart + i) === 47 /*/*/) {\n // We get here if `to` is the exact base path for `from`.\n // For example: from='/foo/bar/baz'; to='/foo/bar'\n lastCommonSep = i;\n } else if (i === 0) {\n // We get here if `to` is the root.\n // For example: from='/foo'; to='/'\n lastCommonSep = 0;\n }\n }\n break;\n }\n var fromCode = from.charCodeAt(fromStart + i);\n var toCode = to.charCodeAt(toStart + i);\n if (fromCode !== toCode)\n break;\n else if (fromCode === 47 /*/*/)\n lastCommonSep = i;\n }\n\n var out = '';\n // Generate the relative path based on the path difference between `to`\n // and `from`\n for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {\n if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {\n if (out.length === 0)\n out += '..';\n else\n out += '/..';\n }\n }\n\n // Lastly, append the rest of the destination (`to`) path that comes after\n // the common path parts\n if (out.length > 0)\n return out + to.slice(toStart + lastCommonSep);\n else {\n toStart += lastCommonSep;\n if (to.charCodeAt(toStart) === 47 /*/*/)\n ++toStart;\n return to.slice(toStart);\n }\n },\n\n _makeLong: function _makeLong(path) {\n return path;\n },\n\n dirname: function dirname(path) {\n assertPath(path);\n if (path.length === 0) return '.';\n var code = path.charCodeAt(0);\n var hasRoot = code === 47 /*/*/;\n var end = -1;\n var matchedSlash = true;\n for (var i = path.length - 1; i >= 1; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n if (!matchedSlash) {\n end = i;\n break;\n }\n } else {\n // We saw the first non-path separator\n matchedSlash = false;\n }\n }\n\n if (end === -1) return hasRoot ? '/' : '.';\n if (hasRoot && end === 1) return '//';\n return path.slice(0, end);\n },\n\n basename: function basename(path, ext) {\n if (ext !== undefined && typeof ext !== 'string') throw new TypeError('\"ext\" argument must be a string');\n assertPath(path);\n\n var start = 0;\n var end = -1;\n var matchedSlash = true;\n var i;\n\n if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {\n if (ext.length === path.length && ext === path) return '';\n var extIdx = ext.length - 1;\n var firstNonSlashEnd = -1;\n for (i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else {\n if (firstNonSlashEnd === -1) {\n // We saw the first non-path separator, remember this index in case\n // we need it if the extension ends up not matching\n matchedSlash = false;\n firstNonSlashEnd = i + 1;\n }\n if (extIdx >= 0) {\n // Try to match the explicit extension\n if (code === ext.charCodeAt(extIdx)) {\n if (--extIdx === -1) {\n // We matched the extension, so mark this as the end of our path\n // component\n end = i;\n }\n } else {\n // Extension does not match, so our result is the entire path\n // component\n extIdx = -1;\n end = firstNonSlashEnd;\n }\n }\n }\n }\n\n if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;\n return path.slice(start, end);\n } else {\n for (i = path.length - 1; i >= 0; --i) {\n if (path.charCodeAt(i) === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n start = i + 1;\n break;\n }\n } else if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // path component\n matchedSlash = false;\n end = i + 1;\n }\n }\n\n if (end === -1) return '';\n return path.slice(start, end);\n }\n },\n\n extname: function extname(path) {\n assertPath(path);\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n for (var i = path.length - 1; i >= 0; --i) {\n var code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1)\n startDot = i;\n else if (preDotState !== 1)\n preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n return '';\n }\n return path.slice(startDot, end);\n },\n\n format: function format(pathObject) {\n if (pathObject === null || typeof pathObject !== 'object') {\n throw new TypeError('The \"pathObject\" argument must be of type Object. Received type ' + typeof pathObject);\n }\n return _format('/', pathObject);\n },\n\n parse: function parse(path) {\n assertPath(path);\n\n var ret = { root: '', dir: '', base: '', ext: '', name: '' };\n if (path.length === 0) return ret;\n var code = path.charCodeAt(0);\n var isAbsolute = code === 47 /*/*/;\n var start;\n if (isAbsolute) {\n ret.root = '/';\n start = 1;\n } else {\n start = 0;\n }\n var startDot = -1;\n var startPart = 0;\n var end = -1;\n var matchedSlash = true;\n var i = path.length - 1;\n\n // Track the state of characters (if any) we see before our first dot and\n // after any path separator we find\n var preDotState = 0;\n\n // Get non-dir info\n for (; i >= start; --i) {\n code = path.charCodeAt(i);\n if (code === 47 /*/*/) {\n // If we reached a path separator that was not part of a set of path\n // separators at the end of the string, stop now\n if (!matchedSlash) {\n startPart = i + 1;\n break;\n }\n continue;\n }\n if (end === -1) {\n // We saw the first non-path separator, mark this as the end of our\n // extension\n matchedSlash = false;\n end = i + 1;\n }\n if (code === 46 /*.*/) {\n // If this is our first dot, mark it as the start of our extension\n if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;\n } else if (startDot !== -1) {\n // We saw a non-dot and non-path separator before our dot, so we should\n // have a good chance at having a non-empty extension\n preDotState = -1;\n }\n }\n\n if (startDot === -1 || end === -1 ||\n // We saw a non-dot character immediately before the dot\n preDotState === 0 ||\n // The (right-most) trimmed path component is exactly '..'\n preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {\n if (end !== -1) {\n if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);\n }\n } else {\n if (startPart === 0 && isAbsolute) {\n ret.name = path.slice(1, startDot);\n ret.base = path.slice(1, end);\n } else {\n ret.name = path.slice(startPart, startDot);\n ret.base = path.slice(startPart, end);\n }\n ret.ext = path.slice(startDot, end);\n }\n\n if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';\n\n return ret;\n },\n\n sep: '/',\n delimiter: ':',\n win32: null,\n posix: null\n};\n\nposix.posix = posix;\n\nmodule.exports = posix;\n", "'use strict';\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nmodule.exports = function required(port, protocol) {\n protocol = protocol.split(':')[0];\n port = +port;\n\n if (!port) return false;\n\n switch (protocol) {\n case 'http':\n case 'ws':\n return port !== 80;\n\n case 'https':\n case 'wss':\n return port !== 443;\n\n case 'ftp':\n return port !== 21;\n\n case 'gopher':\n return port !== 70;\n\n case 'file':\n return false;\n }\n\n return port !== 0;\n};\n", "'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , undef;\n\n/**\n * Decode a URI encoded string.\n *\n * @param {String} input The URI encoded string.\n * @returns {String|Null} The decoded string.\n * @api private\n */\nfunction decode(input) {\n try {\n return decodeURIComponent(input.replace(/\\+/g, ' '));\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Attempts to encode a given input.\n *\n * @param {String} input The string that needs to be encoded.\n * @returns {String|Null} The encoded string.\n * @api private\n */\nfunction encode(input) {\n try {\n return encodeURIComponent(input);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Simple query string parser.\n *\n * @param {String} query The query string that needs to be parsed.\n * @returns {Object}\n * @api public\n */\nfunction querystring(query) {\n var parser = /([^=?#&]+)=?([^&]*)/g\n , result = {}\n , part;\n\n while (part = parser.exec(query)) {\n var key = decode(part[1])\n , value = decode(part[2]);\n\n //\n // Prevent overriding of existing properties. This ensures that build-in\n // methods like `toString` or __proto__ are not overriden by malicious\n // querystrings.\n //\n // In the case if failed decoding, we want to omit the key/value pairs\n // from the result.\n //\n if (key === null || value === null || key in result) continue;\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Transform a query string to an object.\n *\n * @param {Object} obj Object that should be transformed.\n * @param {String} prefix Optional prefix.\n * @returns {String}\n * @api public\n */\nfunction querystringify(obj, prefix) {\n prefix = prefix || '';\n\n var pairs = []\n , value\n , key;\n\n //\n // Optionally prefix with a '?' if needed\n //\n if ('string' !== typeof prefix) prefix = '?';\n\n for (key in obj) {\n if (has.call(obj, key)) {\n value = obj[key];\n\n //\n // Edge cases where we actually want to encode the value to an empty\n // string instead of the stringified value.\n //\n if (!value && (value === null || value === undef || isNaN(value))) {\n value = '';\n }\n\n key = encode(key);\n value = encode(value);\n\n //\n // If we failed to encode the strings, we should bail out as we don't\n // want to add invalid strings to the query.\n //\n if (key === null || value === null) continue;\n pairs.push(key +'='+ value);\n }\n }\n\n return pairs.length ? prefix + pairs.join('&') : '';\n}\n\n//\n// Expose the module.\n//\nexports.stringify = querystringify;\nexports.parse = querystring;\n", "'use strict';\n\nvar required = require('requires-port')\n , qs = require('querystringify')\n , controlOrWhitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/\n , CRHTLF = /[\\n\\r\\t]/g\n , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//\n , port = /:\\d+$/\n , protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i\n , windowsDriveLetter = /^[a-zA-Z]:/;\n\n/**\n * Remove control characters and whitespace from the beginning of a string.\n *\n * @param {Object|String} str String to trim.\n * @returns {String} A new string representing `str` stripped of control\n * characters and whitespace from its beginning.\n * @public\n */\nfunction trimLeft(str) {\n return (str ? str : '').toString().replace(controlOrWhitespace, '');\n}\n\n/**\n * These are the parse rules for the URL parser, it informs the parser\n * about:\n *\n * 0. The char it Needs to parse, if it's a string it should be done using\n * indexOf, RegExp using exec and NaN means set as current value.\n * 1. The property we should set when parsing this value.\n * 2. Indication if it's backwards or forward parsing, when set as number it's\n * the value of extra chars that should be split off.\n * 3. Inherit from location if non existing in the parser.\n * 4. `toLowerCase` the resulting value.\n */\nvar rules = [\n ['#', 'hash'], // Extract from the back.\n ['?', 'query'], // Extract from the back.\n function sanitize(address, url) { // Sanitize what is left of the address\n return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n },\n ['/', 'pathname'], // Extract from the back.\n ['@', 'auth', 1], // Extract from the front.\n [NaN, 'host', undefined, 1, 1], // Set left over value.\n [/:(\\d*)$/, 'port', undefined, 1], // RegExp the back.\n [NaN, 'hostname', undefined, 1, 1] // Set left over.\n];\n\n/**\n * These properties should not be copied or inherited from. This is only needed\n * for all non blob URL's as a blob URL does not include a hash, only the\n * origin.\n *\n * @type {Object}\n * @private\n */\nvar ignore = { hash: 1, query: 1 };\n\n/**\n * The location object differs when your code is loaded through a normal page,\n * Worker or through a worker using a blob. And with the blobble begins the\n * trouble as the location object will contain the URL of the blob, not the\n * location of the page where our code is loaded in. The actual origin is\n * encoded in the `pathname` so we can thankfully generate a good \"default\"\n * location from it so we can generate proper relative URL's again.\n *\n * @param {Object|String} loc Optional default location object.\n * @returns {Object} lolcation object.\n * @public\n */\nfunction lolcation(loc) {\n var globalVar;\n\n if (typeof window !== 'undefined') globalVar = window;\n else if (typeof global !== 'undefined') globalVar = global;\n else if (typeof self !== 'undefined') globalVar = self;\n else globalVar = {};\n\n var location = globalVar.location || {};\n loc = loc || location;\n\n var finaldestination = {}\n , type = typeof loc\n , key;\n\n if ('blob:' === loc.protocol) {\n finaldestination = new Url(unescape(loc.pathname), {});\n } else if ('string' === type) {\n finaldestination = new Url(loc, {});\n for (key in ignore) delete finaldestination[key];\n } else if ('object' === type) {\n for (key in loc) {\n if (key in ignore) continue;\n finaldestination[key] = loc[key];\n }\n\n if (finaldestination.slashes === undefined) {\n finaldestination.slashes = slashes.test(loc.href);\n }\n }\n\n return finaldestination;\n}\n\n/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n return (\n scheme === 'file:' ||\n scheme === 'ftp:' ||\n scheme === 'http:' ||\n scheme === 'https:' ||\n scheme === 'ws:' ||\n scheme === 'wss:'\n );\n}\n\n/**\n * @typedef ProtocolExtract\n * @type Object\n * @property {String} protocol Protocol matched in the URL, in lowercase.\n * @property {Boolean} slashes `true` if protocol is followed by \"//\", else `false`.\n * @property {String} rest Rest of the URL that is not part of the protocol.\n */\n\n/**\n * Extract protocol information from a URL with/without double slash (\"//\").\n *\n * @param {String} address URL we want to extract from.\n * @param {Object} location\n * @return {ProtocolExtract} Extracted information.\n * @private\n */\nfunction extractProtocol(address, location) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n location = location || {};\n\n var match = protocolre.exec(address);\n var protocol = match[1] ? match[1].toLowerCase() : '';\n var forwardSlashes = !!match[2];\n var otherSlashes = !!match[3];\n var slashesCount = 0;\n var rest;\n\n if (forwardSlashes) {\n if (otherSlashes) {\n rest = match[2] + match[3] + match[4];\n slashesCount = match[2].length + match[3].length;\n } else {\n rest = match[2] + match[4];\n slashesCount = match[2].length;\n }\n } else {\n if (otherSlashes) {\n rest = match[3] + match[4];\n slashesCount = match[3].length;\n } else {\n rest = match[4]\n }\n }\n\n if (protocol === 'file:') {\n if (slashesCount >= 2) {\n rest = rest.slice(2);\n }\n } else if (isSpecial(protocol)) {\n rest = match[4];\n } else if (protocol) {\n if (forwardSlashes) {\n rest = rest.slice(2);\n }\n } else if (slashesCount >= 2 && isSpecial(location.protocol)) {\n rest = match[4];\n }\n\n return {\n protocol: protocol,\n slashes: forwardSlashes || isSpecial(protocol),\n slashesCount: slashesCount,\n rest: rest\n };\n}\n\n/**\n * Resolve a relative URL pathname against a base URL pathname.\n *\n * @param {String} relative Pathname of the relative URL.\n * @param {String} base Pathname of the base URL.\n * @return {String} Resolved pathname.\n * @private\n */\nfunction resolve(relative, base) {\n if (relative === '') return base;\n\n var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))\n , i = path.length\n , last = path[i - 1]\n , unshift = false\n , up = 0;\n\n while (i--) {\n if (path[i] === '.') {\n path.splice(i, 1);\n } else if (path[i] === '..') {\n path.splice(i, 1);\n up++;\n } else if (up) {\n if (i === 0) unshift = true;\n path.splice(i, 1);\n up--;\n }\n }\n\n if (unshift) path.unshift('');\n if (last === '.' || last === '..') path.push('');\n\n return path.join('/');\n}\n\n/**\n * The actual URL instance. Instead of returning an object we've opted-in to\n * create an actual constructor as it's much more memory efficient and\n * faster and it pleases my OCD.\n *\n * It is worth noting that we should not use `URL` as class name to prevent\n * clashes with the global URL instance that got introduced in browsers.\n *\n * @constructor\n * @param {String} address URL we want to parse.\n * @param {Object|String} [location] Location defaults for relative paths.\n * @param {Boolean|Function} [parser] Parser for the query string.\n * @private\n */\nfunction Url(address, location, parser) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n\n if (!(this instanceof Url)) {\n return new Url(address, location, parser);\n }\n\n var relative, extracted, parse, instruction, index, key\n , instructions = rules.slice()\n , type = typeof location\n , url = this\n , i = 0;\n\n //\n // The following if statements allows this module two have compatibility with\n // 2 different API:\n //\n // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n // where the boolean indicates that the query string should also be parsed.\n //\n // 2. The `URL` interface of the browser which accepts a URL, object as\n // arguments. The supplied object will be used as default values / fall-back\n // for relative paths.\n //\n if ('object' !== type && 'string' !== type) {\n parser = location;\n location = null;\n }\n\n if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n location = lolcation(location);\n\n //\n // Extract protocol information before running the instructions.\n //\n extracted = extractProtocol(address || '', location);\n relative = !extracted.protocol && !extracted.slashes;\n url.slashes = extracted.slashes || relative && location.slashes;\n url.protocol = extracted.protocol || location.protocol || '';\n address = extracted.rest;\n\n //\n // When the authority component is absent the URL starts with a path\n // component.\n //\n if (\n extracted.protocol === 'file:' && (\n extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n (!extracted.slashes &&\n (extracted.protocol ||\n extracted.slashesCount < 2 ||\n !isSpecial(url.protocol)))\n ) {\n instructions[3] = [/(.*)/, 'pathname'];\n }\n\n for (; i < instructions.length; i++) {\n instruction = instructions[i];\n\n if (typeof instruction === 'function') {\n address = instruction(address, url);\n continue;\n }\n\n parse = instruction[0];\n key = instruction[1];\n\n if (parse !== parse) {\n url[key] = address;\n } else if ('string' === typeof parse) {\n index = parse === '@'\n ? address.lastIndexOf(parse)\n : address.indexOf(parse);\n\n if (~index) {\n if ('number' === typeof instruction[2]) {\n url[key] = address.slice(0, index);\n address = address.slice(index + instruction[2]);\n } else {\n url[key] = address.slice(index);\n address = address.slice(0, index);\n }\n }\n } else if ((index = parse.exec(address))) {\n url[key] = index[1];\n address = address.slice(0, index.index);\n }\n\n url[key] = url[key] || (\n relative && instruction[3] ? location[key] || '' : ''\n );\n\n //\n // Hostname, host and protocol should be lowercased so they can be used to\n // create a proper `origin`.\n //\n if (instruction[4]) url[key] = url[key].toLowerCase();\n }\n\n //\n // Also parse the supplied query string in to an object. If we're supplied\n // with a custom parser as function use that instead of the default build-in\n // parser.\n //\n if (parser) url.query = parser(url.query);\n\n //\n // If the URL is relative, resolve the pathname against the base URL.\n //\n if (\n relative\n && location.slashes\n && url.pathname.charAt(0) !== '/'\n && (url.pathname !== '' || location.pathname !== '')\n ) {\n url.pathname = resolve(url.pathname, location.pathname);\n }\n\n //\n // Default to a / for pathname if none exists. This normalizes the URL\n // to always have a /\n //\n if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n url.pathname = '/' + url.pathname;\n }\n\n //\n // We should not add port numbers if they are already the default port number\n // for a given protocol. As the host also contains the port number we're going\n // override it with the hostname which contains no port number.\n //\n if (!required(url.port, url.protocol)) {\n url.host = url.hostname;\n url.port = '';\n }\n\n //\n // Parse down the `auth` for the username and password.\n //\n url.username = url.password = '';\n\n if (url.auth) {\n index = url.auth.indexOf(':');\n\n if (~index) {\n url.username = url.auth.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = url.auth.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password))\n } else {\n url.username = encodeURIComponent(decodeURIComponent(url.auth));\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n }\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n //\n // The href is just the compiled result.\n //\n url.href = url.toString();\n}\n\n/**\n * This is convenience method for changing properties in the URL instance to\n * insure that they all propagate correctly.\n *\n * @param {String} part Property we need to adjust.\n * @param {Mixed} value The newly assigned value.\n * @param {Boolean|Function} fn When setting the query, it will be the function\n * used to parse the query.\n * When setting the protocol, double slash will be\n * removed from the final url if it is true.\n * @returns {URL} URL instance for chaining.\n * @public\n */\nfunction set(part, value, fn) {\n var url = this;\n\n switch (part) {\n case 'query':\n if ('string' === typeof value && value.length) {\n value = (fn || qs.parse)(value);\n }\n\n url[part] = value;\n break;\n\n case 'port':\n url[part] = value;\n\n if (!required(value, url.protocol)) {\n url.host = url.hostname;\n url[part] = '';\n } else if (value) {\n url.host = url.hostname +':'+ value;\n }\n\n break;\n\n case 'hostname':\n url[part] = value;\n\n if (url.port) value += ':'+ url.port;\n url.host = value;\n break;\n\n case 'host':\n url[part] = value;\n\n if (port.test(value)) {\n value = value.split(':');\n url.port = value.pop();\n url.hostname = value.join(':');\n } else {\n url.hostname = value;\n url.port = '';\n }\n\n break;\n\n case 'protocol':\n url.protocol = value.toLowerCase();\n url.slashes = !fn;\n break;\n\n case 'pathname':\n case 'hash':\n if (value) {\n var char = part === 'pathname' ? '/' : '#';\n url[part] = value.charAt(0) !== char ? char + value : value;\n } else {\n url[part] = value;\n }\n break;\n\n case 'username':\n case 'password':\n url[part] = encodeURIComponent(value);\n break;\n\n case 'auth':\n var index = value.indexOf(':');\n\n if (~index) {\n url.username = value.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = value.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(value));\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var ins = rules[i];\n\n if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n url.href = url.toString();\n\n return url;\n}\n\n/**\n * Transform the properties back in to a valid and full URL string.\n *\n * @param {Function} stringify Optional query stringify function.\n * @returns {String} Compiled version of the URL.\n * @public\n */\nfunction toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n var query\n , url = this\n , host = url.host\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) result += ':'+ url.password;\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n //\n // Trailing colon is removed from `url.host` when it is parsed. If it still\n // ends with a colon, then add back the trailing colon that was removed. This\n // prevents an invalid URL from being transformed into a valid one.\n //\n if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {\n host += ':';\n }\n\n result += host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n if (url.hash) result += url.hash;\n\n return result;\n}\n\nUrl.prototype = { set: set, toString: toString };\n\n//\n// Expose the URL parser and some additional properties that might be useful for\n// others or testing.\n//\nUrl.extractProtocol = extractProtocol;\nUrl.location = lolcation;\nUrl.trimLeft = trimLeft;\nUrl.qs = qs;\n\nmodule.exports = Url;\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { PartialJSONObject } from '@lumino/coreutils';\nimport { posix } from 'path';\nimport urlparse from 'url-parse';\n\n/**\n * The namespace for URL-related functions.\n */\nexport namespace URLExt {\n /**\n * Parse a url into a URL object.\n *\n * @param url - The URL string to parse.\n *\n * @returns A URL object.\n */\n export function parse(url: string): IUrl {\n if (typeof document !== 'undefined' && document) {\n const a = document.createElement('a');\n a.href = url;\n return a;\n }\n return urlparse(url);\n }\n\n /**\n * Parse URL and retrieve hostname\n *\n * @param url - The URL string to parse\n *\n * @returns a hostname string value\n */\n export function getHostName(url: string): string {\n return urlparse(url).hostname;\n }\n /**\n * Normalize a url.\n */\n export function normalize(url: string): string;\n export function normalize(url: undefined): undefined;\n export function normalize(url: string | undefined): string | undefined;\n export function normalize(url: string | undefined): string | undefined {\n return url && parse(url).toString();\n }\n\n /**\n * Join a sequence of url components and normalizes as in node `path.join`.\n *\n * @param parts - The url components.\n *\n * @returns the joined url.\n */\n export function join(...parts: string[]): string {\n let u = urlparse(parts[0], {});\n // Schema-less URL can be only parsed as relative to a base URL\n // see https://github.com/unshiftio/url-parse/issues/219#issuecomment-1002219326\n const isSchemaLess = u.protocol === '' && u.slashes;\n if (isSchemaLess) {\n u = urlparse(parts[0], 'https:' + parts[0]);\n }\n const prefix = `${isSchemaLess ? '' : u.protocol}${u.slashes ? '//' : ''}${\n u.auth\n }${u.auth ? '@' : ''}${u.host}`;\n // If there was a prefix, then the first path must start at the root.\n const path = posix.join(\n `${!!prefix && u.pathname[0] !== '/' ? '/' : ''}${u.pathname}`,\n ...parts.slice(1)\n );\n return `${prefix}${path === '.' ? '' : path}`;\n }\n\n /**\n * Encode the components of a multi-segment url.\n *\n * @param url - The url to encode.\n *\n * @returns the encoded url.\n *\n * #### Notes\n * Preserves the `'/'` separators.\n * Should not include the base url, since all parts are escaped.\n */\n export function encodeParts(url: string): string {\n return join(...url.split('/').map(encodeURIComponent));\n }\n\n /**\n * Return a serialized object string suitable for a query.\n *\n * @param value The source object.\n *\n * @returns an encoded url query.\n *\n * #### Notes\n * Modified version of [stackoverflow](http://stackoverflow.com/a/30707423).\n */\n export function objectToQueryString(value: PartialJSONObject): string {\n const keys = Object.keys(value).filter(key => key.length > 0);\n\n if (!keys.length) {\n return '';\n }\n\n return (\n '?' +\n keys\n .map(key => {\n const content = encodeURIComponent(String(value[key]));\n\n return key + (content ? '=' + content : '');\n })\n .join('&')\n );\n }\n\n /**\n * Return a parsed object that represents the values in a query string.\n */\n export function queryStringToObject(value: string): {\n [key: string]: string | undefined;\n } {\n return value\n .replace(/^\\?/, '')\n .split('&')\n .reduce(\n (acc, val) => {\n const [key, value] = val.split('=');\n\n if (key.length > 0) {\n acc[key] = decodeURIComponent(value || '');\n }\n\n return acc;\n },\n {} as { [key: string]: string }\n );\n }\n\n /**\n * Test whether the url is a local url.\n *\n * @param allowRoot - Whether the paths starting at Unix-style filesystem root (`/`) are permitted.\n *\n * #### Notes\n * This function returns `false` for any fully qualified url, including\n * `data:`, `file:`, and `//` protocol URLs.\n */\n export function isLocal(url: string, allowRoot: boolean = false): boolean {\n const { protocol } = parse(url);\n\n return (\n (!protocol || url.toLowerCase().indexOf(protocol) !== 0) &&\n (allowRoot ? url.indexOf('//') !== 0 : url.indexOf('/') !== 0)\n );\n }\n\n /**\n * The interface for a URL object\n */\n export interface IUrl {\n /**\n * The full URL string that was parsed with both the protocol and host\n * components converted to lower-case.\n */\n href: string;\n\n /**\n * Identifies the URL's lower-cased protocol scheme.\n */\n protocol: string;\n\n /**\n * The full lower-cased host portion of the URL, including the port if\n * specified.\n */\n host: string;\n\n /**\n * The lower-cased host name portion of the host component without the\n * port included.\n */\n hostname: string;\n\n /**\n * The numeric port portion of the host component.\n */\n port: string;\n\n /**\n * The entire path section of the URL.\n */\n pathname: string;\n\n /**\n * The \"fragment\" portion of the URL including the leading ASCII hash\n * `(#)` character\n */\n hash: string;\n\n /**\n * The search element, including leading question mark (`'?'`), if any,\n * of the URL.\n */\n search?: string;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { JSONExt } from '@lumino/coreutils';\nimport minimist from 'minimist';\nimport { URLExt } from './url';\n\n/**\n * Declare stubs for the node variables.\n */\ndeclare let process: any;\ndeclare let require: any;\n\n/**\n * The namespace for `PageConfig` functions.\n */\nexport namespace PageConfig {\n /**\n * Get global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n *\n * @returns The config value or an empty string if not found.\n *\n * #### Notes\n * All values are treated as strings.\n * For browser based applications, it is assumed that the page HTML\n * includes a script tag with the id `jupyter-config-data` containing the\n * configuration as valid JSON. In order to support the classic Notebook,\n * we fall back on checking for `body` data of the given `name`.\n *\n * For node applications, it is assumed that the process was launched\n * with a `--jupyter-config-data` option pointing to a JSON settings\n * file.\n */\n export function getOption(name: string): string {\n if (configData) {\n return configData[name] || getBodyData(name);\n }\n configData = Object.create(null);\n let found = false;\n\n // Use script tag if available.\n if (typeof document !== 'undefined' && document) {\n const el = document.getElementById('jupyter-config-data');\n\n if (el) {\n configData = JSON.parse(el.textContent || '') as {\n [key: string]: string;\n };\n found = true;\n }\n }\n // Otherwise use CLI if given.\n if (!found && typeof process !== 'undefined' && process.argv) {\n try {\n const cli = minimist(process.argv.slice(2));\n const path: any = require('path');\n let fullPath = '';\n if ('jupyter-config-data' in cli) {\n fullPath = path.resolve(cli['jupyter-config-data']);\n } else if ('JUPYTER_CONFIG_DATA' in process.env) {\n fullPath = path.resolve(process.env['JUPYTER_CONFIG_DATA']);\n }\n if (fullPath) {\n // Force Webpack to ignore this require.\n // eslint-disable-next-line\n configData = eval('require')(fullPath) as { [key: string]: string };\n }\n } catch (e) {\n console.error(e);\n }\n }\n\n if (!JSONExt.isObject(configData)) {\n configData = Object.create(null);\n } else {\n for (const key in configData) {\n // PageConfig expects strings\n if (typeof configData[key] !== 'string') {\n configData[key] = JSON.stringify(configData[key]);\n }\n }\n }\n return configData![name] || getBodyData(name);\n }\n\n /**\n * Set global configuration data for the Jupyter application.\n *\n * @param name - The name of the configuration option.\n * @param value - The value to set the option to.\n *\n * @returns The last config value or an empty string if it doesn't exist.\n */\n export function setOption(name: string, value: string): string {\n const last = getOption(name);\n\n configData![name] = value;\n return last;\n }\n\n /**\n * Get the base url for a Jupyter application, or the base url of the page.\n */\n export function getBaseUrl(): string {\n return URLExt.normalize(getOption('baseUrl') || '/');\n }\n\n /**\n * Get the tree url for a JupyterLab application.\n */\n export function getTreeUrl(): string {\n return URLExt.join(getBaseUrl(), getOption('treeUrl'));\n }\n\n /**\n * Get the base url for sharing links (usually baseUrl)\n */\n export function getShareUrl(): string {\n return URLExt.normalize(getOption('shareUrl') || getBaseUrl());\n }\n\n /**\n * Get the tree url for shareable links.\n * Usually the same as treeUrl,\n * but overridable e.g. when sharing with JupyterHub.\n */\n export function getTreeShareUrl(): string {\n return URLExt.normalize(URLExt.join(getShareUrl(), getOption('treeUrl')));\n }\n\n /**\n * Create a new URL given an optional mode and tree path.\n *\n * This is used to create URLS when the mode or tree path change as the user\n * changes mode or the current document in the main area. If fields in\n * options are omitted, the value in PageConfig will be used.\n *\n * @param options - IGetUrlOptions for the new path.\n */\n export function getUrl(options: IGetUrlOptions): string {\n let path = options.toShare ? getShareUrl() : getBaseUrl();\n const mode = options.mode ?? getOption('mode');\n const workspace = options.workspace ?? getOption('workspace');\n const labOrDoc = mode === 'single-document' ? 'doc' : 'lab';\n path = URLExt.join(path, labOrDoc);\n if (workspace !== defaultWorkspace) {\n path = URLExt.join(\n path,\n 'workspaces',\n encodeURIComponent(getOption('workspace') ?? defaultWorkspace)\n );\n }\n const treePath = options.treePath ?? getOption('treePath');\n if (treePath) {\n path = URLExt.join(path, 'tree', URLExt.encodeParts(treePath));\n }\n return path;\n }\n\n export const defaultWorkspace: string = 'default';\n\n /**\n * Options for getUrl\n */\n\n export interface IGetUrlOptions {\n /**\n * The optional mode as a string 'single-document' or 'multiple-document'. If\n * the mode argument is missing, it will be provided from the PageConfig.\n */\n mode?: string;\n\n /**\n * The optional workspace as a string. If this argument is missing, the value will\n * be pulled from PageConfig. To use the default workspace (no /workspaces/<name>\n * URL segment will be included) pass the string PageConfig.defaultWorkspace.\n */\n workspace?: string;\n\n /**\n * Whether the url is meant to be shared or not; default false.\n */\n toShare?: boolean;\n\n /**\n * The optional tree path as as string. If treePath is not provided it will be\n * provided from the PageConfig. If an empty string, the resulting path will not\n * contain a tree portion.\n */\n treePath?: string;\n }\n\n /**\n * Get the base websocket url for a Jupyter application, or an empty string.\n */\n export function getWsUrl(baseUrl?: string): string {\n let wsUrl = getOption('wsUrl');\n if (!wsUrl) {\n baseUrl = baseUrl ? URLExt.normalize(baseUrl) : getBaseUrl();\n if (baseUrl.indexOf('http') !== 0) {\n return '';\n }\n wsUrl = 'ws' + baseUrl.slice(4);\n }\n return URLExt.normalize(wsUrl);\n }\n\n /**\n * Returns the URL converting this notebook to a certain\n * format with nbconvert.\n */\n export function getNBConvertURL({\n path,\n format,\n download\n }: {\n path: string;\n format: string;\n download: boolean;\n }): string {\n const notebookPath = URLExt.encodeParts(path);\n const url = URLExt.join(getBaseUrl(), 'nbconvert', format, notebookPath);\n if (download) {\n return url + '?download=true';\n }\n return url;\n }\n\n /**\n * Get the authorization token for a Jupyter application.\n */\n export function getToken(): string {\n return getOption('token') || getBodyData('jupyterApiToken');\n }\n\n /**\n * Get the Notebook version info [major, minor, patch].\n */\n export function getNotebookVersion(): [number, number, number] {\n const notebookVersion = getOption('notebookVersion');\n if (notebookVersion === '') {\n return [0, 0, 0];\n }\n return JSON.parse(notebookVersion);\n }\n\n /**\n * Private page config data for the Jupyter application.\n */\n let configData: { [key: string]: string } | null = null;\n\n /**\n * Get a url-encoded item from `body.data` and decode it\n * We should never have any encoded URLs anywhere else in code\n * until we are building an actual request.\n */\n function getBodyData(key: string): string {\n if (typeof document === 'undefined' || !document.body) {\n return '';\n }\n const val = document.body.dataset[key];\n if (typeof val === 'undefined') {\n return '';\n }\n return decodeURIComponent(val);\n }\n\n /**\n * The namespace for page config `Extension` functions.\n */\n export namespace Extension {\n /**\n * Populate an array from page config.\n *\n * @param key - The page config key (e.g., `deferredExtensions`).\n *\n * #### Notes\n * This is intended for `deferredExtensions` and `disabledExtensions`.\n */\n function populate(key: string): string[] {\n try {\n const raw = getOption(key);\n if (raw) {\n return JSON.parse(raw);\n }\n } catch (error) {\n console.warn(`Unable to parse ${key}.`, error);\n }\n return [];\n }\n\n /**\n * The collection of deferred extensions in page config.\n */\n export const deferred = populate('deferredExtensions');\n\n /**\n * The collection of disabled extensions in page config.\n */\n export const disabled = populate('disabledExtensions');\n\n /**\n * Returns whether a plugin is deferred.\n *\n * @param id - The plugin ID.\n */\n export function isDeferred(id: string): boolean {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return deferred.some(val => val === id || (extName && val === extName));\n }\n\n /**\n * Returns whether a plugin is disabled.\n *\n * @param id - The plugin ID.\n */\n export function isDisabled(id: string): boolean {\n // Check for either a full plugin id match or an extension\n // name match.\n const separatorIndex = id.indexOf(':');\n let extName = '';\n if (separatorIndex !== -1) {\n extName = id.slice(0, separatorIndex);\n }\n return disabled.some(val => val === id || (extName && val === extName));\n }\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { posix } from 'path';\n\n/**\n * The namespace for path-related functions.\n *\n * Note that Jupyter server paths do not start with a leading slash.\n */\nexport namespace PathExt {\n /**\n * Join all arguments together and normalize the resulting path.\n * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.\n *\n * @param paths - The string paths to join.\n */\n export function join(...paths: string[]): string {\n const path = posix.join(...paths);\n return path === '.' ? '' : removeSlash(path);\n }\n\n /**\n * Join all arguments together and normalize the resulting path and preserve the leading slash.\n *\n * @param paths - The string paths to join.\n */\n export function joinWithLeadingSlash(...paths: string[]): string {\n const path = posix.join(...paths);\n return path === '.' ? '' : path;\n }\n\n /**\n * Return the last portion of a path. Similar to the Unix basename command.\n * Often used to extract the file name from a fully qualified path.\n *\n * @param path - The path to evaluate.\n *\n * @param ext - An extension to remove from the result.\n */\n export function basename(path: string, ext?: string): string {\n return posix.basename(path, ext);\n }\n\n /**\n * Get the directory name of a path, similar to the Unix dirname command.\n * When an empty path is given, returns the root path.\n *\n * @param path - The file path.\n */\n export function dirname(path: string): string {\n const dir = removeSlash(posix.dirname(path));\n return dir === '.' ? '' : dir;\n }\n\n /**\n * Get the extension of the path.\n *\n * @param path - The file path.\n *\n * @returns the extension of the file.\n *\n * #### Notes\n * The extension is the string from the last occurrence of the `.`\n * character to end of string in the last portion of the path, inclusive.\n * If there is no `.` in the last portion of the path, or if the first\n * character of the basename of path [[basename]] is `.`, then an\n * empty string is returned.\n */\n export function extname(path: string): string {\n return posix.extname(path);\n }\n\n /**\n * Normalize a string path, reducing '..' and '.' parts.\n * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.\n * When an empty path is given, returns the root path.\n *\n * @param path - The string path to normalize.\n */\n export function normalize(path: string): string {\n if (path === '') {\n return '';\n }\n return removeSlash(posix.normalize(path));\n }\n\n /**\n * Resolve a sequence of paths or path segments into an absolute path.\n * The root path in the application has no leading slash, so it is removed.\n *\n * @param parts - The paths to join.\n *\n * #### Notes\n * The right-most parameter is considered \\{to\\}. Other parameters are considered an array of \\{from\\}.\n *\n * Starting from leftmost \\{from\\} parameter, resolves \\{to\\} to an absolute path.\n *\n * If \\{to\\} isn't already absolute, \\{from\\} arguments are prepended in right to left order, until an absolute path is found. If after using all \\{from\\} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.\n */\n export function resolve(...parts: string[]): string {\n return removeSlash(posix.resolve(...parts));\n }\n\n /**\n * Solve the relative path from \\{from\\} to \\{to\\}.\n *\n * @param from - The source path.\n *\n * @param to - The target path.\n *\n * #### Notes\n * If from and to each resolve to the same path (after calling\n * path.resolve() on each), a zero-length string is returned.\n * If a zero-length string is passed as from or to, `/`\n * will be used instead of the zero-length strings.\n */\n export function relative(from: string, to: string): string {\n return removeSlash(posix.relative(from, to));\n }\n\n /**\n * Normalize a file extension to be of the type `'.foo'`.\n *\n * @param extension - the file extension.\n *\n * #### Notes\n * Adds a leading dot if not present and converts to lower case.\n */\n export function normalizeExtension(extension: string): string {\n if (extension.length > 0 && extension.indexOf('.') !== 0) {\n extension = `.${extension}`;\n }\n return extension;\n }\n\n /**\n * Remove the leading slash from a path.\n *\n * @param path the path from which to remove a leading slash.\n */\n export function removeSlash(path: string): string {\n if (path.indexOf('/') === 0) {\n path = path.slice(1);\n }\n return path;\n }\n}\n", "/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\n\nimport { PromiseDelegate } from '@lumino/coreutils';\nimport { ISignal } from '@lumino/signaling';\n\n/**\n * Convert a signal into a promise for the first emitted value.\n *\n * @param signal - The signal we are listening to.\n * @param timeout - Timeout to wait for signal in ms (not timeout if not defined or 0)\n *\n * @returns a Promise that resolves with a `(sender, args)` pair.\n */\nexport function signalToPromise<T, U>(\n signal: ISignal<T, U>,\n timeout?: number\n): Promise<[T, U]> {\n const waitForSignal = new PromiseDelegate<[T, U]>();\n\n function cleanup() {\n signal.disconnect(slot);\n }\n\n function slot(sender: T, args: U) {\n cleanup();\n waitForSignal.resolve([sender, args]);\n }\n signal.connect(slot);\n\n if ((timeout ?? 0) > 0) {\n setTimeout(() => {\n cleanup();\n waitForSignal.reject(`Signal not emitted within ${timeout} ms.`);\n }, timeout);\n }\n return waitForSignal.promise;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n/**\n * The namespace for text-related functions.\n */\nexport namespace Text {\n // javascript stores text as utf16 and string indices use \"code units\",\n // which stores high-codepoint characters as \"surrogate pairs\",\n // which occupy two indices in the javascript string.\n // We need to translate cursor_pos in the Jupyter protocol (in characters)\n // to js offset (with surrogate pairs taking two spots).\n\n const HAS_SURROGATES: boolean = '\uD835\uDC1A'.length > 1;\n\n /**\n * Convert a javascript string index into a unicode character offset\n *\n * @param jsIdx - The javascript string index (counting surrogate pairs)\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The unicode character offset\n */\n export function jsIndexToCharIndex(jsIdx: number, text: string): number {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return jsIdx;\n }\n let charIdx = jsIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n charIdx--;\n i++;\n }\n }\n }\n return charIdx;\n }\n\n /**\n * Convert a unicode character offset to a javascript string index.\n *\n * @param charIdx - The index in unicode characters\n *\n * @param text - The text in which the offset is calculated\n *\n * @returns The js-native index\n */\n export function charIndexToJsIndex(charIdx: number, text: string): number {\n if (HAS_SURROGATES) {\n // not using surrogates, nothing to do\n return charIdx;\n }\n let jsIdx = charIdx;\n for (let i = 0; i + 1 < text.length && i < jsIdx; i++) {\n const charCode = text.charCodeAt(i);\n // check for surrogate pair\n if (charCode >= 0xd800 && charCode <= 0xdbff) {\n const nextCharCode = text.charCodeAt(i + 1);\n if (nextCharCode >= 0xdc00 && nextCharCode <= 0xdfff) {\n jsIdx++;\n i++;\n }\n }\n }\n return jsIdx;\n }\n\n /**\n * Given a 'snake-case', 'snake_case', 'snake:case', or\n * 'snake case' string, will return the camel case version: 'snakeCase'.\n *\n * @param str the snake-case input string.\n *\n * @param upper default = false. If true, the first letter of the\n * returned string will be capitalized.\n *\n * @returns the camel case version of the input string.\n */\n export function camelCase(str: string, upper: boolean = false): string {\n return str.replace(/^(\\w)|[\\s-_:]+(\\w)/g, function (match, p1, p2) {\n if (p2) {\n return p2.toUpperCase();\n } else {\n return upper ? p1.toUpperCase() : p1.toLowerCase();\n }\n });\n }\n\n /**\n * Given a string, title case the words in the string.\n *\n * @param str the string to title case.\n *\n * @returns the same string, but with each word capitalized.\n */\n export function titleCase(str: string): string {\n return (str || '')\n .toLowerCase()\n .split(' ')\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n/**\n * A list of time units with their associated value in milliseconds.\n */\nconst UNITS: { name: Intl.RelativeTimeFormatUnit; milliseconds: number }[] = [\n { name: 'years', milliseconds: 365 * 24 * 60 * 60 * 1000 },\n { name: 'months', milliseconds: 30 * 24 * 60 * 60 * 1000 },\n { name: 'days', milliseconds: 24 * 60 * 60 * 1000 },\n { name: 'hours', milliseconds: 60 * 60 * 1000 },\n { name: 'minutes', milliseconds: 60 * 1000 },\n { name: 'seconds', milliseconds: 1000 }\n];\n\n/**\n * The namespace for date functions.\n */\nexport namespace Time {\n export type HumanStyle = Intl.ResolvedRelativeTimeFormatOptions['style'];\n\n /**\n * Convert a timestring to a human readable string (e.g. 'two minutes ago').\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n export function formatHuman(\n value: string | Date,\n format: HumanStyle = 'long'\n ): string {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.RelativeTimeFormat(lang, {\n numeric: 'auto',\n style: format\n });\n const delta = new Date(value).getTime() - Date.now();\n for (let unit of UNITS) {\n const amount = Math.ceil(delta / unit.milliseconds);\n if (amount === 0) {\n continue;\n }\n return formatter.format(amount, unit.name);\n }\n return formatter.format(0, 'seconds');\n }\n\n /**\n * Convenient helper to convert a timestring to a date format.\n *\n * @param value - The date timestring or date object.\n *\n * @returns A formatted date.\n */\n export function format(value: string | Date): string {\n const lang = document.documentElement.lang || 'en';\n const formatter = new Intl.DateTimeFormat(lang, {\n dateStyle: 'short',\n timeStyle: 'short'\n });\n return formatter.format(new Date(value));\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * @packageDocumentation\n * @module coreutils\n */\n\nexport * from './activitymonitor';\nexport * from './interfaces';\nexport * from './lru';\nexport * from './markdowncodeblocks';\nexport * from './pageconfig';\nexport * from './path';\nexport * from './signal';\nexport * from './text';\nexport * from './time';\nexport * from './url';\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport * as nbformat from '@jupyterlab/nbformat';\nimport { JSONObject, UUID } from '@lumino/coreutils';\n\nexport interface IOptions<T extends Message> {\n session: string;\n channel: T['channel'];\n msgType: T['header']['msg_type'];\n content: T['content'];\n buffers?: (ArrayBuffer | ArrayBufferView)[];\n metadata?: JSONObject;\n msgId?: string;\n username?: string;\n subshellId?: string | null;\n parentHeader?: T['parent_header'];\n}\nexport function createMessage<T extends IClearOutputMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICommCloseMsg<'iopub'>>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICommCloseMsg<'shell'>>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICommInfoReplyMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICommInfoRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICommMsgMsg<'iopub'>>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICommMsgMsg<'shell'>>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICommOpenMsg<'iopub'>>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICommOpenMsg<'shell'>>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICompleteReplyMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICompleteRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IDisplayDataMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IErrorMsg>(options: IOptions<T>): T;\nexport function createMessage<T extends IExecuteInputMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IExecuteReplyMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IExecuteRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IExecuteResultMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IHistoryReplyMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IHistoryRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IInfoReplyMsg>(options: IOptions<T>): T;\nexport function createMessage<T extends IInfoRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IInputReplyMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IInputRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IInspectReplyMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IInspectRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IIsCompleteReplyMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IIsCompleteRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IStatusMsg>(options: IOptions<T>): T;\nexport function createMessage<T extends IStreamMsg>(options: IOptions<T>): T;\nexport function createMessage<T extends IUpdateDisplayDataMsg>(\n options: IOptions<T>\n): T;\n\n/**\n * @hidden\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this function is *NOT* considered\n * part of the public API, and may change without notice.\n */\nexport function createMessage<T extends IDebugRequestMsg>(\n options: IOptions<T>\n): T;\n\n/**\n * @hidden\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this function is *NOT* considered\n * part of the public API, and may change without notice.\n */\nexport function createMessage<T extends IDebugReplyMsg>(\n options: IOptions<T>\n): T;\n\n/**\n * @hidden\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this function is *NOT* considered\n * part of the public API, and may change without notice.\n */\nexport function createMessage<T extends IDebugEventMsg>(\n options: IOptions<T>\n): T;\n\nexport function createMessage<T extends ICreateSubshellRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends ICreateSubshellReplyMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IDeleteSubshellRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IDeleteSubshellReplyMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IListSubshellRequestMsg>(\n options: IOptions<T>\n): T;\nexport function createMessage<T extends IListSubshellReplyMsg>(\n options: IOptions<T>\n): T;\n\nexport function createMessage<T extends Message>(options: IOptions<T>): T {\n return {\n buffers: options.buffers ?? [],\n channel: options.channel,\n content: options.content,\n header: {\n date: new Date().toISOString(),\n msg_id: options.msgId ?? UUID.uuid4(),\n msg_type: options.msgType,\n session: options.session,\n username: options.username ?? '',\n subshell_id: options.subshellId ?? null,\n version: '5.2'\n },\n metadata: options.metadata ?? {},\n parent_header: options.parentHeader ?? {}\n } as T;\n}\n\n/**\n * Shell message types.\n */\nexport type ShellMessageType =\n | 'comm_close'\n | 'comm_info_reply'\n | 'comm_info_request'\n | 'comm_msg'\n | 'comm_open'\n | 'complete_reply'\n | 'complete_request'\n | 'execute_reply'\n | 'execute_request'\n | 'history_reply'\n | 'history_request'\n | 'inspect_reply'\n | 'inspect_request'\n | 'interrupt_reply'\n | 'interrupt_request'\n | 'is_complete_reply'\n | 'is_complete_request'\n | 'kernel_info_reply'\n | 'kernel_info_request'\n | 'shutdown_reply'\n | 'shutdown_request';\n\n/**\n * Control message types.\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, debug message types are *NOT*\n * considered part of the public API, and may change without notice.\n */\nexport type ControlMessageType =\n | 'debug_request'\n | 'debug_reply'\n | 'create_subshell_request'\n | 'create_subshell_reply'\n | 'delete_subshell_request'\n | 'delete_subshell_reply'\n | 'list_subshell_request'\n | 'list_subshell_reply';\n\n/**\n * IOPub message types.\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, debug message types are *NOT*\n * considered part of the public API, and may change without notice.\n */\nexport type IOPubMessageType =\n | 'clear_output'\n | 'comm_close'\n | 'comm_msg'\n | 'comm_open'\n | 'display_data'\n | 'error'\n | 'execute_input'\n | 'execute_result'\n | 'shutdown_reply'\n | 'status'\n | 'stream'\n | 'update_display_data'\n | 'debug_event';\n\n/**\n * Stdin message types.\n */\nexport type StdinMessageType = 'input_request' | 'input_reply';\n\n/**\n * Jupyter message types.\n */\nexport type MessageType =\n | IOPubMessageType\n | ShellMessageType\n | ControlMessageType\n | StdinMessageType;\n\n/**\n * The valid Jupyter channel names in a message to a frontend.\n */\nexport type Channel = 'shell' | 'control' | 'iopub' | 'stdin';\n\n/**\n * Kernel message header content.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#general-message-format).\n *\n * **See also:** [[IMessage]]\n */\nexport interface IHeader<T extends MessageType = MessageType> {\n /**\n * ISO 8601 timestamp for when the message is created\n */\n date: string;\n\n /**\n * Message id, typically UUID, must be unique per message\n */\n msg_id: string;\n\n /**\n * Message type\n */\n msg_type: T;\n\n /**\n * Session id, typically UUID, should be unique per session.\n */\n session: string;\n\n /**\n * The user sending the message\n */\n username: string;\n\n /**\n * Subshell id identifying a subshell if not in main shell\n */\n subshell_id?: string;\n\n /**\n * The message protocol version, should be 5.1, 5.2, 5.3, etc.\n */\n version: string;\n}\n\n/**\n * Kernel message specification.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#general-message-format).\n */\nexport interface IMessage<MSGTYPE extends MessageType = MessageType> {\n /**\n * An optional list of binary buffers.\n */\n buffers?: (ArrayBuffer | ArrayBufferView)[];\n\n /**\n * The channel on which the message is transmitted.\n */\n channel: Channel;\n\n /**\n * The content of the message.\n */\n content: Message['content'];\n\n /**\n * The message header.\n */\n header: IHeader<MSGTYPE>;\n\n /**\n * Metadata associated with the message.\n */\n metadata: JSONObject;\n\n /**\n * The parent message\n */\n parent_header: IHeader | Record<string, never>;\n}\n\n/**\n * A kernel message on the `'shell'` channel.\n */\nexport interface IShellMessage<T extends ShellMessageType = ShellMessageType>\n extends IMessage<T> {\n channel: 'shell';\n}\n\n/**\n * A kernel message on the `'control'` channel.\n */\nexport interface IControlMessage<\n T extends ControlMessageType = ControlMessageType\n> extends IMessage<T> {\n channel: 'control';\n}\n\n/**\n * A message type for shell or control messages.\n *\n * #### Notes\n * This convenience is so we can use it as a generic type constraint.\n */\nexport type IShellControlMessage = IShellMessage | IControlMessage;\n\n/**\n * A kernel message on the `'iopub'` channel.\n */\nexport interface IIOPubMessage<T extends IOPubMessageType = IOPubMessageType>\n extends IMessage<T> {\n channel: 'iopub';\n}\n\n/**\n * A kernel message on the `'stdin'` channel.\n */\nexport interface IStdinMessage<T extends StdinMessageType = StdinMessageType>\n extends IMessage<T> {\n channel: 'stdin';\n}\n\n/**\n * Message types.\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, debug message types are *NOT*\n * considered part of the public API, and may change without notice.\n */\nexport type Message =\n | IClearOutputMsg\n | ICommCloseMsg<'iopub'>\n | ICommCloseMsg<'shell'>\n | ICommInfoReplyMsg\n | ICommInfoRequestMsg\n | ICommMsgMsg<'iopub'>\n | ICommMsgMsg<'shell'>\n | ICommOpenMsg<'iopub'>\n | ICommOpenMsg<'shell'>\n | ICompleteReplyMsg\n | ICompleteRequestMsg\n | IDisplayDataMsg\n | IErrorMsg\n | IExecuteInputMsg\n | IExecuteReplyMsg\n | IExecuteRequestMsg\n | IExecuteResultMsg\n | IHistoryReplyMsg\n | IHistoryRequestMsg\n | IInfoReplyMsg\n | IInfoRequestMsg\n | IInputReplyMsg\n | IInputRequestMsg\n | IInspectReplyMsg\n | IInspectRequestMsg\n | IIsCompleteReplyMsg\n | IIsCompleteRequestMsg\n | IStatusMsg\n | IStreamMsg\n | IUpdateDisplayDataMsg\n | IDebugRequestMsg\n | IDebugReplyMsg\n | IDebugEventMsg\n | ICreateSubshellRequestMsg\n | ICreateSubshellReplyMsg\n | IDeleteSubshellRequestMsg\n | IDeleteSubshellReplyMsg\n | IListSubshellRequestMsg\n | IListSubshellReplyMsg;\n\n// ////////////////////////////////////////////////\n// IOPub Messages\n// ///////////////////////////////////////////////\n\n/**\n * A `'stream'` message on the `'iopub'` channel.\n *\n * See [Streams](https://jupyter-client.readthedocs.io/en/latest/messaging.html#streams-stdout-stderr-etc).\n */\nexport interface IStreamMsg extends IIOPubMessage<'stream'> {\n content: {\n name: 'stdout' | 'stderr';\n text: string;\n };\n}\n\n/**\n * Test whether a kernel message is a `'stream'` message.\n */\nexport function isStreamMsg(msg: IMessage): msg is IStreamMsg {\n return msg.header.msg_type === 'stream';\n}\n\n/**\n * A `'display_data'` message on the `'iopub'` channel.\n *\n * See [Display data](https://jupyter-client.readthedocs.io/en/latest/messaging.html#display-data).\n */\nexport interface IDisplayDataMsg extends IIOPubMessage<'display_data'> {\n content: {\n data: nbformat.IMimeBundle;\n metadata: nbformat.OutputMetadata;\n transient?: { display_id?: string };\n };\n}\n\n/**\n * Test whether a kernel message is an `'display_data'` message.\n */\nexport function isDisplayDataMsg(msg: IMessage): msg is IDisplayDataMsg {\n return msg.header.msg_type === 'display_data';\n}\n\n/**\n * An `'update_display_data'` message on the `'iopub'` channel.\n *\n * See [Update Display data](https://jupyter-client.readthedocs.io/en/latest/messaging.html#update-display-data).\n */\nexport interface IUpdateDisplayDataMsg\n extends IIOPubMessage<'update_display_data'> {\n content: IDisplayDataMsg['content'] & {\n // display_id is a required field in update_display_data\n transient: { display_id: string };\n };\n}\n\n/**\n * Test whether a kernel message is an `'update_display_data'` message.\n */\nexport function isUpdateDisplayDataMsg(\n msg: IMessage\n): msg is IUpdateDisplayDataMsg {\n return msg.header.msg_type === 'update_display_data';\n}\n\n/**\n * An `'execute_input'` message on the `'iopub'` channel.\n *\n * See [Code inputs](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-inputs).\n */\nexport interface IExecuteInputMsg extends IIOPubMessage<'execute_input'> {\n content: {\n code: string;\n execution_count: nbformat.ExecutionCount;\n };\n}\n\n/**\n * Test whether a kernel message is an `'execute_input'` message.\n */\nexport function isExecuteInputMsg(msg: IMessage): msg is IExecuteInputMsg {\n return msg.header.msg_type === 'execute_input';\n}\n\n/**\n * An `'execute_result'` message on the `'iopub'` channel.\n *\n * See [Execution results](https://jupyter-client.readthedocs.io/en/latest/messaging.html#id4).\n */\nexport interface IExecuteResultMsg extends IIOPubMessage<'execute_result'> {\n content: {\n execution_count: nbformat.ExecutionCount;\n data: nbformat.IMimeBundle;\n metadata: nbformat.OutputMetadata;\n transient?: { display_id?: string };\n };\n}\n\n/**\n * Test whether a kernel message is an `'execute_result'` message.\n */\nexport function isExecuteResultMsg(msg: IMessage): msg is IExecuteResultMsg {\n return msg.header.msg_type === 'execute_result';\n}\n\n/**\n * A `'error'` message on the `'iopub'` channel.\n *\n * See [Execution errors](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execution-errors).\n */\nexport interface IErrorMsg extends IIOPubMessage<'error'> {\n content: {\n ename: string;\n evalue: string;\n traceback: string[];\n };\n}\n\n/**\n * Test whether a kernel message is an `'error'` message.\n */\nexport function isErrorMsg(msg: IMessage): msg is IErrorMsg {\n return msg.header.msg_type === 'error';\n}\n\n/**\n * The valid Kernel status states.\n *\n * #### Notes\n * The status states are:\n * * `unknown`: The kernel status is unknown, often because the connection\n * is disconnected or connecting. This state is determined by the kernel\n * connection status.\n * * `autorestarting`: The kernel is restarting, initiated by the server.\n * This state is set by the services library, not explicitly sent from the\n * kernel.\n * * `starting`: The kernel is starting\n * * `idle`: The kernel has finished processing messages.\n * * `busy`: The kernel is currently processing messages.\n * * `restarting`: The kernel is restarting. This state is sent by the\n * Jupyter server.\n * * `dead`: The kernel is dead and will not be restarted. This state is set\n * by the Jupyter server and is a final state.\n */\nexport type Status =\n | 'unknown'\n | 'starting'\n | 'idle'\n | 'busy'\n | 'terminating'\n | 'restarting'\n | 'autorestarting'\n | 'dead';\n\n/**\n * A `'status'` message on the `'iopub'` channel.\n *\n * See [Kernel status](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-status).\n */\nexport interface IStatusMsg extends IIOPubMessage<'status'> {\n content: {\n execution_state: Status;\n };\n}\n\n/**\n * Test whether a kernel message is a `'status'` message.\n */\nexport function isStatusMsg(msg: IMessage): msg is IStatusMsg {\n return msg.header.msg_type === 'status';\n}\n\n/**\n * A `'clear_output'` message on the `'iopub'` channel.\n *\n * See [Clear output](https://jupyter-client.readthedocs.io/en/latest/messaging.html#clear-output).\n */\nexport interface IClearOutputMsg extends IIOPubMessage<'clear_output'> {\n content: {\n wait: boolean;\n };\n}\n\n/**\n * Test whether a kernel message is a `'clear_output'` message.\n */\nexport function isClearOutputMsg(msg: IMessage): msg is IClearOutputMsg {\n return msg.header.msg_type === 'clear_output';\n}\n\n/**\n * An experimental `'debug_event'` message on the `'iopub'` channel\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\nexport interface IDebugEventMsg extends IIOPubMessage<'debug_event'> {\n content: {\n seq: number;\n type: 'event';\n event: string;\n body?: any;\n };\n}\n\n/**\n * Test whether a kernel message is an experimental `'debug_event'` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\n\nexport function isDebugEventMsg(msg: IMessage): msg is IDebugEventMsg {\n return msg.header.msg_type === 'debug_event';\n}\n\n// ////////////////////////////////////////////////\n// Comm Messages\n// ///////////////////////////////////////////////\n\n/**\n * A `'comm_open'` message on the `'iopub'` channel.\n *\n * See [Comm open](https://jupyter-client.readthedocs.io/en/latest/messaging.html#opening-a-comm).\n */\nexport interface ICommOpenMsg<T extends 'shell' | 'iopub' = 'iopub' | 'shell'>\n extends IMessage<'comm_open'> {\n channel: T;\n content: {\n comm_id: string;\n target_name: string;\n data: JSONObject;\n target_module?: string;\n };\n}\n\n/**\n * Test whether a kernel message is a `'comm_open'` message.\n */\nexport function isCommOpenMsg(msg: IMessage): msg is ICommOpenMsg {\n return msg.header.msg_type === 'comm_open';\n}\n\n/**\n * A `'comm_close'` message on the `'iopub'` channel.\n *\n * See [Comm close](https://jupyter-client.readthedocs.io/en/latest/messaging.html#opening-a-comm).\n */\nexport interface ICommCloseMsg<T extends 'iopub' | 'shell' = 'iopub' | 'shell'>\n extends IMessage<'comm_close'> {\n channel: T;\n content: {\n comm_id: string;\n data: JSONObject;\n };\n}\n\n/**\n * Test whether a kernel message is a `'comm_close'` message.\n */\nexport function isCommCloseMsg(\n msg: IMessage\n): msg is ICommCloseMsg<'iopub' | 'shell'> {\n return msg.header.msg_type === 'comm_close';\n}\n\n/**\n * A `'comm_msg'` message on the `'iopub'` channel.\n *\n * See [Comm msg](https://jupyter-client.readthedocs.io/en/latest/messaging.html#opening-a-comm).\n */\nexport interface ICommMsgMsg<T extends 'iopub' | 'shell' = 'iopub' | 'shell'>\n extends IMessage<'comm_msg'> {\n channel: T;\n content: {\n comm_id: string;\n data: JSONObject;\n };\n}\n\n/**\n * Test whether a kernel message is a `'comm_msg'` message.\n */\nexport function isCommMsgMsg(msg: IMessage): msg is ICommMsgMsg {\n return msg.header.msg_type === 'comm_msg';\n}\n\n// ////////////////////////////////////////////////\n// Shell Messages\n// ///////////////////////////////////////////////\n\n/**\n * Reply content indicating a successful request.\n */\nexport interface IReplyOkContent {\n status: 'ok';\n}\n\n/**\n * Reply content indicating an error.\n *\n * See the [Message spec](https://jupyter-client.readthedocs.io/en/latest/messaging.html#request-reply) for details.\n */\nexport interface IReplyErrorContent {\n status: 'error';\n\n /**\n * Exception name\n */\n ename: string;\n\n /**\n * Exception value\n */\n evalue: string;\n\n /**\n * Traceback\n */\n traceback: string[];\n}\n\n/**\n * Reply content indicating an aborted request.\n *\n * This is [deprecated](https://jupyter-client.readthedocs.io/en/latest/messaging.html#request-reply)\n * in message spec 5.1. Kernels should send an 'error' reply instead.\n */\nexport interface IReplyAbortContent {\n status: 'abort';\n}\n\n/**\n * A convenience type for reply content.\n *\n * This automatically unions the necessary error and abort replies required in\n * the [message spec](https://jupyter-client.readthedocs.io/en/latest/messaging.html#request-reply).\n */\ntype ReplyContent<T> = T | IReplyErrorContent | IReplyAbortContent;\n\n/**\n * A `'kernel_info_request'` message on the `'shell'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).\n */\nexport interface IInfoRequestMsg extends IShellMessage<'kernel_info_request'> {\n content: Record<string, never>;\n}\n\n/**\n * Test whether a kernel message is a `'kernel_info_request'` message.\n */\nexport function isInfoRequestMsg(msg: IMessage): msg is IInfoRequestMsg {\n return msg.header.msg_type === 'kernel_info_request';\n}\n\n/**\n * A `'kernel_info_reply'` message content.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).\n */\nexport interface IInfoReply extends IReplyOkContent {\n protocol_version: string;\n implementation: string;\n implementation_version: string;\n language_info: ILanguageInfo;\n banner: string;\n help_links: { text: string; url: string }[];\n supported_features?: string[]; // https://github.com/jupyter/enhancement-proposals/pull/92\n}\n\n/**\n * The kernel language information specification.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).\n */\nexport interface ILanguageInfo extends nbformat.ILanguageInfoMetadata {\n version: string;\n nbconverter_exporter?: string;\n}\n\n/**\n * A `'kernel_info_reply'` message on the `'shell'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).\n */\nexport interface IInfoReplyMsg extends IShellMessage<'kernel_info_reply'> {\n parent_header: IHeader<'kernel_info_request'>;\n content: ReplyContent<IInfoReply>;\n}\n\n/**\n * A `'complete_request'` message.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).\n *\n * **See also:** [[ICompleteReplyMsg]], [[IKernel.complete]]\n */\nexport interface ICompleteRequestMsg extends IShellMessage<'complete_request'> {\n content: {\n code: string;\n cursor_pos: number;\n };\n}\n\n/**\n * A `'complete_reply'` message content.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).\n *\n * **See also:** [[ICompleteRequest]], [[IKernel.complete]]\n */\ninterface ICompleteReply extends IReplyOkContent {\n matches: string[];\n cursor_start: number;\n cursor_end: number;\n metadata: JSONObject;\n}\n\n/**\n * A `'complete_reply'` message on the `'shell'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).\n *\n * **See also:** [[ICompleteRequest]], [[IKernel.complete]]\n */\nexport interface ICompleteReplyMsg extends IShellMessage<'complete_reply'> {\n parent_header: IHeader<'complete_request'>;\n content: ReplyContent<ICompleteReply>;\n}\n\n/**\n * An `'inspect_request'` message.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).\n *\n * **See also:** [[IInspectReplyMsg]], [[[IKernel.inspect]]]\n */\nexport interface IInspectRequestMsg extends IShellMessage<'inspect_request'> {\n content: {\n code: string;\n cursor_pos: number;\n detail_level: 0 | 1;\n };\n}\n\n/**\n * A `'inspect_reply'` message content.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).\n *\n * **See also:** [[IInspectRequest]], [[IKernel.inspect]]\n */\n\nexport interface IInspectReply extends IReplyOkContent {\n found: boolean;\n data: JSONObject;\n metadata: JSONObject;\n}\n\n/**\n * A `'inspect_reply'` message on the `'shell'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).\n *\n * **See also:** [[IInspectRequest]], [[IKernel.inspect]]\n */\nexport interface IInspectReplyMsg extends IShellMessage<'inspect_reply'> {\n parent_header: IHeader<'inspect_request'>;\n content: ReplyContent<IInspectReply>;\n}\n\n/**\n * A `'history_request'` message.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).\n *\n * **See also:** [[IHistoryReplyMsg]], [[[IKernel.history]]]\n */\nexport interface IHistoryRequestMsg extends IShellMessage<'history_request'> {\n content: IHistoryRequestRange | IHistoryRequestSearch | IHistoryRequestTail;\n}\n\n/**\n * The content of a `'history_request'` range message.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).\n *\n * **See also:** [[IHistoryReply]], [[[IKernel.history]]]\n */\nexport interface IHistoryRequestRange {\n output: boolean;\n raw: boolean;\n hist_access_type: 'range';\n session: number;\n start: number;\n stop: number;\n}\n\n/**\n * The content of a `'history_request'` search message.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).\n *\n * **See also:** [[IHistoryReply]], [[[IKernel.history]]]\n */\nexport interface IHistoryRequestSearch {\n output: boolean;\n raw: boolean;\n hist_access_type: 'search';\n n: number;\n pattern: string;\n unique: boolean;\n}\n\n/**\n * The content of a `'history_request'` tail message.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).\n *\n * **See also:** [[IHistoryReply]], [[[IKernel.history]]]\n */\nexport interface IHistoryRequestTail {\n output: boolean;\n raw: boolean;\n hist_access_type: 'tail';\n n: number;\n}\n\n/**\n * A `'history_reply'` message content.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).\n *\n * **See also:** [[IHistoryRequest]], [[IKernel.history]]\n */\nexport interface IHistoryReply extends IReplyOkContent {\n history: [number, number, string][] | [number, number, [string, string]][];\n}\n\n/**\n * A `'history_reply'` message on the `'shell'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).\n *\n * **See also:** [[IHistoryRequest]], [[IKernel.history]]\n */\nexport interface IHistoryReplyMsg extends IShellMessage<'history_reply'> {\n parent_header: IHeader<'history_request'>;\n content: ReplyContent<IHistoryReply>;\n}\n\n/**\n * An `'is_complete_request'` message.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).\n *\n * **See also:** [[IIsCompleteReplyMsg]], [[IKernel.isComplete]]\n */\nexport interface IIsCompleteRequestMsg\n extends IShellMessage<'is_complete_request'> {\n content: {\n code: string;\n };\n}\n\n/**\n * An `'is_complete_reply'` message on the `'stream'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).\n *\n * **See also:** [[IIsCompleteRequest]], [[IKernel.isComplete]]\n */\nexport interface IIsCompleteReplyMsg\n extends IShellMessage<'is_complete_reply'> {\n parent_header: IHeader<'is_complete_request'>;\n content: ReplyContent<IIsCompleteReplyIncomplete | IIsCompleteReplyOther>;\n}\n\n/**\n * An 'incomplete' completion reply\n */\nexport interface IIsCompleteReplyIncomplete {\n status: 'incomplete';\n indent: string;\n}\n\n/**\n * A completion reply for completion or invalid states.\n */\nexport interface IIsCompleteReplyOther {\n status: 'complete' | 'invalid' | 'unknown';\n}\n\n/**\n * An `execute_request` message on the `'shell'` channel.\n */\nexport interface IExecuteRequestMsg extends IShellMessage<'execute_request'> {\n content: {\n /**\n * The code to execute.\n */\n code: string;\n\n /**\n * Whether to execute the code as quietly as possible.\n * The default is `false`.\n */\n silent?: boolean;\n\n /**\n * Whether to store history of the execution.\n * The default `true` if silent is False.\n * It is forced to `false ` if silent is `true`.\n */\n store_history?: boolean;\n\n /**\n * A mapping of names to expressions to be evaluated in the\n * kernel's interactive namespace.\n */\n user_expressions?: JSONObject;\n\n /**\n * Whether to allow stdin requests.\n * The default is `true`.\n */\n allow_stdin?: boolean;\n\n /**\n * Whether to the abort execution queue on an error.\n * The default is `false`.\n */\n stop_on_error?: boolean;\n };\n}\n\n/**\n * The content of an `execute-reply` message.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execution-results).\n */\nexport interface IExecuteCount {\n execution_count: nbformat.ExecutionCount;\n}\n\n/**\n * A convenience type for a base for an execute reply content.\n */\ntype IExecuteReplyBase = IExecuteCount & IReplyOkContent;\n\n/**\n * The `'execute_reply'` contents for an `'ok'` status.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execution-results).\n */\nexport interface IExecuteReply extends IExecuteReplyBase {\n /**\n * A list of payload objects.\n * Payloads are considered deprecated.\n * The only requirement of each payload object is that it have a 'source'\n * key, which is a string classifying the payload (e.g. 'page').\n */\n payload?: JSONObject[];\n\n /**\n * Results for the user_expressions.\n */\n user_expressions: JSONObject;\n}\n\n/**\n * An `'execute_reply'` message on the `'stream'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execution-results).\n *\n * **See also:** [[IExecuteRequest]], [[IKernel.execute]]\n */\nexport interface IExecuteReplyMsg extends IShellMessage<'execute_reply'> {\n parent_header: IHeader<'execute_request'>;\n content: ReplyContent<IExecuteReply> & IExecuteCount;\n}\n\n/**\n * Test whether a kernel message is an `'execute_reply'` message.\n */\nexport function isExecuteReplyMsg(msg: IMessage): msg is IExecuteReplyMsg {\n return msg.header.msg_type === 'execute_reply';\n}\n\n/**\n * A `'comm_info_request'` message on the `'shell'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#comm-info).\n *\n * **See also:** [[ICommInfoReplyMsg]], [[IKernel.commInfo]]\n */\nexport interface ICommInfoRequestMsg\n extends IShellMessage<'comm_info_request'> {\n content: {\n /**\n * The comm target name to filter returned comms\n */\n target_name?: string;\n };\n}\n\n/**\n * A `'comm_info_reply'` message content.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#comm-info).\n *\n * **See also:** [[ICommInfoRequest]], [[IKernel.commInfo]]\n */\nexport interface ICommInfoReply extends IReplyOkContent {\n /**\n * Mapping of comm ids to target names.\n */\n comms: { [commId: string]: { target_name: string } };\n}\n\n/**\n * A `'comm_info_reply'` message on the `'shell'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#comm-info).\n *\n * **See also:** [[ICommInfoRequestMsg]], [[IKernel.commInfo]]\n */\nexport interface ICommInfoReplyMsg extends IShellMessage<'comm_info_reply'> {\n parent_header: IHeader<'comm_info_request'>;\n content: ReplyContent<ICommInfoReply>;\n}\n\n// ///////////////////////////////////////////////\n// Control Messages\n// ///////////////////////////////////////////////\n\n/**\n * An experimental `'debug_request'` message on the `'control'` channel.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this function is *NOT* considered\n * part of the public API, and may change without notice.\n */\nexport interface IDebugRequestMsg extends IControlMessage<'debug_request'> {\n content: {\n seq: number;\n type: 'request';\n command: string;\n arguments?: any;\n };\n}\n\n/**\n * Test whether a kernel message is an experimental `'debug_request'` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\nexport function isDebugRequestMsg(msg: IMessage): msg is IDebugRequestMsg {\n return msg.header.msg_type === 'debug_request';\n}\n\n/**\n * An experimental `'debug_reply'` message on the `'control'` channel.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\nexport interface IDebugReplyMsg extends IControlMessage<'debug_reply'> {\n content: {\n seq: number;\n type: 'response';\n request_seq: number;\n success: boolean;\n command: string;\n message?: string;\n body?: any;\n };\n}\n\n/**\n * Test whether a kernel message is an experimental `'debug_reply'` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this is *NOT* considered\n * part of the public API, and may change without notice.\n */\nexport function isDebugReplyMsg(msg: IMessage): msg is IDebugReplyMsg {\n return msg.header.msg_type === 'debug_reply';\n}\n\n/**\n * A `'create_subshell_request'` message on the `'control'` channel.\n */\nexport interface ICreateSubshellRequestMsg\n extends IControlMessage<'create_subshell_request'> {\n content: Record<string, unknown>;\n}\n\n/**\n * A `'create_subshell_reply'` message on the `'control'` channel.\n */\nexport interface ICreateSubshellReplyMsg\n extends IControlMessage<'create_subshell_reply'> {\n content: {\n subshell_id: string;\n };\n}\n\n/**\n * A `'delete_subshell_request'` message on the `'control'` channel.\n */\nexport interface IDeleteSubshellRequestMsg\n extends IControlMessage<'delete_subshell_request'> {\n content: {\n subshell_id: string;\n };\n}\n\n/**\n * A `'delete_subshell_reply'` message on the `'control'` channel.\n */\nexport interface IDeleteSubshellReplyMsg\n extends IControlMessage<'delete_subshell_reply'> {\n content: Record<string, unknown>;\n}\n\n/**\n * A `'list_subshell_request'` message on the `'control'` channel.\n */\nexport interface IListSubshellRequestMsg\n extends IControlMessage<'list_subshell_request'> {\n content: Record<string, unknown>;\n}\n\n/**\n * A `'list_subshell_reply'` message on the `'control'` channel.\n */\nexport interface IListSubshellReplyMsg\n extends IControlMessage<'list_subshell_reply'> {\n content: {\n subshell_id: string[];\n };\n}\n\n// ////////////////////////////////////////////////\n// Stdin Messages\n// ///////////////////////////////////////////////\n\n/**\n * An `'input_request'` message on the `'stdin'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).\n */\nexport interface IInputRequestMsg extends IStdinMessage<'input_request'> {\n content: {\n /**\n * The text to show at the prompt.\n */\n prompt: string;\n\n /**\n * Whether the request is for a password.\n * If so, the frontend shouldn't echo input.\n */\n password: boolean;\n };\n}\n\n/**\n * Test whether a kernel message is an `'input_request'` message.\n */\nexport function isInputRequestMsg(msg: IMessage): msg is IInputRequestMsg {\n return msg.header.msg_type === 'input_request';\n}\n\n/**\n * An `'input_reply'` message content.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).\n */\nexport interface IInputReply extends IReplyOkContent {\n value: string;\n}\n\n/**\n * An `'input_reply'` message on the `'stdin'` channel.\n *\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).\n */\nexport interface IInputReplyMsg extends IStdinMessage<'input_reply'> {\n parent_header: IHeader<'input_request'>;\n content: ReplyContent<IInputReply>;\n}\n\n/**\n * Test whether a kernel message is an `'input_reply'` message.\n */\nexport function isInputReplyMsg(msg: IMessage): msg is IInputReplyMsg {\n return msg.header.msg_type === 'input_reply';\n}\n\n// ///////////////////////////////////////////////\n// Message (de)serialization\n// ///////////////////////////////////////////////\n\n/**\n * The list of supported kernel wire protocols over websocket.\n */\nexport enum supportedKernelWebSocketProtocols {\n v1KernelWebsocketJupyterOrg = 'v1.kernel.websocket.jupyter.org'\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport * as KernelMessage from './messages';\n\n/**\n * Serialize a kernel message for transport.\n */\nexport function serialize(\n msg: KernelMessage.IMessage,\n protocol: string = ''\n): string | ArrayBuffer {\n switch (protocol) {\n case KernelMessage.supportedKernelWebSocketProtocols\n .v1KernelWebsocketJupyterOrg:\n return Private.serializeV1KernelWebsocketJupyterOrg(msg);\n default:\n return Private.serializeDefault(msg);\n }\n}\n\n/**\n * Deserialize and return the unpacked message.\n */\nexport function deserialize(\n data: ArrayBuffer,\n protocol: string = ''\n): KernelMessage.IMessage {\n switch (protocol) {\n case KernelMessage.supportedKernelWebSocketProtocols\n .v1KernelWebsocketJupyterOrg:\n return Private.deserializeV1KernelWebsocketJupyterOrg(data);\n default:\n return Private.deserializeDefault(data);\n }\n}\n\nnamespace Private {\n /**\n * Deserialize and return the unpacked message.\n * Protocol `v1.kernel.websocket.jupyter.org`\n */\n export function deserializeV1KernelWebsocketJupyterOrg(\n binMsg: ArrayBuffer\n ): KernelMessage.IMessage {\n let msg: KernelMessage.IMessage;\n const data = new DataView(binMsg);\n const offsetNumber: number = Number(\n data.getBigUint64(0, true /* littleEndian */)\n );\n let offsets: number[] = [];\n for (let i = 0; i < offsetNumber; i++) {\n // WARNING: we cast our 64-bit unsigned int to a number!\n // so offsets cannot index up to 2**64 bytes\n offsets.push(\n Number(data.getBigUint64(8 * (i + 1), true /* littleEndian */))\n );\n }\n const decoder = new TextDecoder('utf8');\n const channel = decoder.decode(\n binMsg.slice(offsets[0], offsets[1])\n ) as KernelMessage.Channel;\n const header = JSON.parse(\n decoder.decode(binMsg.slice(offsets[1], offsets[2]))\n );\n const parent_header = JSON.parse(\n decoder.decode(binMsg.slice(offsets[2], offsets[3]))\n );\n const metadata = JSON.parse(\n decoder.decode(binMsg.slice(offsets[3], offsets[4]))\n );\n const content = JSON.parse(\n decoder.decode(binMsg.slice(offsets[4], offsets[5]))\n );\n let buffers = [];\n for (let i = 5; i < offsets.length - 1; i++) {\n buffers.push(new DataView(binMsg.slice(offsets[i], offsets[i + 1])));\n }\n msg = {\n channel,\n header,\n parent_header,\n metadata,\n content,\n buffers\n };\n return msg;\n }\n\n /**\n * Serialize a kernel message for transport.\n * Protocol `v1.kernel.websocket.jupyter.org`\n */\n export function serializeV1KernelWebsocketJupyterOrg(\n msg: KernelMessage.IMessage\n ): ArrayBuffer {\n const header = JSON.stringify(msg.header);\n const parentHeader =\n msg.parent_header == null ? '{}' : JSON.stringify(msg.parent_header);\n const metadata = JSON.stringify(msg.metadata);\n const content = JSON.stringify(msg.content);\n const buffers: (ArrayBuffer | ArrayBufferView)[] =\n msg.buffers !== undefined ? msg.buffers : [];\n const offsetNumber: number = 1 + 4 + buffers.length + 1;\n let offsets: number[] = [];\n offsets.push(8 * (1 + offsetNumber));\n offsets.push(msg.channel.length + offsets[offsets.length - 1]);\n const encoder = new TextEncoder();\n const channelEncoded = encoder.encode(msg.channel);\n const headerEncoded = encoder.encode(header);\n const parentHeaderEncoded = encoder.encode(parentHeader);\n const metadataEncoded = encoder.encode(metadata);\n const contentEncoded = encoder.encode(content);\n const binMsgNoBuff = new Uint8Array(\n channelEncoded.length +\n headerEncoded.length +\n parentHeaderEncoded.length +\n metadataEncoded.length +\n contentEncoded.length\n );\n binMsgNoBuff.set(channelEncoded);\n binMsgNoBuff.set(headerEncoded, channelEncoded.length);\n binMsgNoBuff.set(\n parentHeaderEncoded,\n channelEncoded.length + headerEncoded.length\n );\n binMsgNoBuff.set(\n metadataEncoded,\n channelEncoded.length + headerEncoded.length + parentHeaderEncoded.length\n );\n binMsgNoBuff.set(\n contentEncoded,\n channelEncoded.length +\n headerEncoded.length +\n parentHeaderEncoded.length +\n metadataEncoded.length\n );\n for (let length of [\n headerEncoded.length,\n parentHeaderEncoded.length,\n metadataEncoded.length,\n contentEncoded.length\n ]) {\n offsets.push(length + offsets[offsets.length - 1]);\n }\n let buffersByteLength = 0;\n for (let buffer of buffers) {\n let length = buffer.byteLength;\n offsets.push(length + offsets[offsets.length - 1]);\n buffersByteLength += length;\n }\n const binMsg = new Uint8Array(\n 8 * (1 + offsetNumber) + binMsgNoBuff.byteLength + buffersByteLength\n );\n const word = new ArrayBuffer(8);\n const data = new DataView(word);\n data.setBigUint64(0, BigInt(offsetNumber), true /* littleEndian */);\n binMsg.set(new Uint8Array(word), 0);\n for (let i = 0; i < offsets.length; i++) {\n data.setBigUint64(0, BigInt(offsets[i]), true /* littleEndian */);\n binMsg.set(new Uint8Array(word), 8 * (i + 1));\n }\n binMsg.set(binMsgNoBuff, offsets[0]);\n for (let i = 0; i < buffers.length; i++) {\n const buffer = buffers[i];\n binMsg.set(\n new Uint8Array(ArrayBuffer.isView(buffer) ? buffer.buffer : buffer),\n offsets[5 + i]\n );\n }\n return binMsg.buffer;\n }\n\n /**\n * Deserialize and return the unpacked message.\n * Default protocol\n *\n * #### Notes\n * Handles JSON blob strings and binary messages.\n */\n export function deserializeDefault(\n data: ArrayBuffer | string\n ): KernelMessage.IMessage {\n let value: KernelMessage.IMessage;\n if (typeof data === 'string') {\n value = JSON.parse(data);\n } else {\n value = deserializeBinary(data);\n }\n return value;\n }\n\n /**\n * Serialize a kernel message for transport.\n * Default protocol\n *\n * #### Notes\n * If there is binary content, an `ArrayBuffer` is returned,\n * otherwise the message is converted to a JSON string.\n */\n export function serializeDefault(\n msg: KernelMessage.IMessage\n ): string | ArrayBuffer {\n let value: string | ArrayBuffer;\n if (msg.buffers?.length) {\n value = serializeBinary(msg);\n } else {\n value = JSON.stringify(msg);\n }\n return value;\n }\n\n /**\n * Deserialize a binary message to a Kernel Message.\n */\n function deserializeBinary(buf: ArrayBuffer): KernelMessage.IMessage {\n const data = new DataView(buf);\n // read the header: 1 + nbufs 32b integers\n const nbufs = data.getUint32(0);\n const offsets: number[] = [];\n if (nbufs < 2) {\n throw new Error('Invalid incoming Kernel Message');\n }\n for (let i = 1; i <= nbufs; i++) {\n offsets.push(data.getUint32(i * 4));\n }\n const jsonBytes = new Uint8Array(buf.slice(offsets[0], offsets[1]));\n const msg = JSON.parse(new TextDecoder('utf8').decode(jsonBytes));\n // the remaining chunks are stored as DataViews in msg.buffers\n msg.buffers = [];\n for (let i = 1; i < nbufs; i++) {\n const start = offsets[i];\n const stop = offsets[i + 1] || buf.byteLength;\n msg.buffers.push(new DataView(buf.slice(start, stop)));\n }\n return msg;\n }\n\n /**\n * Implement the binary serialization protocol.\n *\n * Serialize Kernel message to ArrayBuffer.\n */\n function serializeBinary(msg: KernelMessage.IMessage): ArrayBuffer {\n const offsets: number[] = [];\n const buffers: ArrayBuffer[] = [];\n const encoder = new TextEncoder();\n let origBuffers: (ArrayBuffer | ArrayBufferView)[] = [];\n if (msg.buffers !== undefined) {\n origBuffers = msg.buffers;\n delete msg['buffers'];\n }\n const jsonUtf8 = encoder.encode(JSON.stringify(msg));\n buffers.push(jsonUtf8.buffer);\n for (let i = 0; i < origBuffers.length; i++) {\n // msg.buffers elements could be either views or ArrayBuffers\n // buffers elements are ArrayBuffers\n const b: any = origBuffers[i];\n buffers.push(ArrayBuffer.isView(b) ? b.buffer : b);\n }\n const nbufs = buffers.length;\n offsets.push(4 * (nbufs + 1));\n for (let i = 0; i + 1 < buffers.length; i++) {\n offsets.push(offsets[offsets.length - 1] + buffers[i].byteLength);\n }\n const msgBuf = new Uint8Array(\n offsets[offsets.length - 1] + buffers[buffers.length - 1].byteLength\n );\n // use DataView.setUint32 for network byte-order\n const view = new DataView(msgBuf.buffer);\n // write nbufs to first 4 bytes\n view.setUint32(0, nbufs);\n // write offsets to next 4 * nbufs bytes\n for (let i = 0; i < offsets.length; i++) {\n view.setUint32(4 * (i + 1), offsets[i]);\n }\n // write all the buffers at their respective offsets\n for (let i = 0; i < buffers.length; i++) {\n msgBuf.set(new Uint8Array(buffers[i]), offsets[i]);\n }\n return msgBuf.buffer;\n }\n}\n", "/*\n * Copyright (c) Jupyter Development Team.\n * Distributed under the terms of the Modified BSD License.\n */\n\nexport default WebSocket;\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { PageConfig, URLExt } from '@jupyterlab/coreutils';\nimport { KernelMessage } from './kernel';\nimport { deserialize, serialize } from './kernel/serialize';\n\nlet WEBSOCKET: typeof WebSocket;\n\nif (typeof window === 'undefined') {\n // Mangle the require statements so it does not get picked up in the\n // browser assets.\n WEBSOCKET = require('ws');\n} else {\n WEBSOCKET = WebSocket;\n}\n\ninterface ISerializer {\n /**\n * Serialize a kernel message for transport.\n */\n serialize(\n msg: KernelMessage.IMessage,\n protocol?: string\n ): string | ArrayBuffer;\n /**\n * Deserialize and return the unpacked message.\n */\n deserialize(data: ArrayBuffer, protocol?: string): KernelMessage.IMessage;\n}\n\n/**\n * The namespace for ServerConnection functions.\n *\n * #### Notes\n * This is only intended to manage communication with the Jupyter server.\n *\n * The default values can be used in a JupyterLab or Jupyter Notebook context.\n *\n * We use `token` authentication if available, falling back on an XSRF\n * cookie if one has been provided on the `document`.\n *\n * A content type of `'application/json'` is added when using authentication\n * and there is no body data to allow the server to prevent malicious forms.\n */\nexport namespace ServerConnection {\n /**\n * A Jupyter server settings object.\n * Note that all of the settings are optional when passed to\n * [[makeSettings]]. The default settings are given in [[defaultSettings]].\n */\n export interface ISettings {\n /**\n * The base url of the server.\n */\n readonly baseUrl: string;\n\n /**\n * The app url of the JupyterLab application.\n */\n readonly appUrl: string;\n\n /**\n * The base ws url of the server.\n */\n readonly wsUrl: string;\n\n /**\n * The default request init options.\n */\n readonly init: RequestInit;\n\n /**\n * The authentication token for requests. Use an empty string to disable.\n */\n readonly token: string;\n\n /**\n * Whether to append a token to a Websocket url. The default is `false` in the browser\n * and `true` in node or jest.\n */\n readonly appendToken: boolean;\n\n /**\n * The `fetch` method to use.\n */\n readonly fetch: (\n input: RequestInfo,\n init?: RequestInit\n ) => Promise<Response>;\n\n /**\n * The `Request` object constructor.\n */\n readonly Request: typeof Request;\n\n /**\n * The `Headers` object constructor.\n */\n readonly Headers: typeof Headers;\n\n /**\n * The `WebSocket` object constructor.\n */\n readonly WebSocket: typeof WebSocket;\n\n /**\n * Serializer used to serialize/deserialize kernel messages.\n */\n readonly serializer: ISerializer;\n }\n\n /**\n * Create a settings object given a subset of options.\n *\n * @param options - An optional partial set of options.\n *\n * @returns The full settings object.\n */\n export function makeSettings(options?: Partial<ISettings>): ISettings {\n return Private.makeSettings(options);\n }\n\n /**\n * Make an request to the notebook server.\n *\n * @param url - The url for the request.\n *\n * @param init - The initialization options for the request.\n *\n * @param settings - The server settings to apply to the request.\n *\n * @returns a Promise that resolves with the response.\n *\n * @throws If the url of the request is not a notebook server url.\n *\n * #### Notes\n * The `url` must start with `settings.baseUrl`. The `init` settings are\n * merged with `settings.init`, with `init` taking precedence.\n * The headers in the two objects are not merged.\n * If there is no body data, we set the content type to `application/json`\n * because it is required by the Notebook server.\n */\n export function makeRequest(\n url: string,\n init: RequestInit,\n settings: ISettings\n ): Promise<Response> {\n return Private.handleRequest(url, init, settings);\n }\n\n /**\n * A wrapped error for a fetch response.\n */\n export class ResponseError extends Error {\n /**\n * Create a ResponseError from a response, handling the traceback and message\n * as appropriate.\n *\n * @param response The response object.\n *\n * @returns A promise that resolves with a `ResponseError` object.\n */\n static async create(response: Response): Promise<ResponseError> {\n try {\n const data = await response.json();\n const { message, traceback } = data;\n if (traceback) {\n console.error(traceback);\n }\n return new ResponseError(\n response,\n message ?? ResponseError._defaultMessage(response),\n traceback ?? ''\n );\n } catch (e) {\n console.debug(e);\n return new ResponseError(response);\n }\n }\n\n /**\n * Create a new response error.\n */\n constructor(\n response: Response,\n message = ResponseError._defaultMessage(response),\n traceback = ''\n ) {\n super(message);\n this.response = response;\n this.traceback = traceback;\n }\n\n /**\n * The response associated with the error.\n */\n response: Response;\n\n /**\n * The traceback associated with the error.\n */\n traceback: string;\n\n private static _defaultMessage(response: Response): string {\n return `Invalid response: ${response.status} ${response.statusText}`;\n }\n }\n\n /**\n * A wrapped error for a network error.\n */\n export class NetworkError extends TypeError {\n /**\n * Create a new network error.\n */\n constructor(original: TypeError) {\n super(original.message);\n this.stack = original.stack;\n }\n }\n}\n\n/**\n * The namespace for module private data.\n */\nnamespace Private {\n /**\n * Handle the server connection settings, returning a new value.\n */\n export function makeSettings(\n options: Partial<ServerConnection.ISettings> = {}\n ): ServerConnection.ISettings {\n const pageBaseUrl = PageConfig.getBaseUrl();\n const pageWsUrl = PageConfig.getWsUrl();\n const baseUrl = URLExt.normalize(options.baseUrl) || pageBaseUrl;\n let wsUrl = options.wsUrl;\n // Prefer the default wsUrl if we are using the default baseUrl.\n if (!wsUrl && baseUrl === pageBaseUrl) {\n wsUrl = pageWsUrl;\n }\n // Otherwise convert the baseUrl to a wsUrl if possible.\n if (!wsUrl && baseUrl.indexOf('http') === 0) {\n wsUrl = 'ws' + baseUrl.slice(4);\n }\n // Otherwise fall back on the default wsUrl.\n wsUrl = wsUrl ?? pageWsUrl;\n\n const appendTokenConfig = PageConfig.getOption('appendToken').toLowerCase();\n let appendToken;\n if (appendTokenConfig === '') {\n appendToken =\n typeof window === 'undefined' ||\n (typeof process !== 'undefined' &&\n process?.env?.JEST_WORKER_ID !== undefined) ||\n URLExt.getHostName(pageBaseUrl) !== URLExt.getHostName(wsUrl);\n } else {\n appendToken = appendTokenConfig === 'true';\n }\n\n return {\n init: { cache: 'no-store', credentials: 'same-origin' },\n fetch,\n Headers,\n Request,\n WebSocket: WEBSOCKET,\n token: PageConfig.getToken(),\n appUrl: PageConfig.getOption('appUrl'),\n appendToken,\n serializer: { serialize, deserialize },\n ...options,\n baseUrl,\n wsUrl\n };\n }\n\n /**\n * Handle a request.\n *\n * @param url - The url for the request.\n *\n * @param init - The overrides for the request init.\n *\n * @param settings - The settings object for the request.\n *\n * #### Notes\n * The `url` must start with `settings.baseUrl`. The `init` settings\n * take precedence over `settings.init`.\n */\n export function handleRequest(\n url: string,\n init: RequestInit,\n settings: ServerConnection.ISettings\n ): Promise<Response> {\n // Handle notebook server requests.\n if (url.indexOf(settings.baseUrl) !== 0) {\n throw new Error('Can only be used for notebook server requests');\n }\n\n // Use explicit cache buster when `no-store` is set since\n // not all browsers use it properly.\n const cache = init.cache ?? settings.init.cache;\n if (cache === 'no-store') {\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Bypassing_the_cache\n url += (/\\?/.test(url) ? '&' : '?') + new Date().getTime();\n }\n\n const request = new settings.Request(url, { ...settings.init, ...init });\n\n // Handle authentication. Authentication can be overdetermined by\n // settings token and XSRF token.\n let authenticated = false;\n if (settings.token) {\n authenticated = true;\n request.headers.append('Authorization', `token ${settings.token}`);\n }\n if (typeof document !== 'undefined') {\n const xsrfToken = getCookie('_xsrf');\n if (xsrfToken !== undefined) {\n authenticated = true;\n request.headers.append('X-XSRFToken', xsrfToken);\n }\n }\n\n // Set the content type if there is no given data and we are\n // using an authenticated connection.\n if (!request.headers.has('Content-Type') && authenticated) {\n request.headers.set('Content-Type', 'application/json');\n }\n\n // Use `call` to avoid a `TypeError` in the browser.\n return settings.fetch.call(null, request).catch((e: TypeError) => {\n // Convert the TypeError into a more specific error.\n throw new ServerConnection.NetworkError(e);\n });\n // TODO: *this* is probably where we need a system-wide connectionFailure\n // signal we can hook into.\n }\n\n /**\n * Get a cookie from the document.\n */\n function getCookie(name: string): string | undefined {\n // From http://www.tornadoweb.org/en/stable/guide/security.html\n let cookie = '';\n try {\n cookie = document.cookie;\n } catch (e) {\n // e.g. SecurityError in case of CSP Sandbox\n return;\n }\n const matches = cookie.match('\\\\b' + name + '=([^;]*)\\\\b');\n return matches?.[1];\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { IObservableDisposable } from '@lumino/disposable';\nimport { ISignal, Signal } from '@lumino/signaling';\nimport { ServerConnection } from './serverconnection';\n\n/**\n * Object which manages kernel instances for a given base url.\n *\n * #### Notes\n * The manager is responsible for maintaining the state of kernel specs.\n */\nexport interface IManager extends IObservableDisposable {\n /**\n * A signal emitted when there is a connection failure.\n */\n connectionFailure: ISignal<IManager, ServerConnection.NetworkError>;\n\n /**\n * The server settings for the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Whether the manager is ready.\n */\n readonly isReady: boolean;\n\n /**\n * A promise that resolves when the manager is initially ready.\n */\n readonly ready: Promise<void>;\n\n /**\n * Whether the manager is active.\n */\n readonly isActive: boolean;\n}\n\nexport abstract class BaseManager implements IManager {\n constructor(options: BaseManager.IOptions) {\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n }\n /**\n * A signal emitted when the delegate is disposed.\n */\n get disposed(): ISignal<this, void> {\n return this._disposed;\n }\n\n /**\n * A signal emitted when there is a connection failure.\n */\n abstract connectionFailure: ISignal<this, Error>;\n\n /**\n * Test whether the delegate has been disposed.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * Test whether the manager is ready.\n */\n abstract isReady: boolean;\n\n /**\n * A promise that fulfills when the manager is ready.\n */\n abstract ready: Promise<void>;\n\n /**\n * Whether the manager is active.\n */\n get isActive(): boolean {\n return true;\n }\n\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n\n /**\n * The server settings of the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n private _isDisposed = false;\n private _disposed = new Signal<this, void>(this);\n}\n\n/**\n * The namespace for `BaseManager` class statics.\n */\nexport namespace BaseManager {\n /**\n * The options used to initialize a SessionManager.\n */\n export interface IOptions {\n /**\n * The server settings for the manager.\n */\n serverSettings?: ServerConnection.ISettings;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { URLExt } from '@jupyterlab/coreutils';\n\nimport { JSONObject, JSONValue } from '@lumino/coreutils';\n\nimport { ServerConnection } from '..';\n\n/**\n * The url for the config service.\n */\nconst SERVICE_CONFIG_URL = 'api/config';\n\n/**\n * A Configurable data section.\n */\nexport interface IConfigSection {\n /**\n * The data for this section.\n */\n readonly data: JSONObject;\n\n /**\n * Modify the stored config values.\n *\n * #### Notes\n * Updates the local data immediately, sends the change to the server,\n * and updates the local data with the response, and fulfils the promise\n * with that data.\n */\n update(newdata: JSONObject): Promise<JSONObject>;\n\n /**\n * The server settings for the section.\n */\n readonly serverSettings: ServerConnection.ISettings;\n}\n\n/**\n * A manager for config sections.\n */\nexport class ConfigSectionManager implements ConfigSection.IManager {\n /**\n * Create a config section manager.\n */\n constructor(options: ConfigSectionManager.IOptions) {\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n }\n\n /**\n * Create a config section.\n */\n async create(\n options: ConfigSectionManager.ICreateOptions\n ): Promise<IConfigSection> {\n const section = new DefaultConfigSection({\n ...options,\n serverSettings: this.serverSettings\n });\n await section.load();\n return section;\n }\n\n /**\n * The server settings used to make API requests.\n */\n readonly serverSettings: ServerConnection.ISettings;\n}\n\n/**\n * The namespace for ConfigSection statics.\n */\nexport namespace ConfigSection {\n /**\n * Create a config section.\n *\n * @returns A Promise that is fulfilled with the config section is loaded.\n *\n * @deprecated Creating a config section via the `ConfigSection.create()` global has been deprecated and may be removed in a future version.\n * Instead, require the config section manager via the `IConfigSectionManager` token in a plugin.\n */\n export async function create(\n options: ConfigSection.IOptions\n ): Promise<IConfigSection> {\n if (!_configSectionManager) {\n const section = new DefaultConfigSection(options);\n await section.load();\n return section;\n }\n const section = await _configSectionManager.create(options);\n return section;\n }\n\n let _configSectionManager: ConfigSectionManager | undefined;\n\n /**\n * Internal function to set the config section manager.\n *\n * @deprecated This function is an internal helper kept for backward compatiblity.\n * It is not part of the public API and may be removed in a future version.\n */\n export function _setConfigSectionManager(manager: ConfigSectionManager) {\n if (_configSectionManager) {\n throw new Error(\n 'ConfigSectionManager already set. If you would like to create a config section, use the `IConfigSectionManager` token in a plugin.'\n );\n }\n _configSectionManager = manager;\n }\n\n /**\n * The options used to create a config section.\n */\n export interface IOptions extends ConfigSectionManager.ICreateOptions {\n /**\n * The optional server settings.\n */\n serverSettings?: ServerConnection.ISettings;\n }\n\n /**\n * The interface for the build manager.\n */\n export interface IManager extends ConfigSectionManager {}\n}\n\n/**\n * Implementation of the Configurable data section.\n */\nclass DefaultConfigSection implements IConfigSection {\n /**\n * Construct a new config section.\n */\n constructor(options: ConfigSection.IOptions) {\n const settings = (this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings());\n this._url = URLExt.join(\n settings.baseUrl,\n SERVICE_CONFIG_URL,\n encodeURIComponent(options.name)\n );\n }\n\n /**\n * The server settings for the section.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Get the data for this section.\n */\n get data(): JSONObject {\n return this._data;\n }\n\n /**\n * Load the initial data for this section.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async load(): Promise<void> {\n const response = await ServerConnection.makeRequest(\n this._url,\n {},\n this.serverSettings\n );\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n this._data = await response.json();\n }\n\n /**\n * Modify the stored config values.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * Updates the local data immediately, sends the change to the server,\n * and updates the local data with the response, and fulfils the promise\n * with that data.\n */\n async update(newdata: JSONObject): Promise<JSONObject> {\n this._data = { ...this._data, ...newdata };\n const init = {\n method: 'PATCH',\n body: JSON.stringify(newdata)\n };\n const response = await ServerConnection.makeRequest(\n this._url,\n init,\n this.serverSettings\n );\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n this._data = await response.json();\n return this._data;\n }\n\n private _url = 'unknown';\n private _data: JSONObject;\n}\n\n/**\n * Configurable object with defaults.\n */\nexport class ConfigWithDefaults {\n /**\n * Create a new config with defaults.\n */\n constructor(options: ConfigWithDefaults.IOptions) {\n this._section = options.section;\n this._defaults = options.defaults ?? {};\n this._className = options.className ?? '';\n }\n\n /**\n * Get data from the config section or fall back to defaults.\n */\n get(key: string): JSONValue {\n const data = this._classData();\n return key in data ? data[key] : this._defaults[key];\n }\n\n /**\n * Set a config value.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/config).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * Sends the update to the server, and changes our local copy of the data\n * immediately.\n */\n set(key: string, value: JSONValue): Promise<JSONValue> {\n const d: JSONObject = {};\n d[key] = value;\n if (this._className) {\n const d2: JSONObject = {};\n d2[this._className] = d;\n return this._section.update(d2);\n } else {\n return this._section.update(d);\n }\n }\n\n /**\n * Get data from the Section with our classname, if available.\n *\n * #### Notes\n * If we have no classname, get all of the data in the Section\n */\n private _classData(): JSONObject {\n const data = this._section.data;\n if (this._className && this._className in data) {\n return data[this._className] as JSONObject;\n }\n return data;\n }\n\n private _section: IConfigSection;\n private _defaults: JSONObject;\n private _className = '';\n}\n\n/**\n * A namespace for ConfigWithDefaults statics.\n */\nexport namespace ConfigWithDefaults {\n /**\n * The options used to initialize a ConfigWithDefaults object.\n */\n export interface IOptions {\n /**\n * The configuration section.\n */\n section: IConfigSection;\n\n /**\n * The default values.\n */\n defaults?: JSONObject;\n\n /**\n * The optional classname namespace.\n */\n className?: string;\n }\n}\n\n/**\n * A namespace for config section API interfaces.\n */\nexport namespace ConfigSectionManager {\n /**\n * The instantiation options for a config section manager.\n */\n export interface IOptions {\n /**\n * The server settings used to make API requests.\n */\n serverSettings?: ServerConnection.ISettings;\n }\n\n /**\n * The config section create options\n */\n export interface ICreateOptions {\n /**\n * The section name.\n */\n name: string;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { IConnectionStatus } from './tokens';\n\n/**\n * Application connection status\n */\nexport class ConnectionStatus implements IConnectionStatus {\n /**\n * Whether the application is connected to the server or not.\n *\n * #### Notes\n *\n * Every periodic network polling should be paused while this is set\n * to `false`. Extensions should use this value to decide whether to proceed\n * with the polling.\n * The extensions may also set this value to `false` if there is no need to\n * fetch anything from the server backend basing on some conditions\n * (e.g. when an error message dialog is displayed).\n * At the same time, the extensions are responsible for setting this value\n * back to `true`.\n */\n isConnected = true;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module disposable\n */\nimport { ISignal, Signal } from '@lumino/signaling';\n\n/**\n * An object which implements the disposable pattern.\n */\nexport interface IDisposable {\n /**\n * Test whether the object has been disposed.\n *\n * #### Notes\n * This property is always safe to access.\n */\n readonly isDisposed: boolean;\n\n /**\n * Dispose of the resources held by the object.\n *\n * #### Notes\n * If the object's `dispose` method is called more than once, all\n * calls made after the first will be a no-op.\n *\n * #### Undefined Behavior\n * It is undefined behavior to use any functionality of the object\n * after it has been disposed unless otherwise explicitly noted.\n */\n dispose(): void;\n}\n\n/**\n * A disposable object with an observable `disposed` signal.\n */\nexport interface IObservableDisposable extends IDisposable {\n /**\n * A signal emitted when the object is disposed.\n */\n readonly disposed: ISignal<this, void>;\n}\n\n/**\n * A disposable object which delegates to a callback function.\n */\nexport class DisposableDelegate implements IDisposable {\n /**\n * Construct a new disposable delegate.\n *\n * @param fn - The callback function to invoke on dispose.\n */\n constructor(fn: () => void) {\n this._fn = fn;\n }\n\n /**\n * Test whether the delegate has been disposed.\n */\n get isDisposed(): boolean {\n return !this._fn;\n }\n\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose(): void {\n if (!this._fn) {\n return;\n }\n let fn = this._fn;\n this._fn = null;\n fn();\n }\n\n private _fn: (() => void) | null;\n}\n\n/**\n * An observable disposable object which delegates to a callback function.\n */\nexport class ObservableDisposableDelegate\n extends DisposableDelegate\n implements IObservableDisposable\n{\n /**\n * A signal emitted when the delegate is disposed.\n */\n get disposed(): ISignal<this, void> {\n return this._disposed;\n }\n\n /**\n * Dispose of the delegate and invoke the callback function.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n\n private _disposed = new Signal<this, void>(this);\n}\n\n/**\n * An object which manages a collection of disposable items.\n */\nexport class DisposableSet implements IDisposable {\n /**\n * Test whether the set has been disposed.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose(): void {\n if (this._isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._items.forEach(item => {\n item.dispose();\n });\n this._items.clear();\n }\n\n /**\n * Test whether the set contains a specific item.\n *\n * @param item - The item of interest.\n *\n * @returns `true` if the set contains the item, `false` otherwise.\n */\n contains(item: IDisposable): boolean {\n return this._items.has(item);\n }\n\n /**\n * Add a disposable item to the set.\n *\n * @param item - The item to add to the set.\n *\n * #### Notes\n * If the item is already contained in the set, this is a no-op.\n */\n add(item: IDisposable): void {\n this._items.add(item);\n }\n\n /**\n * Remove a disposable item from the set.\n *\n * @param item - The item to remove from the set.\n *\n * #### Notes\n * If the item is not contained in the set, this is a no-op.\n */\n remove(item: IDisposable): void {\n this._items.delete(item);\n }\n\n /**\n * Remove all items from the set.\n */\n clear(): void {\n this._items.clear();\n }\n\n private _isDisposed = false;\n private _items = new Set<IDisposable>();\n}\n\n/**\n * The namespace for the `DisposableSet` class statics.\n */\nexport namespace DisposableSet {\n /**\n * Create a disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n export function from(items: Iterable<IDisposable>): DisposableSet {\n let set = new DisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n}\n\n/**\n * An observable object which manages a collection of disposable items.\n */\nexport class ObservableDisposableSet\n extends DisposableSet\n implements IObservableDisposable\n{\n /**\n * A signal emitted when the set is disposed.\n */\n get disposed(): ISignal<this, void> {\n return this._disposed;\n }\n\n /**\n * Dispose of the set and the items it contains.\n *\n * #### Notes\n * Items are disposed in the order they are added to the set.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n super.dispose();\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n\n private _disposed = new Signal<this, void>(this);\n}\n\n/**\n * The namespace for the `ObservableDisposableSet` class statics.\n */\nexport namespace ObservableDisposableSet {\n /**\n * Create an observable disposable set from an iterable of items.\n *\n * @param items - The iterable object of interest.\n *\n * @returns A new disposable initialized with the given items.\n */\n export function from(items: Iterable<IDisposable>): ObservableDisposableSet {\n let set = new ObservableDisposableSet();\n for (const item of items) {\n set.add(item);\n }\n return set;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n/**\n * Validate a property as being on an object, and optionally\n * of a given type and among a given set of values.\n */\nexport function validateProperty(\n // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\n object: any,\n name: string,\n typeName?: string,\n values: any[] = []\n): void {\n if (!object.hasOwnProperty(name)) {\n throw Error(`Missing property '${name}'`);\n }\n const value = object[name];\n\n if (typeName !== void 0) {\n let valid = true;\n switch (typeName) {\n case 'array':\n valid = Array.isArray(value);\n break;\n case 'object':\n valid = typeof value !== 'undefined';\n break;\n default:\n valid = typeof value === typeName;\n }\n if (!valid) {\n throw new Error(`Property '${name}' is not of type '${typeName}'`);\n }\n\n if (values.length > 0) {\n let valid = true;\n switch (typeName) {\n case 'string':\n case 'number':\n case 'boolean':\n valid = values.includes(value);\n break;\n default:\n valid = values.findIndex(v => v === value) >= 0;\n break;\n }\n if (!valid) {\n throw new Error(\n `Property '${name}' is not one of the valid values ${JSON.stringify(\n values\n )}`\n );\n }\n }\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { Contents } from './index';\nimport { validateProperty } from '../validate';\n\n/**\n * Validate an `Contents.IModel` object.\n */\nexport function validateContentsModel(\n model: Contents.IModel\n): asserts model is Contents.IModel {\n validateProperty(model, 'name', 'string');\n validateProperty(model, 'path', 'string');\n validateProperty(model, 'type', 'string');\n validateProperty(model, 'created', 'string');\n validateProperty(model, 'last_modified', 'string');\n validateProperty(model, 'mimetype', 'object');\n validateProperty(model, 'content', 'object');\n validateProperty(model, 'format', 'object');\n}\n\n/**\n * Validate an `Contents.ICheckpointModel` object.\n */\nexport function validateCheckpointModel(\n model: Contents.ICheckpointModel\n): asserts model is Contents.ICheckpointModel {\n validateProperty(model, 'id', 'string');\n validateProperty(model, 'last_modified', 'string');\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport type { DocumentChange, ISharedDocument, YDocument } from '@jupyter/ydoc';\n\nimport { PathExt, URLExt } from '@jupyterlab/coreutils';\n\nimport { PartialJSONObject } from '@lumino/coreutils';\n\nimport { DisposableDelegate, IDisposable } from '@lumino/disposable';\n\nimport { ISignal, Signal } from '@lumino/signaling';\n\nimport { ServerConnection } from '..';\n\nimport * as validate from './validate';\n\n/**\n * The url for the default drive service.\n */\nconst SERVICE_DRIVE_URL = 'api/contents';\n\n/**\n * The url for the file access.\n */\nconst FILES_URL = 'files';\n\n/**\n * A document factory for registering shared models\n */\nexport type SharedDocumentFactory = (\n options: Contents.ISharedFactoryOptions\n) => YDocument<DocumentChange>;\n\n/**\n * A namespace for contents interfaces.\n */\nexport namespace Contents {\n /**\n * A contents model.\n */\n export interface IModel {\n /**\n * Name of the contents file.\n *\n * #### Notes\n * Equivalent to the last part of the `path` field.\n */\n readonly name: string;\n\n /**\n * The full file path.\n *\n * #### Notes\n * It will *not* start with `/`, and it will be `/`-delimited.\n */\n readonly path: string;\n\n /**\n * The path as returned by the server contents API.\n *\n * #### Notes\n * Differently to `path` it does not include IDrive API prefix.\n */\n readonly serverPath?: string;\n\n /**\n * The type of file.\n */\n readonly type: ContentType;\n\n /**\n * Whether the requester has permission to edit the file.\n */\n readonly writable: boolean;\n\n /**\n * File creation timestamp.\n */\n readonly created: string;\n\n /**\n * Last modified timestamp.\n */\n readonly last_modified: string;\n\n /**\n * Specify the mime-type of file contents.\n *\n * #### Notes\n * Only non-`null` when `content` is present and `type` is `\"file\"`.\n */\n readonly mimetype: string;\n\n /**\n * The optional file content.\n */\n readonly content: any;\n\n /**\n * The chunk of the file upload.\n */\n readonly chunk?: number;\n\n /**\n * The format of the file `content`.\n *\n * #### Notes\n * Only relevant for type: 'file'\n */\n readonly format: FileFormat;\n\n /**\n * The size of then file in bytes.\n */\n readonly size?: number;\n\n /**\n * The indices of the matched characters in the name.\n */\n indices?: ReadonlyArray<number> | null;\n\n /**\n * The hexdigest hash string of content, if requested (otherwise null).\n * It cannot be null if hash_algorithm is defined.\n */\n readonly hash?: string;\n\n /**\n * The algorithm used to compute hash value. It cannot be null if hash is defined.\n */\n readonly hash_algorithm?: string;\n }\n\n /**\n * Validates an IModel, throwing an error if it does not pass.\n */\n export function validateContentsModel(contents: IModel): void {\n validate.validateContentsModel(contents);\n }\n\n /**\n * A contents file type. It can be anything but `jupyter-server`\n * has special treatment for `notebook` and `directory` types.\n * Anything else is considered as `file` type.\n */\n export type ContentType = string;\n\n /**\n * A contents file format. Always `json` for `notebook` and\n * `directory` types. It should be set to either `text` or\n * `base64` for `file` type.\n * See the\n * [jupyter server data model for filesystem entities](https://jupyter-server.readthedocs.io/en/latest/developers/contents.html#filesystem-entities)\n * for more details.\n */\n export type FileFormat = 'json' | 'text' | 'base64' | null;\n\n /**\n * The options used to decode which provider to use.\n */\n export interface IContentProvisionOptions {\n /**\n * The override for the content provider.\n * @experimental\n */\n contentProviderId?: string;\n }\n\n /**\n * The options used to fetch a file.\n */\n export interface IFetchOptions extends IContentProvisionOptions {\n /**\n * The override file type for the request.\n */\n type?: ContentType;\n\n /**\n * The override file format for the request.\n */\n format?: FileFormat;\n\n /**\n * Whether to include the file content.\n *\n * The default is `true`.\n */\n content?: boolean;\n\n /**\n * Whether to include a hash in the response.\n *\n * The default is `false`.\n */\n hash?: boolean;\n }\n\n /**\n * The options used to create a file.\n */\n export interface ICreateOptions {\n /**\n * The directory in which to create the file.\n */\n path?: string;\n\n /**\n * The optional file extension for the new file (e.g. `\".txt\"`).\n *\n * #### Notes\n * This ignored if `type` is `'notebook'`.\n */\n ext?: string;\n\n /**\n * The file type.\n */\n type?: ContentType;\n }\n\n /**\n * Checkpoint model.\n */\n export interface ICheckpointModel {\n /**\n * The unique identifier for the checkpoint.\n */\n readonly id: string;\n\n /**\n * Last modified timestamp.\n */\n readonly last_modified: string;\n }\n\n /**\n * Validates an ICheckpointModel, throwing an error if it does not pass.\n */\n export function validateCheckpointModel(checkpoint: ICheckpointModel): void {\n validate.validateCheckpointModel(checkpoint);\n }\n\n /**\n * The change args for a file change.\n */\n export interface IChangedArgs {\n /**\n * The type of change.\n */\n type: 'new' | 'delete' | 'rename' | 'save';\n\n /**\n * The old contents.\n */\n oldValue: Partial<IModel> | null;\n\n /**\n * The new contents.\n */\n newValue: Partial<IModel> | null;\n }\n\n /**\n * A factory interface for creating `ISharedDocument` objects.\n */\n export interface ISharedFactory {\n /**\n * Whether the IDrive supports real-time collaboration or not.\n * Note: If it is not provided, it is false by default.\n */\n readonly collaborative?: boolean;\n\n /**\n * Create a new `ISharedDocument` instance.\n *\n * It should return `undefined` if the factory is not able to create a `ISharedDocument`.\n */\n createNew(options: ISharedFactoryOptions): ISharedDocument | undefined;\n\n /**\n * Register a SharedDocumentFactory.\n *\n * @param type Document type\n * @param factory Document factory\n */\n registerDocumentFactory?(\n type: Contents.ContentType,\n factory: SharedDocumentFactory\n ): void;\n }\n\n /**\n * The options used to instantiate a ISharedDocument\n */\n export interface ISharedFactoryOptions {\n /**\n * The path of the file.\n */\n path: string;\n /**\n * The format of the document. If null, the document won't be\n * collaborative.\n */\n format: FileFormat;\n /**\n * The content type of the document.\n */\n contentType: ContentType;\n /**\n * Whether the document is collaborative or not.\n *\n * The default value is `true`.\n */\n collaborative?: boolean;\n }\n\n /**\n * The interface for a contents manager.\n */\n export interface IManager extends IDisposable {\n /**\n * A signal emitted when a file operation takes place.\n */\n readonly fileChanged: ISignal<IManager, IChangedArgs>;\n\n /**\n * The server settings associated with the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Add an `IDrive` to the manager.\n */\n addDrive(drive: IDrive): void;\n\n /**\n * Given a path of the form `drive:local/portion/of/it.txt`\n * get the local part of it.\n *\n * @param path the path.\n *\n * @returns The local part of the path.\n */\n localPath(path: string): string;\n\n /**\n * Normalize a global path. Reduces '..' and '.' parts, and removes\n * leading slashes from the local part of the path, while retaining\n * the drive name if it exists.\n *\n * @param path the path.\n *\n * @returns The normalized path.\n */\n normalize(path: string): string;\n\n /**\n * Resolve a global path, starting from the root path. Behaves like\n * posix-path.resolve, with 3 differences:\n * - will never prepend cwd\n * - if root has a drive name, the result is prefixed with \"<drive>:\"\n * - before adding drive name, leading slashes are removed\n *\n * @param path the path.\n *\n * @returns The normalized path.\n */\n resolvePath(root: string, path: string): string;\n\n /**\n * Given a path of the form `drive:local/portion/of/it.txt`\n * get the name of the drive. If the path is missing\n * a drive portion, returns an empty string.\n *\n * @param path the path.\n *\n * @returns The drive name for the path, or the empty string.\n */\n driveName(path: string): string;\n\n /**\n * Given a path, get a shared model IFactory from the\n * relevant backend. Returns `null` if the backend\n * does not provide one.\n */\n getSharedModelFactory(\n path: string,\n options?: IContentProvisionOptions\n ): ISharedFactory | null;\n\n /**\n * Get a file or directory.\n *\n * @param path The path to the file.\n *\n * @param options The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n */\n get(path: string, options?: IFetchOptions): Promise<IModel>;\n\n /**\n * Get an encoded download url given a file path.\n *\n * @param A promise which resolves with the absolute POSIX\n * file path on the server.\n *\n * #### Notes\n * The returned URL may include a query parameter.\n */\n getDownloadUrl(path: string): Promise<string>;\n\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the\n * file is created.\n */\n newUntitled(options?: ICreateOptions): Promise<IModel>;\n\n /**\n * Delete a file.\n *\n * @param path - The path to the file.\n *\n * @returns A promise which resolves when the file is deleted.\n */\n delete(path: string): Promise<void>;\n\n /**\n * Rename a file or directory.\n *\n * @param path - The original file path.\n *\n * @param newPath - The new file path.\n *\n * @returns A promise which resolves with the new file content model when the\n * file is renamed.\n */\n rename(path: string, newPath: string): Promise<IModel>;\n\n /**\n * Save a file.\n *\n * @param path - The desired file path.\n *\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the\n * file is saved.\n */\n save(\n path: string,\n options?: Partial<IModel> & Contents.IContentProvisionOptions\n ): Promise<IModel>;\n\n /**\n * Copy a file into a given directory.\n *\n * @param path - The original file path.\n *\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new content model when the\n * file is copied.\n */\n copy(path: string, toDir: string): Promise<IModel>;\n\n /**\n * Create a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n */\n createCheckpoint(path: string): Promise<ICheckpointModel>;\n\n /**\n * List available checkpoints for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n */\n listCheckpoints(path: string): Promise<ICheckpointModel[]>;\n\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param path - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n */\n restoreCheckpoint(path: string, checkpointID: string): Promise<void>;\n\n /**\n * Delete a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n */\n deleteCheckpoint(path: string, checkpointID: string): Promise<void>;\n }\n\n /**\n * The interface for a network drive that can be mounted\n * in the contents manager.\n */\n export interface IDrive extends IDisposable {\n /**\n * An optional content provider registry, consisting of all the\n * content providers that this drive can use to access files.\n */\n readonly contentProviderRegistry?: IContentProviderRegistry;\n\n /**\n * The name of the drive, which is used at the leading\n * component of file paths.\n */\n readonly name: string;\n\n /**\n * The server settings of the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * An optional shared model factory instance for the\n * drive.\n */\n readonly sharedModelFactory?: ISharedFactory;\n\n /**\n * A signal emitted when a file operation takes place.\n */\n fileChanged: ISignal<IDrive, IChangedArgs>;\n\n /**\n * Get a file or directory.\n *\n * @param localPath The path to the file.\n *\n * @param options The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n */\n get(localPath: string, options?: IFetchOptions): Promise<IModel>;\n\n /**\n * Get an encoded download url given a file path.\n *\n * @returns A promise which resolves with the absolute POSIX\n * file path on the server.\n *\n * #### Notes\n * The returned URL may include a query parameter.\n */\n getDownloadUrl(localPath: string): Promise<string>;\n\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the\n * file is created.\n */\n newUntitled(options?: ICreateOptions): Promise<IModel>;\n\n /**\n * Delete a file.\n *\n * @param localPath - The path to the file.\n *\n * @returns A promise which resolves when the file is deleted.\n */\n delete(localPath: string): Promise<void>;\n\n /**\n * Rename a file or directory.\n *\n * @param oldLocalPath - The original file path.\n *\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with the new file content model when the\n * file is renamed.\n */\n rename(oldLocalPath: string, newLocalPath: string): Promise<IModel>;\n\n /**\n * Save a file.\n *\n * @param localPath - The desired file path.\n *\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the\n * file is saved.\n */\n save(localPath: string, options?: Partial<IModel>): Promise<IModel>;\n\n /**\n * Copy a file into a given directory.\n *\n * @param localPath - The original file path.\n *\n * @param toLocalDir - The destination directory path.\n *\n * @returns A promise which resolves with the new content model when the\n * file is copied.\n */\n copy(localPath: string, toLocalDir: string): Promise<IModel>;\n\n /**\n * Create a checkpoint for a file.\n *\n * @param localPath - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n */\n createCheckpoint(localPath: string): Promise<ICheckpointModel>;\n\n /**\n * List available checkpoints for a file.\n *\n * @param localPath - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n */\n listCheckpoints(localPath: string): Promise<ICheckpointModel[]>;\n\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param localPath - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n */\n restoreCheckpoint(localPath: string, checkpointID: string): Promise<void>;\n\n /**\n * Delete a checkpoint for a file.\n *\n * @param localPath - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n */\n deleteCheckpoint(localPath: string, checkpointID: string): Promise<void>;\n }\n}\n\n/**\n * A contents manager that passes file operations to the server.\n * Multiple servers implementing the `IDrive` interface can be\n * attached to the contents manager, so that the same session can\n * perform file operations on multiple backends.\n *\n * This includes checkpointing with the normal file operations.\n */\nexport class ContentsManager implements Contents.IManager {\n /**\n * Construct a new contents manager object.\n *\n * @param options - The options used to initialize the object.\n */\n constructor(options: ContentsManager.IOptions = {}) {\n const serverSettings = (this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings());\n this._defaultDrive = options.defaultDrive ?? new Drive({ serverSettings });\n this._defaultDrive.fileChanged.connect(this._onFileChanged, this);\n }\n\n /**\n * The default drive associated with the manager.\n */\n get defaultDrive(): Contents.IDrive {\n return this._defaultDrive;\n }\n\n /**\n * The server settings associated with the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * A signal emitted when a file operation takes place.\n */\n get fileChanged(): ISignal<this, Contents.IChangedArgs> {\n return this._fileChanged;\n }\n\n /**\n * Test whether the manager has been disposed.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * Dispose of the resources held by the manager.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n Signal.clearData(this);\n }\n\n /**\n * Add an `IDrive` to the manager.\n */\n addDrive(drive: Contents.IDrive): void {\n this._additionalDrives.set(drive.name, drive);\n drive.fileChanged.connect(this._onFileChanged, this);\n }\n\n /**\n * Given a path, get a shared model factory from the relevant backend.\n * The factory defined on content provider best matching the given path\n * takes precedence over the factory defined on the drive as a whole.\n * Returns `null` if the backend does not provide one.\n */\n getSharedModelFactory(\n path: string,\n options?: Contents.IContentProvisionOptions\n ): Contents.ISharedFactory | null {\n const [drive] = this._driveForPath(path);\n const provider = drive.contentProviderRegistry?.getProvider(\n options?.contentProviderId\n );\n if (provider?.sharedModelFactory) {\n return provider.sharedModelFactory;\n }\n return drive.sharedModelFactory ?? null;\n }\n\n /**\n * Given a path of the form `drive:local/portion/of/it.txt`\n * get the local part of it.\n *\n * @param path the path.\n *\n * @returns The local part of the path.\n */\n localPath(path: string): string {\n const parts = path.split('/');\n const firstParts = parts[0].split(':');\n if (firstParts.length === 1 || !this._additionalDrives.has(firstParts[0])) {\n return PathExt.removeSlash(path);\n }\n return PathExt.join(firstParts.slice(1).join(':'), ...parts.slice(1));\n }\n\n /**\n * Normalize a global path. Reduces '..' and '.' parts, and removes\n * leading slashes from the local part of the path, while retaining\n * the drive name if it exists.\n *\n * @param path the path.\n *\n * @returns The normalized path.\n */\n normalize(path: string): string {\n const parts = path.split(':');\n if (parts.length === 1) {\n return PathExt.normalize(path);\n }\n return `${parts[0]}:${PathExt.normalize(parts.slice(1).join(':'))}`;\n }\n\n /**\n * Resolve a global path, starting from the root path. Behaves like\n * posix-path.resolve, with 3 differences:\n * - will never prepend cwd\n * - if root has a drive name, the result is prefixed with \"<drive>:\"\n * - before adding drive name, leading slashes are removed\n *\n * @param path the path.\n *\n * @returns The normalized path.\n */\n resolvePath(root: string, path: string): string {\n const driveName = this.driveName(root);\n const localPath = this.localPath(root);\n const resolved = PathExt.resolve('/', localPath, path);\n return driveName ? `${driveName}:${resolved}` : resolved;\n }\n\n /**\n * Given a path of the form `drive:local/portion/of/it.txt`\n * get the name of the drive. If the path is missing\n * a drive portion, returns an empty string.\n *\n * @param path the path.\n *\n * @returns The drive name for the path, or the empty string.\n */\n driveName(path: string): string {\n const parts = path.split('/');\n const firstParts = parts[0].split(':');\n if (firstParts.length === 1) {\n return '';\n }\n if (this._additionalDrives.has(firstParts[0])) {\n return firstParts[0];\n }\n return '';\n }\n\n /**\n * Get a file or directory.\n *\n * @param path The path to the file.\n *\n * @param options The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n */\n get(\n path: string,\n options?: Contents.IFetchOptions\n ): Promise<Contents.IModel> {\n const [drive, localPath] = this._driveForPath(path);\n return drive.get(localPath, options).then(contentsModel => {\n const listing: Contents.IModel[] = [];\n if (contentsModel.type === 'directory' && contentsModel.content) {\n for (const item of contentsModel.content) {\n listing.push({ ...item, path: this._toGlobalPath(drive, item.path) });\n }\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive, localPath),\n content: listing,\n serverPath: contentsModel.path\n } as Contents.IModel;\n } else {\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive, localPath),\n serverPath: contentsModel.path\n } as Contents.IModel;\n }\n });\n }\n\n /**\n * Get an encoded download url given a file path.\n *\n * @param path - An absolute POSIX file path on the server.\n *\n * #### Notes\n * It is expected that the path contains no relative paths.\n *\n * The returned URL may include a query parameter.\n */\n getDownloadUrl(path: string): Promise<string> {\n const [drive, localPath] = this._driveForPath(path);\n return drive.getDownloadUrl(localPath);\n }\n\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the\n * file is created.\n */\n newUntitled(options: Contents.ICreateOptions = {}): Promise<Contents.IModel> {\n if (options.path) {\n const globalPath = this.normalize(options.path);\n const [drive, localPath] = this._driveForPath(globalPath);\n return drive\n .newUntitled({ ...options, path: localPath })\n .then(contentsModel => {\n return {\n ...contentsModel,\n path: PathExt.join(globalPath, contentsModel.name),\n serverPath: contentsModel.path\n } as Contents.IModel;\n });\n } else {\n return this._defaultDrive.newUntitled(options);\n }\n }\n\n /**\n * Delete a file.\n *\n * @param path - The path to the file.\n *\n * @returns A promise which resolves when the file is deleted.\n */\n delete(path: string): Promise<void> {\n const [drive, localPath] = this._driveForPath(path);\n return drive.delete(localPath);\n }\n\n /**\n * Rename a file or directory.\n *\n * @param path - The original file path.\n *\n * @param newPath - The new file path.\n *\n * @returns A promise which resolves with the new file contents model when\n * the file is renamed.\n */\n rename(path: string, newPath: string): Promise<Contents.IModel> {\n const [drive1, path1] = this._driveForPath(path);\n const [drive2, path2] = this._driveForPath(newPath);\n if (drive1 !== drive2) {\n throw Error('ContentsManager: renaming files must occur within a Drive');\n }\n return drive1.rename(path1, path2).then(contentsModel => {\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive1, path2),\n serverPath: contentsModel.path\n } as Contents.IModel;\n });\n }\n\n /**\n * Save a file.\n *\n * @param path - The desired file path.\n *\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the\n * file is saved.\n *\n * #### Notes\n * Ensure that `model.content` is populated for the file.\n */\n save(\n path: string,\n options: Partial<Contents.IModel> = {}\n ): Promise<Contents.IModel> {\n const globalPath = this.normalize(path);\n const [drive, localPath] = this._driveForPath(path);\n return drive\n .save(localPath, { ...options, path: localPath })\n .then(contentsModel => {\n return {\n ...contentsModel,\n path: globalPath,\n serverPath: contentsModel.path\n } as Contents.IModel;\n });\n }\n\n /**\n * Copy a file into a given directory.\n *\n * @param path - The original file path.\n *\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n */\n copy(fromFile: string, toDir: string): Promise<Contents.IModel> {\n const [drive1, path1] = this._driveForPath(fromFile);\n const [drive2, path2] = this._driveForPath(toDir);\n if (drive1 === drive2) {\n return drive1.copy(path1, path2).then(contentsModel => {\n return {\n ...contentsModel,\n path: this._toGlobalPath(drive1, contentsModel.path),\n serverPath: contentsModel.path\n } as Contents.IModel;\n });\n } else {\n throw Error('Copying files between drives is not currently implemented');\n }\n }\n\n /**\n * Create a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n */\n createCheckpoint(path: string): Promise<Contents.ICheckpointModel> {\n const [drive, localPath] = this._driveForPath(path);\n return drive.createCheckpoint(localPath);\n }\n\n /**\n * List available checkpoints for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n */\n listCheckpoints(path: string): Promise<Contents.ICheckpointModel[]> {\n const [drive, localPath] = this._driveForPath(path);\n return drive.listCheckpoints(localPath);\n }\n\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param path - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n */\n restoreCheckpoint(path: string, checkpointID: string): Promise<void> {\n const [drive, localPath] = this._driveForPath(path);\n return drive.restoreCheckpoint(localPath, checkpointID);\n }\n\n /**\n * Delete a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n */\n deleteCheckpoint(path: string, checkpointID: string): Promise<void> {\n const [drive, localPath] = this._driveForPath(path);\n return drive.deleteCheckpoint(localPath, checkpointID);\n }\n\n /**\n * Given a drive and a local path, construct a fully qualified\n * path. The inverse of `_driveForPath`.\n *\n * @param drive an `IDrive`.\n *\n * @param localPath the local path on the drive.\n *\n * @returns the fully qualified path.\n */\n private _toGlobalPath(drive: Contents.IDrive, localPath: string): string {\n if (drive === this._defaultDrive) {\n return PathExt.removeSlash(localPath);\n } else {\n return `${drive.name}:${PathExt.removeSlash(localPath)}`;\n }\n }\n\n /**\n * Given a path, get the `IDrive to which it refers,\n * where the path satisfies the pattern\n * `'driveName:path/to/file'`. If there is no `driveName`\n * prepended to the path, it returns the default drive.\n *\n * @param path a path to a file.\n *\n * @returns A tuple containing an `IDrive` object for the path,\n * and a local path for that drive.\n */\n private _driveForPath(path: string): [Contents.IDrive, string] {\n const driveName = this.driveName(path);\n const localPath = this.localPath(path);\n if (driveName) {\n return [this._additionalDrives.get(driveName)!, localPath];\n } else {\n return [this._defaultDrive, localPath];\n }\n }\n\n /**\n * Respond to fileChanged signals from the drives attached to\n * the manager. This prepends the drive name to the path if necessary,\n * and then forwards the signal.\n */\n private _onFileChanged(sender: Contents.IDrive, args: Contents.IChangedArgs) {\n if (sender === this._defaultDrive) {\n this._fileChanged.emit(args);\n } else {\n let newValue: Partial<Contents.IModel> | null = null;\n let oldValue: Partial<Contents.IModel> | null = null;\n if (args.newValue?.path) {\n newValue = {\n ...args.newValue,\n path: this._toGlobalPath(sender, args.newValue.path)\n };\n }\n if (args.oldValue?.path) {\n oldValue = {\n ...args.oldValue,\n path: this._toGlobalPath(sender, args.oldValue.path)\n };\n }\n this._fileChanged.emit({\n type: args.type,\n newValue,\n oldValue\n });\n }\n }\n\n private _isDisposed = false;\n private _additionalDrives = new Map<string, Contents.IDrive>();\n private _defaultDrive: Contents.IDrive;\n private _fileChanged = new Signal<this, Contents.IChangedArgs>(this);\n}\n\n/**\n * A default implementation for an `IDrive`, talking to the\n * server using the Jupyter REST API.\n */\nexport class Drive implements Contents.IDrive {\n /**\n * Construct a new contents manager object.\n *\n * @param options - The options used to initialize the object.\n */\n constructor(options: Drive.IOptions = {}) {\n this.name = options.name ?? 'Default';\n this._apiEndpoint = options.apiEndpoint ?? SERVICE_DRIVE_URL;\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n const restContentProvider = new RestContentProvider({\n apiEndpoint: this._apiEndpoint,\n serverSettings: this.serverSettings\n });\n this.contentProviderRegistry = new ContentProviderRegistry({\n defaultProvider: restContentProvider\n });\n this.contentProviderRegistry.fileChanged.connect(\n (registry, change: Contents.IChangedArgs) => {\n this._fileChanged.emit(change);\n }\n );\n }\n\n /**\n * Content provider registry.\n * @experimental\n */\n readonly contentProviderRegistry: IContentProviderRegistry;\n\n /**\n * The name of the drive, which is used at the leading\n * component of file paths.\n */\n readonly name: string;\n\n /**\n * A signal emitted when a file operation takes place.\n */\n get fileChanged(): ISignal<this, Contents.IChangedArgs> {\n return this._fileChanged;\n }\n\n /**\n * The server settings of the drive.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Test whether the manager has been disposed.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * Dispose of the resources held by the manager.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n Signal.clearData(this);\n }\n\n /**\n * Get a file or directory.\n *\n * @param localPath The path to the file.\n *\n * @param options The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n *\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async get(\n localPath: string,\n options?: Contents.IFetchOptions\n ): Promise<Contents.IModel> {\n const contentProvider = this.contentProviderRegistry.getProvider(\n options?.contentProviderId\n );\n return contentProvider.get(localPath, options);\n }\n\n /**\n * Get an encoded download url given a file path.\n *\n * @param localPath - An absolute POSIX file path on the server.\n *\n * #### Notes\n * It is expected that the path contains no relative paths.\n *\n * The returned URL may include a query parameter.\n */\n getDownloadUrl(localPath: string): Promise<string> {\n const baseUrl = this.serverSettings.baseUrl;\n let url = URLExt.join(baseUrl, FILES_URL, URLExt.encodeParts(localPath));\n let cookie = '';\n try {\n cookie = document.cookie;\n } catch (e) {\n // e.g. SecurityError in case of CSP Sandbox\n }\n const xsrfTokenMatch = cookie.match('\\\\b_xsrf=([^;]*)\\\\b');\n if (xsrfTokenMatch) {\n const fullUrl = new URL(url);\n fullUrl.searchParams.append('_xsrf', xsrfTokenMatch[1]);\n url = fullUrl.toString();\n }\n return Promise.resolve(url);\n }\n\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the\n * file is created.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async newUntitled(\n options: Contents.ICreateOptions = {}\n ): Promise<Contents.IModel> {\n let body = '{}';\n if (options) {\n if (options.ext) {\n options.ext = Private.normalizeExtension(options.ext);\n }\n body = JSON.stringify(options);\n }\n\n const settings = this.serverSettings;\n const url = this._getUrl(options.path ?? '');\n const init = {\n method: 'POST',\n body\n };\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'new',\n oldValue: null,\n newValue: data\n });\n return data;\n }\n\n /**\n * Delete a file.\n *\n * @param localPath - The path to the file.\n *\n * @returns A promise which resolves when the file is deleted.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).\n */\n async delete(localPath: string): Promise<void> {\n const url = this._getUrl(localPath);\n const settings = this.serverSettings;\n const init = { method: 'DELETE' };\n const response = await ServerConnection.makeRequest(url, init, settings);\n // TODO: update IPEP27 to specify errors more precisely, so\n // that error types can be detected here with certainty.\n if (response.status !== 204) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n this._fileChanged.emit({\n type: 'delete',\n oldValue: { path: localPath },\n newValue: null\n });\n }\n\n /**\n * Rename a file or directory.\n *\n * @param oldLocalPath - The original file path.\n *\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with the new file contents model when\n * the file is renamed.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async rename(\n oldLocalPath: string,\n newLocalPath: string\n ): Promise<Contents.IModel> {\n const settings = this.serverSettings;\n const url = this._getUrl(oldLocalPath);\n const init = {\n method: 'PATCH',\n body: JSON.stringify({ path: newLocalPath })\n };\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'rename',\n oldValue: { path: oldLocalPath },\n newValue: data\n });\n return data;\n }\n\n /**\n * Save a file.\n *\n * @param localPath - The desired file path.\n *\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the\n * file is saved.\n *\n * #### Notes\n * Ensure that `model.content` is populated for the file.\n *\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async save(\n localPath: string,\n options: Partial<Contents.IModel> & Contents.IContentProvisionOptions = {}\n ): Promise<Contents.IModel> {\n const contentProvider = this.contentProviderRegistry.getProvider(\n options?.contentProviderId\n );\n const data = await contentProvider.save(localPath, options);\n this._fileChanged.emit({\n type: 'save',\n oldValue: null,\n newValue: data\n });\n return data;\n }\n\n /**\n * Copy a file into a given directory.\n *\n * @param localPath - The original file path.\n *\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n *\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async copy(fromFile: string, toDir: string): Promise<Contents.IModel> {\n const settings = this.serverSettings;\n const url = this._getUrl(toDir);\n const init = {\n method: 'POST',\n body: JSON.stringify({ copy_from: fromFile })\n };\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n this._fileChanged.emit({\n type: 'new',\n oldValue: null,\n newValue: data\n });\n return data;\n }\n\n /**\n * Create a checkpoint for a file.\n *\n * @param localPath - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async createCheckpoint(\n localPath: string\n ): Promise<Contents.ICheckpointModel> {\n const url = this._getUrl(localPath, 'checkpoints');\n const init = { method: 'POST' };\n const response = await ServerConnection.makeRequest(\n url,\n init,\n this.serverSettings\n );\n if (response.status !== 201) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateCheckpointModel(data);\n return data;\n }\n\n /**\n * List available checkpoints for a file.\n *\n * @param localPath - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async listCheckpoints(\n localPath: string\n ): Promise<Contents.ICheckpointModel[]> {\n const url = this._getUrl(localPath, 'checkpoints');\n const response = await ServerConnection.makeRequest(\n url,\n {},\n this.serverSettings\n );\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error('Invalid Checkpoint list');\n }\n for (let i = 0; i < data.length; i++) {\n validate.validateCheckpointModel(data[i]);\n }\n return data;\n }\n\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param localPath - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).\n */\n async restoreCheckpoint(\n localPath: string,\n checkpointID: string\n ): Promise<void> {\n const url = this._getUrl(localPath, 'checkpoints', checkpointID);\n const init = { method: 'POST' };\n const response = await ServerConnection.makeRequest(\n url,\n init,\n this.serverSettings\n );\n if (response.status !== 204) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n }\n\n /**\n * Delete a checkpoint for a file.\n *\n * @param localPath - The path of the file.\n *\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).\n */\n async deleteCheckpoint(\n localPath: string,\n checkpointID: string\n ): Promise<void> {\n const url = this._getUrl(localPath, 'checkpoints', checkpointID);\n const init = { method: 'DELETE' };\n const response = await ServerConnection.makeRequest(\n url,\n init,\n this.serverSettings\n );\n if (response.status !== 204) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n }\n\n /**\n * Get a REST url for a file given a path.\n */\n private _getUrl(...args: string[]): string {\n const parts = args.map(path => URLExt.encodeParts(path));\n const baseUrl = this.serverSettings.baseUrl;\n return URLExt.join(baseUrl, this._apiEndpoint, ...parts);\n }\n\n private _apiEndpoint: string;\n private _isDisposed = false;\n private _fileChanged = new Signal<this, Contents.IChangedArgs>(this);\n}\n\n/**\n * A namespace for ContentsManager statics.\n */\nexport namespace ContentsManager {\n /**\n * The options used to initialize a contents manager.\n */\n export interface IOptions {\n /**\n * The default drive backend for the contents manager.\n */\n defaultDrive?: Contents.IDrive;\n\n /**\n * The server settings associated with the manager.\n */\n serverSettings?: ServerConnection.ISettings;\n }\n}\n\n/**\n * A namespace for Drive statics.\n */\nexport namespace Drive {\n /**\n * The options used to initialize a `Drive`.\n */\n export interface IOptions {\n /**\n * The name for the `Drive`, which is used in file\n * paths to disambiguate it from other drives.\n */\n name?: string;\n\n /**\n * The server settings for the server.\n */\n serverSettings?: ServerConnection.ISettings;\n\n /**\n * A REST endpoint for drive requests.\n * If not given, defaults to the Jupyter\n * REST API given by [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents).\n */\n apiEndpoint?: string;\n }\n}\n\n/**\n * A namespace for module private data.\n */\nnamespace Private {\n /**\n * Normalize a file extension to be of the type `'.foo'`.\n *\n * Adds a leading dot if not present and converts to lower case.\n */\n export function normalizeExtension(extension: string): string {\n if (extension.length > 0 && extension.indexOf('.') !== 0) {\n extension = `.${extension}`;\n }\n return extension;\n }\n}\n\n/**\n * The default registry of content providers.\n */\nclass ContentProviderRegistry implements IContentProviderRegistry {\n /**\n * Construct a new content provider registry.\n *\n * @param options - The options used to initialize the registry.\n */\n constructor(options: ContentProviderRegistry.IOptions) {\n this.register('default', options.defaultProvider);\n this._defaultProvider = options.defaultProvider;\n }\n\n /**\n * Add a content provider to the registry.\n *\n * @param identifier - The identifier of the provider; it can be reused between drives.\n * @param provider - The content provider to register.\n */\n register(identifier: string, provider: IContentProvider): IDisposable {\n if (this._providers.has(identifier)) {\n throw Error(\n `Provider with ${identifier} identifier was already registered on this drive`\n );\n }\n this._providers.set(identifier, provider);\n\n const fileChangedProxy = (\n _provider: IContentProvider,\n change: Contents.IChangedArgs\n ) => {\n this._fileChanged.emit(change);\n };\n if (provider.fileChanged) {\n provider.fileChanged.connect(fileChangedProxy);\n }\n\n return new DisposableDelegate(() => {\n if (provider.fileChanged) {\n provider.fileChanged.disconnect(fileChangedProxy);\n }\n\n if (this._providers.has(identifier)) {\n this._providers.delete(identifier);\n }\n });\n }\n\n /**\n * Get a content provider matching provided identifier.\n *\n * If no identifier is provided, return the default provider.\n * Throws an error if a provider with given identifier is not found.\n *\n * @param identifier - identifier of the content provider.\n */\n getProvider(identifier?: string): IContentProvider {\n if (!identifier) {\n return this._defaultProvider;\n }\n const provider = this._providers.get(identifier);\n if (!provider) {\n throw Error(`Provider ${identifier} is not registered`);\n }\n return provider;\n }\n\n /**\n * A proxy of the file changed signal for all the providers.\n */\n get fileChanged(): ISignal<IContentProviderRegistry, Contents.IChangedArgs> {\n return this._fileChanged;\n }\n\n private _providers: Map<string, IContentProvider> = new Map();\n private _defaultProvider: IContentProvider;\n private _fileChanged = new Signal<\n IContentProviderRegistry,\n Contents.IChangedArgs\n >(this);\n}\n\nnamespace ContentProviderRegistry {\n /**\n * Initialization options for `ContentProviderRegistry`.\n */\n export interface IOptions {\n /**\n * Default provider for the registry.\n */\n defaultProvider: IContentProvider;\n }\n}\n\n/**\n * A content provider using the Jupyter REST API.\n */\nexport class RestContentProvider implements IContentProvider {\n constructor(options: RestContentProvider.IOptions) {\n this._options = options;\n }\n\n /**\n * Get a file or directory.\n *\n * @param localPath The path to the file.\n *\n * @param options The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n *\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async get(\n localPath: string,\n options?: Contents.IFetchOptions\n ): Promise<Contents.IModel> {\n let url = this._getUrl(localPath);\n if (options) {\n // The notebook type cannot take a format option.\n if (options.type === 'notebook') {\n delete options['format'];\n }\n const content = options.content ? '1' : '0';\n const hash = options.hash ? '1' : '0';\n const params: PartialJSONObject = { ...options, content, hash };\n url += URLExt.objectToQueryString(params);\n }\n\n const settings = this._options.serverSettings;\n const response = await ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n return data;\n }\n\n /**\n * Save a file.\n *\n * @param localPath - The desired file path.\n *\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the\n * file is saved.\n *\n * #### Notes\n * Ensure that `model.content` is populated for the file.\n *\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/contents) and validates the response model.\n */\n async save(\n localPath: string,\n options: Partial<Contents.IModel> = {}\n ): Promise<Contents.IModel> {\n const settings = this._options.serverSettings;\n const url = this._getUrl(localPath);\n const init = {\n method: 'PUT',\n body: JSON.stringify(options)\n };\n const response = await ServerConnection.makeRequest(url, init, settings);\n // will return 200 for an existing file and 201 for a new file\n if (response.status !== 200 && response.status !== 201) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validate.validateContentsModel(data);\n return data;\n }\n\n /**\n * Get a REST url for a file given a path.\n */\n private _getUrl(...args: string[]): string {\n const parts = args.map(path => URLExt.encodeParts(path));\n const baseUrl = this._options.serverSettings.baseUrl;\n return URLExt.join(baseUrl, this._options.apiEndpoint, ...parts);\n }\n\n private _options: RestContentProvider.IOptions;\n}\n\nexport namespace RestContentProvider {\n /**\n * Initialization options for the REST content provider.\n */\n export interface IOptions {\n apiEndpoint: string;\n serverSettings: ServerConnection.ISettings;\n }\n}\n\n/**\n * Registry of content providers.\n * @experimental\n */\nexport interface IContentProviderRegistry {\n /**\n * Add a content provider to the registry.\n *\n * @param identifier - The identifier of the provider; it can be reused between drives.\n * @param provider - The content provider to register.\n */\n register(identifier: string, provider: IContentProvider): IDisposable;\n\n /**\n * Get a content provider matching provided identifier.\n *\n * If no identifier is provided, return the default provider.\n * Throws an error if a provider with given identifier is not found.\n *\n * @param identifier - identifier of the content provider.\n */\n getProvider(identifier?: string): IContentProvider;\n\n /**\n * A proxy of the file changed signal for all the providers.\n */\n readonly fileChanged: ISignal<\n IContentProviderRegistry,\n Contents.IChangedArgs\n >;\n}\n\n/**\n * The content provider interface.\n *\n * Content providers are similar to drives, but instead of a data storage,\n * they represent the data retrieval method (think protocol). Each drive\n * can have multiple providers registered, and each provider ID can be\n * used to register an instance of such provider across multiple drives.\n *\n * To provision file contents via a content provider:\n * - register a widget factory with `contentProviderId` option\n * - register a file type with in the document registry with `contentProviderId` option\n *\n * @experimental\n */\nexport interface IContentProvider\n extends Pick<Contents.IDrive, 'get' | 'save' | 'sharedModelFactory'> {\n /**\n * A signal emitted when a file operation takes place.\n *\n * Content providers which perform save operations initiated on the backend\n * may emit this signal to communicate a change in the file contents.\n */\n readonly fileChanged?: ISignal<IContentProvider, Contents.IChangedArgs>;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { JSONExt, PromiseDelegate } from '@lumino/coreutils';\n\nimport { IObservableDisposable } from '@lumino/disposable';\n\nimport { ISignal, Signal } from '@lumino/signaling';\n\nimport { IPoll } from './index';\n\n/**\n * A class that wraps an asynchronous function to poll at a regular interval\n * with exponential increases to the interval length if the poll fails.\n *\n * @typeparam T - The resolved type of the factory's promises.\n * Defaults to `any`.\n *\n * @typeparam U - The rejected type of the factory's promises.\n * Defaults to `any`.\n *\n * @typeparam V - An optional type to extend the phases supported by a poll.\n * Defaults to `standby`, which already exists in the `Phase` type.\n */\nexport class Poll<T = any, U = any, V extends string = 'standby'>\n implements IObservableDisposable, IPoll<T, U, V>\n{\n /**\n * Instantiate a new poll with exponential backoff in case of failure.\n *\n * @param options - The poll instantiation options.\n */\n constructor(options: Poll.IOptions<T, U, V>) {\n this._factory = options.factory;\n this._linger = options.linger ?? Private.DEFAULT_LINGER;\n this._standby = options.standby || Private.DEFAULT_STANDBY;\n this._state = { ...Private.DEFAULT_STATE, timestamp: new Date().getTime() };\n\n // Normalize poll frequency `max` to be the greater of\n // default `max`, `options.frequency.max`, or `options.frequency.interval`.\n const frequency = options.frequency || {};\n const max = Math.max(\n frequency.interval || 0,\n frequency.max || 0,\n Private.DEFAULT_FREQUENCY.max\n );\n this.frequency = { ...Private.DEFAULT_FREQUENCY, ...frequency, ...{ max } };\n\n this.name = options.name || Private.DEFAULT_NAME;\n\n if ('auto' in options ? options.auto : true) {\n setTimeout(() => this.start());\n }\n }\n\n /**\n * The name of the poll.\n */\n readonly name: string;\n\n /**\n * A signal emitted when the poll is disposed.\n */\n get disposed(): ISignal<this, void> {\n return this._disposed;\n }\n\n /**\n * The polling frequency parameters.\n */\n get frequency(): IPoll.Frequency {\n return this._frequency;\n }\n set frequency(frequency: IPoll.Frequency) {\n if (this.isDisposed || JSONExt.deepEqual(frequency, this.frequency || {})) {\n return;\n }\n\n let { backoff, interval, max } = frequency;\n\n interval = Math.round(interval);\n max = Math.round(max);\n\n if (typeof backoff === 'number' && backoff < 1) {\n throw new Error('Poll backoff growth factor must be at least 1');\n }\n\n if ((interval < 0 || interval > max) && interval !== Poll.NEVER) {\n throw new Error('Poll interval must be between 0 and max');\n }\n\n if (max > Poll.MAX_INTERVAL && max !== Poll.NEVER) {\n throw new Error(`Max interval must be less than ${Poll.MAX_INTERVAL}`);\n }\n\n this._frequency = { backoff, interval, max };\n }\n\n /**\n * Whether the poll is disposed.\n */\n get isDisposed(): boolean {\n return this.state.phase === 'disposed';\n }\n\n /**\n * Indicates when the poll switches to standby.\n */\n get standby(): Poll.Standby | (() => boolean | Poll.Standby) {\n return this._standby;\n }\n set standby(standby: Poll.Standby | (() => boolean | Poll.Standby)) {\n if (this.isDisposed || this.standby === standby) {\n return;\n }\n\n this._standby = standby;\n }\n\n /**\n * The poll state, which is the content of the current poll tick.\n */\n get state(): IPoll.State<T, U, V> {\n return this._state;\n }\n\n /**\n * A promise that resolves when the poll next ticks.\n */\n get tick(): Promise<this> {\n return this._tick.promise;\n }\n\n /**\n * A signal emitted when the poll ticks and fires off a new request.\n */\n get ticked(): ISignal<this, IPoll.State<T, U, V>> {\n return this._ticked;\n }\n\n /**\n * Return an async iterator that yields every tick.\n */\n async *[Symbol.asyncIterator](): AsyncIterableIterator<IPoll.State<T, U, V>> {\n while (!this.isDisposed) {\n yield this.state;\n await this.tick.catch(() => undefined);\n }\n }\n\n /**\n * Dispose the poll.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n\n this._state = {\n ...Private.DISPOSED_STATE,\n timestamp: new Date().getTime()\n };\n this._tick.promise.catch(_ => undefined);\n this._tick.reject(new Error(`Poll (${this.name}) is disposed.`));\n this._disposed.emit(undefined);\n Signal.clearData(this);\n }\n\n /**\n * Refreshes the poll. Schedules `refreshed` tick if necessary.\n *\n * @returns A promise that resolves after tick is scheduled and never rejects.\n *\n * #### Notes\n * The returned promise resolves after the tick is scheduled, but before\n * the polling action is run. To wait until after the poll action executes,\n * await the `poll.tick` promise: `await poll.refresh(); await poll.tick;`\n */\n refresh(): Promise<void> {\n return this.schedule({\n cancel: ({ phase }) => phase === 'refreshed',\n interval: Poll.IMMEDIATE,\n phase: 'refreshed'\n });\n }\n\n /**\n * Schedule the next poll tick.\n *\n * @param next - The next poll state data to schedule. Defaults to standby.\n *\n * @param next.cancel - Cancels state transition if function returns `true`.\n *\n * @returns A promise that resolves when the next poll state is active.\n *\n * #### Notes\n * This method is not meant to be invoked by user code typically. It is public\n * to allow poll instances to be composed into classes that schedule ticks.\n */\n async schedule(\n next: Partial<\n IPoll.State<T, U, V> & { cancel: (last: IPoll.State<T, U, V>) => boolean }\n > = {}\n ): Promise<void> {\n if (this.isDisposed) {\n return;\n }\n\n // Check if the phase transition should be canceled.\n if (next.cancel && next.cancel(this.state)) {\n return;\n }\n\n // Update poll state.\n const pending = this._tick;\n const scheduled = new PromiseDelegate<this>();\n const state = {\n interval: this.frequency.interval,\n payload: null,\n phase: 'standby',\n timestamp: new Date().getTime(),\n ...next\n } as IPoll.State<T, U, V>;\n this._state = state;\n this._tick = scheduled;\n\n // Clear the schedule if possible.\n clearTimeout(this._timeout);\n\n // Emit ticked signal, resolve pending promise, and await its settlement.\n this._ticked.emit(this.state);\n pending.resolve(this);\n await pending.promise;\n\n if (state.interval === Poll.NEVER) {\n this._timeout = undefined;\n return;\n }\n\n // Schedule next execution and cache its timeout handle.\n const execute = () => {\n if (this.isDisposed || this.tick !== scheduled.promise) {\n return;\n }\n\n this._execute();\n };\n\n // Cache the handle in case it needs to be unscheduled.\n this._timeout = setTimeout(execute, state.interval);\n }\n\n /**\n * Starts the poll. Schedules `started` tick if necessary.\n *\n * @returns A promise that resolves after tick is scheduled and never rejects.\n */\n start(): Promise<void> {\n return this.schedule({\n cancel: ({ phase }) =>\n phase !== 'constructed' && phase !== 'standby' && phase !== 'stopped',\n interval: Poll.IMMEDIATE,\n phase: 'started'\n });\n }\n\n /**\n * Stops the poll. Schedules `stopped` tick if necessary.\n *\n * @returns A promise that resolves after tick is scheduled and never rejects.\n */\n stop(): Promise<void> {\n return this.schedule({\n cancel: ({ phase }) => phase === 'stopped',\n interval: Poll.NEVER,\n phase: 'stopped'\n });\n }\n\n /**\n * Whether the poll is hidden.\n *\n * #### Notes\n * This property is only relevant in a browser context.\n */\n protected get hidden(): boolean {\n return Private.hidden;\n }\n\n /**\n * Execute a new poll factory promise or stand by if necessary.\n */\n private _execute(): void {\n let standby =\n typeof this.standby === 'function' ? this.standby() : this.standby;\n\n // Check if execution should proceed, linger, or stand by.\n if (standby === 'never') {\n standby = false;\n } else if (standby === 'when-hidden') {\n if (this.hidden) {\n standby = ++this._lingered > this._linger;\n } else {\n this._lingered = 0;\n standby = false;\n }\n }\n\n // If in standby mode schedule next tick without calling the factory.\n if (standby) {\n void this.schedule();\n return;\n }\n\n const pending = this.tick;\n\n this._factory(this.state)\n .then((resolved: T) => {\n if (this.isDisposed || this.tick !== pending) {\n return;\n }\n\n void this.schedule({\n payload: resolved,\n phase: this.state.phase === 'rejected' ? 'reconnected' : 'resolved'\n });\n })\n .catch((rejected: U) => {\n if (this.isDisposed || this.tick !== pending) {\n return;\n }\n\n void this.schedule({\n interval: Private.sleep(this.frequency, this.state),\n payload: rejected,\n phase: 'rejected'\n });\n });\n }\n\n private _disposed = new Signal<this, void>(this);\n private _factory: Poll.Factory<T, U, V>;\n private _frequency: IPoll.Frequency;\n private _linger: number;\n private _lingered = 0;\n private _standby: Poll.Standby | (() => boolean | Poll.Standby);\n private _state: IPoll.State<T, U, V>;\n private _tick = new PromiseDelegate<this>();\n private _ticked = new Signal<this, IPoll.State<T, U, V>>(this);\n private _timeout: ReturnType<typeof setTimeout> | undefined;\n}\n\n/**\n * A namespace for `Poll` types, interfaces, and statics.\n */\nexport namespace Poll {\n /**\n * A promise factory that returns an individual poll request.\n *\n * @typeparam T - The resolved type of the factory's promises.\n *\n * @typeparam U - The rejected type of the factory's promises.\n *\n * @typeparam V - The type to extend the phases supported by a poll.\n */\n export type Factory<T, U, V extends string> = (\n state: IPoll.State<T, U, V>\n ) => Promise<T>;\n\n /**\n * Indicates when the poll switches to standby.\n */\n export type Standby = 'never' | 'when-hidden';\n\n /**\n * Instantiation options for polls.\n *\n * @typeparam T - The resolved type of the factory's promises.\n *\n * @typeparam U - The rejected type of the factory's promises.\n *\n * @typeparam V - The type to extend the phases supported by a poll.\n */\n export interface IOptions<T, U, V extends string> {\n /**\n * Whether to begin polling automatically; defaults to `true`.\n */\n auto?: boolean;\n\n /**\n * A factory function that is passed a poll tick and returns a poll promise.\n */\n factory: Factory<T, U, V>;\n\n /**\n * The number of ticks to linger if poll switches to standby `when-hidden`.\n * Defaults to `1`.\n */\n linger?: number;\n\n /**\n * The polling frequency parameters.\n */\n frequency?: Partial<IPoll.Frequency>;\n\n /**\n * The name of the poll.\n * Defaults to `'unknown'`.\n */\n name?: string;\n\n /**\n * Indicates when the poll switches to standby or a function that returns\n * a boolean or a `Poll.Standby` value to indicate whether to stand by.\n * Defaults to `'when-hidden'`.\n *\n * #### Notes\n * If a function is passed in, for any given context, it should be\n * idempotent and safe to call multiple times. It will be called before each\n * tick execution, but may be called by clients as well.\n */\n standby?: Standby | (() => boolean | Standby);\n }\n /**\n * An interval value in ms that indicates the poll should tick immediately.\n */\n export const IMMEDIATE = 0;\n\n /**\n * Delays are 32-bit integers in many browsers so intervals need to be capped.\n *\n * #### Notes\n * https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value\n */\n export const MAX_INTERVAL = 2147483647;\n\n /**\n * An interval value that indicates the poll should never tick.\n */\n export const NEVER = Infinity;\n}\n\n/**\n * A namespace for private module data.\n */\nnamespace Private {\n /**\n * The default backoff growth rate if `backoff` is `true`.\n */\n export const DEFAULT_BACKOFF = 3;\n\n /**\n * The default polling frequency.\n */\n export const DEFAULT_FREQUENCY: IPoll.Frequency = {\n backoff: true,\n interval: 1000,\n max: 30 * 1000\n };\n\n /**\n * The default number of times to `linger` when a poll is hidden.\n */\n export const DEFAULT_LINGER = 1;\n\n /**\n * The default poll name.\n */\n export const DEFAULT_NAME = 'unknown';\n\n /**\n * The default poll standby behavior.\n */\n export const DEFAULT_STANDBY: Poll.Standby = 'when-hidden';\n\n /**\n * The first poll tick state's default values superseded in constructor.\n */\n export const DEFAULT_STATE: IPoll.State<any, any, any> = {\n interval: Poll.NEVER,\n payload: null,\n phase: 'constructed',\n timestamp: new Date(0).getTime()\n };\n\n /**\n * The disposed tick state values.\n */\n export const DISPOSED_STATE: IPoll.State<any, any, any> = {\n interval: Poll.NEVER,\n payload: null,\n phase: 'disposed',\n timestamp: new Date(0).getTime()\n };\n\n /**\n * Returns the number of milliseconds to sleep before the next tick.\n *\n * @param frequency - The poll's base frequency.\n * @param last - The poll's last tick.\n */\n export function sleep(\n frequency: IPoll.Frequency,\n last: IPoll.State<any, any, any>\n ): number {\n const { backoff, interval, max } = frequency;\n\n if (interval === Poll.NEVER) {\n return interval;\n }\n\n const growth =\n backoff === true ? DEFAULT_BACKOFF : backoff === false ? 1 : backoff;\n const random = getRandomIntInclusive(interval, last.interval * growth);\n\n return Math.min(max, random);\n }\n\n /**\n * Keep track of whether the document is hidden. This flag is only relevant in\n * a browser context.\n *\n * Listen to `visibilitychange` event to set the `hidden` flag.\n *\n * Listening to `pagehide` is also necessary because Safari support for\n * `visibilitychange` events is partial, cf.\n * https://developer.mozilla.org/docs/Web/API/Document/visibilitychange_event\n */\n export let hidden = (() => {\n if (typeof document === 'undefined') {\n return false;\n }\n document.addEventListener('visibilitychange', () => {\n hidden = document.visibilityState === 'hidden';\n });\n document.addEventListener('pagehide', () => {\n hidden = document.visibilityState === 'hidden';\n });\n return document.visibilityState === 'hidden';\n })();\n\n /**\n * Get a random integer between min and max, inclusive of both.\n *\n * #### Notes\n * From\n * https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive\n *\n * From the MDN page: It might be tempting to use Math.round() to accomplish\n * that, but doing so would cause your random numbers to follow a non-uniform\n * distribution, which may not be acceptable for your needs.\n */\n function getRandomIntInclusive(min: number, max: number) {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { PromiseDelegate } from '@lumino/coreutils';\n\nimport { IRateLimiter } from './index';\n\nimport { Poll } from './poll';\n\n/**\n * A base class to implement rate limiters with different invocation strategies.\n *\n * @typeparam T - The resolved type of the underlying function.\n *\n * @typeparam U - The rejected type of the underlying function.\n *\n * @typeparam V - Arguments for the underlying function.\n */\nexport abstract class RateLimiter<T, U, V extends any[]>\n implements IRateLimiter<T, U, V>\n{\n /**\n * Instantiate a rate limiter.\n *\n * @param fn - The function to rate limit.\n *\n * @param limit - The rate limit; defaults to 500ms.\n */\n constructor(fn: (...args: V) => T | Promise<T>, limit = 500) {\n this.limit = limit;\n this.poll = new Poll({\n auto: false,\n factory: async () => {\n const { args } = this;\n this.args = undefined;\n return fn(...args!);\n },\n frequency: { backoff: false, interval: Poll.NEVER, max: Poll.NEVER },\n standby: 'never'\n });\n this.payload = new PromiseDelegate();\n this.poll.ticked.connect((_, state) => {\n const { payload } = this;\n\n if (state.phase === 'resolved') {\n this.payload = new PromiseDelegate();\n payload!.resolve(state.payload as T);\n return;\n }\n\n if (state.phase === 'rejected' || state.phase === 'stopped') {\n this.payload = new PromiseDelegate();\n payload!.promise.catch(_ => undefined);\n payload!.reject(state.payload as U);\n return;\n }\n }, this);\n }\n\n /**\n * Whether the rate limiter is disposed.\n */\n get isDisposed(): boolean {\n return this.payload === null;\n }\n\n /**\n * Disposes the rate limiter.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this.args = undefined;\n this.payload = null;\n this.poll.dispose();\n }\n\n /**\n * The rate limit in milliseconds.\n */\n readonly limit: number;\n\n /**\n * Invoke the rate limited function.\n */\n abstract invoke(...args: V): Promise<T>;\n\n /**\n * Stop the function if it is mid-flight.\n */\n async stop(): Promise<void> {\n return this.poll.stop();\n }\n\n /**\n * Arguments for the underlying function.\n */\n protected args: V | undefined = undefined;\n\n /**\n * A promise that resolves on each successful invocation.\n */\n protected payload: PromiseDelegate<T> | null = null;\n\n /**\n * The underlying poll instance used by the rate limiter.\n */\n protected poll: Poll<T, U, 'invoked'>;\n}\n\n/**\n * Wraps and debounces a function that can be called multiple times and only\n * executes the underlying function one `interval` after the last invocation.\n *\n * @typeparam T - The resolved type of the underlying function. Defaults to any.\n *\n * @typeparam U - The rejected type of the underlying function. Defaults to any.\n *\n * @typeparam V - Arguments for the underlying function. Defaults to any[].\n */\nexport class Debouncer<\n T = any,\n U = any,\n V extends any[] = any[]\n> extends RateLimiter<T, U, V> {\n /**\n * Invokes the function and only executes after rate limit has elapsed.\n * Each invocation resets the timer.\n */\n invoke(...args: V): Promise<T> {\n this.args = args;\n void this.poll.schedule({ interval: this.limit, phase: 'invoked' });\n return this.payload!.promise;\n }\n}\n\n/**\n * Wraps and throttles a function that can be called multiple times and only\n * executes the underlying function once per `interval`.\n *\n * @typeparam T - The resolved type of the underlying function. Defaults to any.\n *\n * @typeparam U - The rejected type of the underlying function. Defaults to any.\n *\n * @typeparam V - Arguments for the underlying function. Defaults to any[].\n */\nexport class Throttler<\n T = any,\n U = any,\n V extends any[] = any[]\n> extends RateLimiter<T, U, V> {\n /**\n * Instantiate a throttler.\n *\n * @param fn - The function being throttled.\n *\n * @param options - Throttling configuration or throttling limit in ms.\n *\n * #### Notes\n * The `edge` defaults to `leading`; the `limit` defaults to `500`.\n */\n constructor(\n fn: (...args: V) => T | Promise<T>,\n options?: Throttler.IOptions | number\n ) {\n super(fn, typeof options === 'number' ? options : options && options.limit);\n if (typeof options !== 'number' && options && options.edge === 'trailing') {\n this._trailing = true;\n }\n this._interval = this._trailing ? this.limit : Poll.IMMEDIATE;\n }\n\n /**\n * Throttles function invocations if one is currently in flight.\n */\n invoke(...args: V): Promise<T> {\n const idle = this.poll.state.phase !== 'invoked';\n if (idle || this._trailing) {\n this.args = args;\n }\n if (idle) {\n void this.poll.schedule({ interval: this._interval, phase: 'invoked' });\n }\n return this.payload!.promise;\n }\n\n private _interval: number;\n private _trailing = false;\n}\n\n/**\n * A namespace for `Throttler` interfaces.\n */\nexport namespace Throttler {\n /**\n * Instantiation options for a `Throttler`.\n */\n export interface IOptions {\n /**\n * The throttling limit; defaults to 500ms.\n */\n limit?: number;\n\n /**\n * Whether to invoke at the leading or trailing edge of throttle cycle.\n * Defaults to `leading`.\n */\n edge?: 'leading' | 'trailing';\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { URLExt } from '@jupyterlab/coreutils';\nimport { JSONObject, ReadonlyJSONObject } from '@lumino/coreutils';\nimport { IDisposable } from '@lumino/disposable';\nimport { Poll } from '@lumino/polling';\nimport { IStream, Signal, Stream } from '@lumino/signaling';\nimport { ServerConnection } from '../serverconnection';\n\n/**\n * The url for the jupyter-server events service.\n */\nconst SERVICE_EVENTS_URL = 'api/events';\n\n/**\n * The events API service manager.\n */\nexport class EventManager implements Event.IManager {\n /**\n * Create a new event manager.\n */\n constructor(options: EventManager.IOptions = {}) {\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n\n // If subscription fails, the poll attempts to reconnect and backs off.\n this._poll = new Poll({ factory: () => this._subscribe() });\n this._stream = new Stream(this);\n\n // Subscribe to the events socket.\n void this._poll.start();\n }\n\n /**\n * The server settings used to make API requests.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Whether the event manager is disposed.\n */\n get isDisposed(): boolean {\n return this._poll.isDisposed;\n }\n\n /**\n * An event stream that emits and yields each new event.\n */\n get stream(): Event.Stream {\n return this._stream;\n }\n\n /**\n * Dispose the event manager.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n\n // Clean up poll.\n this._poll.dispose();\n\n // Clean up socket.\n const socket = this._socket;\n if (socket) {\n this._socket = null;\n socket.onopen = () => undefined;\n socket.onerror = () => undefined;\n socket.onmessage = () => undefined;\n socket.onclose = () => undefined;\n socket.close();\n }\n\n // Clean up stream.\n Signal.clearData(this);\n this._stream.stop();\n }\n\n /**\n * Post an event request to be emitted by the event bus.\n */\n async emit(event: Event.Request): Promise<void> {\n const { serverSettings } = this;\n const { baseUrl } = serverSettings;\n const { makeRequest, ResponseError } = ServerConnection;\n const url = URLExt.join(baseUrl, SERVICE_EVENTS_URL);\n const init = { body: JSON.stringify(event), method: 'POST' };\n const response = await makeRequest(url, init, serverSettings);\n\n if (response.status !== 204) {\n throw new ResponseError(response);\n }\n }\n\n /**\n * Subscribe to event bus emissions.\n */\n private _subscribe(): Promise<void> {\n return new Promise<void>((_, reject) => {\n if (this.isDisposed) {\n return;\n }\n\n const { appendToken, token, WebSocket, wsUrl } = this.serverSettings;\n let url = URLExt.join(wsUrl, SERVICE_EVENTS_URL, 'subscribe');\n if (appendToken && token !== '') {\n url += `?token=${encodeURIComponent(token)}`;\n }\n const socket = (this._socket = new WebSocket(url));\n const stream = this._stream;\n\n socket.onclose = () => reject(new Error('EventManager socket closed'));\n socket.onmessage = msg => msg.data && stream.emit(JSON.parse(msg.data));\n });\n }\n\n private _poll: Poll;\n private _socket: WebSocket | null = null;\n private _stream: Stream<this, Event.Emission>;\n}\n\n/**\n * A namespace for `EventManager` statics.\n */\nexport namespace EventManager {\n /**\n * The instantiation options for an event manager.\n */\n export interface IOptions {\n /**\n * The server settings used to make API requests.\n */\n serverSettings?: ServerConnection.ISettings;\n }\n}\n\n/**\n * A namespace for event API interfaces.\n */\nexport namespace Event {\n /**\n * The event emission type.\n */\n export type Emission = ReadonlyJSONObject & {\n schema_id: string;\n };\n\n /**\n * The event request type.\n */\n export type Request = {\n data: JSONObject;\n schema_id: string;\n version: string;\n };\n\n /**\n * An event stream with the characteristics of a signal and an async iterator.\n */\n export type Stream = IStream<IManager, Emission>;\n\n /**\n * The interface for the event bus front-end.\n */\n export interface IManager extends IDisposable {\n /**\n * The server settings used to make API requests.\n */\n readonly serverSettings: ServerConnection.ISettings;\n /**\n * An event stream that emits and yields each new event.\n */\n readonly stream: Event.Stream;\n /**\n * Post an event request to be emitted by the event bus.\n */\n emit(event: Event.Request): Promise<void>;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport * as KernelMessage from './messages';\n\nimport { IModel } from './restapi';\n\nimport { validateProperty } from '../validate';\n\n/**\n * Required fields for `IKernelHeader`.\n */\nconst HEADER_FIELDS = ['username', 'version', 'session', 'msg_id', 'msg_type'];\n\n/**\n * Required fields and types for contents of various types of `kernel.IMessage`\n * messages on the iopub channel.\n */\nconst IOPUB_CONTENT_FIELDS: { [key: string]: any } = {\n stream: { name: 'string', text: 'string' },\n display_data: { data: 'object', metadata: 'object' },\n execute_input: { code: 'string', execution_count: 'number' },\n execute_result: {\n execution_count: 'number',\n data: 'object',\n metadata: 'object'\n },\n error: { ename: 'string', evalue: 'string', traceback: 'object' },\n status: {\n execution_state: [\n 'string',\n ['starting', 'idle', 'busy', 'restarting', 'dead']\n ]\n },\n clear_output: { wait: 'boolean' },\n comm_open: { comm_id: 'string', target_name: 'string', data: 'object' },\n comm_msg: { comm_id: 'string', data: 'object' },\n comm_close: { comm_id: 'string' },\n shutdown_reply: { restart: 'boolean' } // Emitted by the IPython kernel.\n};\n\n/**\n * Validate the header of a kernel message.\n */\nfunction validateHeader(\n header: KernelMessage.IHeader\n): asserts header is KernelMessage.IHeader {\n for (let i = 0; i < HEADER_FIELDS.length; i++) {\n validateProperty(header, HEADER_FIELDS[i], 'string');\n }\n}\n\n/**\n * Validate a kernel message object.\n */\nexport function validateMessage(\n msg: KernelMessage.IMessage\n): asserts msg is KernelMessage.IMessage {\n validateProperty(msg, 'metadata', 'object');\n validateProperty(msg, 'content', 'object');\n validateProperty(msg, 'channel', 'string');\n validateHeader(msg.header);\n if (msg.channel === 'iopub') {\n validateIOPubContent(msg as KernelMessage.IIOPubMessage);\n }\n}\n\n/**\n * Validate content an kernel message on the iopub channel.\n */\nfunction validateIOPubContent(\n msg: KernelMessage.IIOPubMessage\n): asserts msg is KernelMessage.IIOPubMessage {\n if (msg.channel === 'iopub') {\n const fields = IOPUB_CONTENT_FIELDS[msg.header.msg_type];\n // Check for unknown message type.\n if (fields === undefined) {\n return;\n }\n const names = Object.keys(fields);\n const content = msg.content;\n for (let i = 0; i < names.length; i++) {\n let args = fields[names[i]];\n if (!Array.isArray(args)) {\n args = [args];\n }\n validateProperty(content, names[i], ...args);\n }\n }\n}\n\n/**\n * Validate a `Kernel.IModel` object.\n */\nexport function validateModel(model: IModel): asserts model is IModel {\n validateProperty(model, 'name', 'string');\n validateProperty(model, 'id', 'string');\n}\n\n/**\n * Validate an array of `IModel` objects.\n */\nexport function validateModels(models: IModel[]): asserts models is IModel[] {\n if (!Array.isArray(models)) {\n throw new Error('Invalid kernel list');\n }\n models.forEach(d => validateModel(d));\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { ServerConnection } from '../serverconnection';\nimport { URLExt } from '@jupyterlab/coreutils';\nimport { validateModel, validateModels } from './validate';\n\n/**\n * The kernel model provided by the server.\n *\n * #### Notes\n * See the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).\n */\nexport interface IModel {\n /**\n * Unique identifier of the kernel on the server.\n */\n readonly id: string;\n\n /**\n * The name of the kernel.\n */\n readonly name: string;\n\n /**\n * The kernel execution state.\n */\n readonly execution_state?: string;\n\n /**\n * The timestamp of the last activity on the kernel.\n */\n // eslint-disable-next-line camelcase\n readonly last_activity?: string;\n\n /**\n * The number of active connections to the kernel.\n */\n readonly connections?: number;\n\n /**\n * The reason the kernel died, if applicable.\n */\n readonly reason?: string;\n\n /**\n * The traceback for a dead kernel, if applicable.\n */\n readonly traceback?: string;\n}\n\n/**\n * The url for the kernel service.\n */\nexport const KERNEL_SERVICE_URL = 'api/kernels';\n\n/**\n * Fetch the running kernels.\n *\n * @param settings - The optional server settings.\n *\n * @returns A promise that resolves with the list of running kernels.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nexport async function listRunning(\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<IModel[]> {\n const url = URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL);\n const response = await ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validateModels(data);\n return data;\n}\n\n/**\n * Start a new kernel.\n *\n * @param options - The options used to create the kernel.\n *\n * @returns A promise that resolves with a kernel connection object.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nexport async function startNew(\n options: IKernelOptions = {},\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<IModel> {\n const url = URLExt.join(settings.baseUrl, KERNEL_SERVICE_URL);\n const init = {\n method: 'POST',\n body: JSON.stringify(options)\n };\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validateModel(data);\n return data;\n}\n\n/**\n * The options object used to initialize a kernel.\n */\nexport type IKernelOptions = Partial<Pick<IModel, 'name'>>;\n\n/**\n * Restart a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response (and thus after a restart) and rejected otherwise.\n */\nexport async function restartKernel(\n id: string,\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<void> {\n const url = URLExt.join(\n settings.baseUrl,\n KERNEL_SERVICE_URL,\n encodeURIComponent(id),\n 'restart'\n );\n const init = { method: 'POST' };\n\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validateModel(data);\n}\n\n/**\n * Interrupt a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nexport async function interruptKernel(\n id: string,\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<void> {\n const url = URLExt.join(\n settings.baseUrl,\n KERNEL_SERVICE_URL,\n encodeURIComponent(id),\n 'interrupt'\n );\n const init = { method: 'POST' };\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 204) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\n\n/**\n * Shut down a kernel.\n *\n * @param id - The id of the running kernel.\n *\n * @param settings - The server settings for the request.\n *\n * @returns A promise that resolves when the kernel is shut down.\n *\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nexport async function shutdownKernel(\n id: string,\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<void> {\n const url = URLExt.join(\n settings.baseUrl,\n KERNEL_SERVICE_URL,\n encodeURIComponent(id)\n );\n const init = { method: 'DELETE' };\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status === 404) {\n const msg = `The kernel \"${id}\" does not exist on the server`;\n console.warn(msg);\n } else if (response.status !== 204) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\n\n/**\n * Get a full kernel model from the server by kernel id string.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\nexport async function getKernelModel(\n id: string,\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<IModel | undefined> {\n const url = URLExt.join(\n settings.baseUrl,\n KERNEL_SERVICE_URL,\n encodeURIComponent(id)\n );\n\n const response = await ServerConnection.makeRequest(url, {}, settings);\n if (response.status === 404) {\n return undefined;\n } else if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n validateModel(data);\n return data;\n}\n\n/**\n * The kernel API client.\n *\n * #### Notes\n * Use this class to interact with the Jupyter Server Kernel API.\n * This class adheres to the Jupyter Server API endpoints.\n */\nexport class KernelAPIClient {\n /**\n * Create a new kernel API client.\n *\n * @param options - The options used to create the client.\n */\n constructor(options: { serverSettings?: ServerConnection.ISettings } = {}) {\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n }\n\n /**\n * The server settings for the client.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * List the running kernels.\n *\n * @returns A promise that resolves with the list of running kernel models.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async listRunning(): Promise<IModel[]> {\n return listRunning(this.serverSettings);\n }\n\n /**\n * Get a kernel model.\n *\n * @param id - The id of the kernel of interest.\n *\n * @returns A promise that resolves with the kernel model.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n * If the kernel does not exist on the server, the promise is resolved with `undefined`.\n */\n async getModel(id: string): Promise<IModel | undefined> {\n return getKernelModel(id, this.serverSettings);\n }\n\n /**\n * Start a new kernel.\n *\n * @param options - The options used to create the kernel.\n *\n * @returns A promise that resolves with the kernel model.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async startNew(options: IKernelOptions = {}): Promise<IModel> {\n return startNew(options, this.serverSettings);\n }\n\n /**\n * Restart a kernel.\n *\n * @param id - The id of the kernel to restart.\n *\n * @returns A promise that resolves when the kernel is restarted.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async restart(id: string): Promise<void> {\n return restartKernel(id, this.serverSettings);\n }\n\n /**\n * Interrupt a kernel.\n *\n * @param id - The id of the kernel to interrupt.\n *\n * @returns A promise that resolves when the kernel is interrupted.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async interrupt(id: string): Promise<void> {\n return interruptKernel(id, this.serverSettings);\n }\n\n /**\n * Shut down a kernel by id.\n *\n * @param id - The id of the kernel to shut down.\n *\n * @returns A promise that resolves when the kernel is shut down.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async shutdown(id: string): Promise<void> {\n return shutdownKernel(id, this.serverSettings);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { JSONObject } from '@lumino/coreutils';\n\nimport { DisposableDelegate } from '@lumino/disposable';\n\nimport * as Kernel from './kernel';\n\nimport * as KernelMessage from './messages';\n\n/**\n * Comm channel handler.\n */\nexport class CommHandler extends DisposableDelegate implements Kernel.IComm {\n /**\n * Construct a new comm channel.\n */\n constructor(\n target: string,\n id: string,\n kernel: Kernel.IKernelConnection,\n disposeCb: () => void\n ) {\n super(disposeCb);\n this._id = id;\n this._target = target;\n this._kernel = kernel;\n }\n\n /**\n * The unique id for the comm channel.\n */\n get commId(): string {\n return this._id;\n }\n\n /**\n * The target name for the comm channel.\n */\n get targetName(): string {\n return this._target;\n }\n\n /**\n * Get the callback for a comm close event.\n *\n * #### Notes\n * This is called when the comm is closed from either the server or client.\n *\n * **See also:** [[ICommClose]], [[close]]\n */\n get onClose(): (\n msg: KernelMessage.ICommCloseMsg\n ) => void | PromiseLike<void> {\n return this._onClose;\n }\n\n /**\n * Set the callback for a comm close event.\n *\n * #### Notes\n * This is called when the comm is closed from either the server or client. If\n * the function returns a promise, and the kernel was closed from the server,\n * kernel message processing will pause until the returned promise is\n * fulfilled.\n *\n * **See also:** [[close]]\n */\n set onClose(\n cb: (msg: KernelMessage.ICommCloseMsg) => void | PromiseLike<void>\n ) {\n this._onClose = cb;\n }\n\n /**\n * Get the callback for a comm message received event.\n */\n get onMsg(): (msg: KernelMessage.ICommMsgMsg) => void | PromiseLike<void> {\n return this._onMsg;\n }\n\n /**\n * Set the callback for a comm message received event.\n *\n * #### Notes\n * This is called when a comm message is received. If the function returns a\n * promise, kernel message processing will pause until it is fulfilled.\n */\n set onMsg(cb: (msg: KernelMessage.ICommMsgMsg) => void | PromiseLike<void>) {\n this._onMsg = cb;\n }\n\n /**\n * Open a comm with optional data and metadata.\n *\n * #### Notes\n * This sends a `comm_open` message to the server.\n *\n * **See also:** [[ICommOpen]]\n */\n open(\n data?: JSONObject,\n metadata?: JSONObject,\n buffers: (ArrayBuffer | ArrayBufferView)[] = []\n ): Kernel.IShellFuture {\n if (this.isDisposed || this._kernel.isDisposed) {\n throw new Error('Cannot open');\n }\n const msg = KernelMessage.createMessage({\n msgType: 'comm_open',\n channel: 'shell',\n username: this._kernel.username,\n session: this._kernel.clientId,\n subshellId: this._kernel.subshellId,\n content: {\n comm_id: this._id,\n target_name: this._target,\n data: data ?? {}\n },\n metadata,\n buffers\n });\n return this._kernel.sendShellMessage(msg, false, true);\n }\n\n /**\n * Send a `comm_msg` message to the kernel.\n *\n * #### Notes\n * This is a no-op if the comm has been closed.\n *\n * **See also:** [[ICommMsg]]\n */\n send(\n data: JSONObject,\n metadata?: JSONObject,\n buffers: (ArrayBuffer | ArrayBufferView)[] = [],\n disposeOnDone: boolean = true\n ): Kernel.IShellFuture {\n if (this.isDisposed || this._kernel.isDisposed) {\n throw new Error('Cannot send');\n }\n const msg = KernelMessage.createMessage({\n msgType: 'comm_msg',\n channel: 'shell',\n username: this._kernel.username,\n session: this._kernel.clientId,\n subshellId: this._kernel.subshellId,\n content: {\n comm_id: this._id,\n data: data\n },\n metadata,\n buffers\n });\n return this._kernel.sendShellMessage(msg, false, disposeOnDone);\n }\n\n /**\n * Close the comm.\n *\n * #### Notes\n * This will send a `comm_close` message to the kernel, and call the\n * `onClose` callback if set.\n *\n * This is a no-op if the comm is already closed.\n *\n * **See also:** [[ICommClose]], [[onClose]]\n */\n close(\n data?: JSONObject,\n metadata?: JSONObject,\n buffers: (ArrayBuffer | ArrayBufferView)[] = []\n ): Kernel.IShellFuture {\n if (this.isDisposed || this._kernel.isDisposed) {\n throw new Error('Cannot close');\n }\n const msg = KernelMessage.createMessage({\n msgType: 'comm_close',\n channel: 'shell',\n username: this._kernel.username,\n session: this._kernel.clientId,\n subshellId: this._kernel.subshellId,\n content: {\n comm_id: this._id,\n data: data ?? {}\n },\n metadata,\n buffers\n });\n const future = this._kernel.sendShellMessage(msg, false, true);\n const onClose = this._onClose;\n if (onClose) {\n const ioMsg = KernelMessage.createMessage({\n msgType: 'comm_close',\n channel: 'iopub',\n username: this._kernel.username,\n session: this._kernel.clientId,\n content: {\n comm_id: this._id,\n data: data ?? {}\n },\n metadata,\n buffers\n });\n // In the future, we may want to communicate back to the user the possible\n // promise returned from onClose.\n void onClose(ioMsg);\n }\n this.dispose();\n return future;\n }\n\n private _target = '';\n private _id = '';\n private _kernel: Kernel.IKernelConnection;\n private _onClose: (\n msg: KernelMessage.ICommCloseMsg<'iopub'>\n ) => void | PromiseLike<void>;\n private _onMsg: (msg: KernelMessage.ICommMsgMsg) => void | PromiseLike<void>;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { PromiseDelegate } from '@lumino/coreutils';\nimport { DisposableDelegate } from '@lumino/disposable';\nimport * as Kernel from './kernel';\nimport * as KernelMessage from './messages';\n\ndeclare let setImmediate: any;\n\n/**\n * Implementation of a kernel future.\n *\n * If a reply is expected, the Future is considered done when both a `reply`\n * message and an `idle` iopub status message have been received. Otherwise, it\n * is considered done when the `idle` status is received.\n *\n */\nexport abstract class KernelFutureHandler<\n REQUEST extends KernelMessage.IShellControlMessage,\n REPLY extends KernelMessage.IShellControlMessage\n >\n extends DisposableDelegate\n implements Kernel.IFuture<REQUEST, REPLY>\n{\n /**\n * Construct a new KernelFutureHandler.\n */\n constructor(\n cb: () => void,\n msg: REQUEST,\n expectReply: boolean,\n disposeOnDone: boolean,\n kernel: Kernel.IKernelConnection\n ) {\n super(cb);\n this._msg = msg;\n if (!expectReply) {\n this._setFlag(Private.KernelFutureFlag.GotReply);\n }\n this._disposeOnDone = disposeOnDone;\n this._kernel = kernel;\n }\n\n /**\n * Get the original outgoing message.\n */\n get msg(): REQUEST {\n return this._msg;\n }\n\n /**\n * A promise that resolves when the future is done.\n */\n get done(): Promise<REPLY> {\n return this._done.promise;\n }\n\n /**\n * Get the reply handler.\n */\n get onReply(): (msg: REPLY) => void | PromiseLike<void> {\n return this._reply;\n }\n\n /**\n * Set the reply handler.\n */\n set onReply(cb: (msg: REPLY) => void | PromiseLike<void>) {\n this._reply = cb;\n }\n\n /**\n * Get the iopub handler.\n */\n get onIOPub(): (\n msg: KernelMessage.IIOPubMessage\n ) => void | PromiseLike<void> {\n return this._iopub;\n }\n\n /**\n * Set the iopub handler.\n */\n set onIOPub(\n cb: (msg: KernelMessage.IIOPubMessage) => void | PromiseLike<void>\n ) {\n this._iopub = cb;\n }\n\n /**\n * Get the stdin handler.\n */\n get onStdin(): (\n msg: KernelMessage.IStdinMessage\n ) => void | PromiseLike<void> {\n return this._stdin;\n }\n\n /**\n * Set the stdin handler.\n */\n set onStdin(\n cb: (msg: KernelMessage.IStdinMessage) => void | PromiseLike<void>\n ) {\n this._stdin = cb;\n }\n\n /**\n * Register hook for IOPub messages.\n *\n * @param hook - The callback invoked for an IOPub message.\n *\n * #### Notes\n * The IOPub hook system allows you to preempt the handlers for IOPub\n * messages handled by the future.\n *\n * The most recently registered hook is run first. A hook can return a\n * boolean or a promise to a boolean, in which case all kernel message\n * processing pauses until the promise is fulfilled. If a hook return value\n * resolves to false, any later hooks will not run and the function will\n * return a promise resolving to false. If a hook throws an error, the error\n * is logged to the console and the next hook is run. If a hook is\n * registered during the hook processing, it will not run until the next\n * message. If a hook is removed during the hook processing, it will be\n * deactivated immediately.\n */\n registerMessageHook(\n hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>\n ): void {\n if (this.isDisposed) {\n throw new Error('Kernel future is disposed');\n }\n this._hooks.add(hook);\n }\n\n /**\n * Remove a hook for IOPub messages.\n *\n * @param hook - The hook to remove.\n *\n * #### Notes\n * If a hook is removed during the hook processing, it will be deactivated immediately.\n */\n removeMessageHook(\n hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>\n ): void {\n if (this.isDisposed) {\n return;\n }\n this._hooks.remove(hook);\n }\n\n /**\n * Send an `input_reply` message.\n */\n sendInputReply(\n content: KernelMessage.IInputReplyMsg['content'],\n parent_header: KernelMessage.IInputReplyMsg['parent_header']\n ): void {\n this._kernel.sendInputReply(content, parent_header);\n }\n\n /**\n * Dispose and unregister the future.\n */\n dispose(): void {\n this._stdin = Private.noOp;\n this._iopub = Private.noOp;\n this._reply = Private.noOp;\n this._hooks = null!;\n if (!this._testFlag(Private.KernelFutureFlag.IsDone)) {\n // TODO: Uncomment the following logging code, and check for any tests that trigger it.\n // let status = [];\n // if (!this._testFlag(Private.KernelFutureFlag.GotIdle)) {\n // status.push('idle');\n // }\n // if (!this._testFlag(Private.KernelFutureFlag.GotReply)) {\n // status.push('reply');\n // }\n // console.warn(\n // `*************** DISPOSED BEFORE DONE: K${this._kernel.id.slice(\n // 0,\n // 6\n // )} M${this._msg.header.msg_id.slice(0, 6)} missing ${status.join(' ')}`\n // );\n\n // Reject the `done` promise, but catch its error here in case no one else\n // is waiting for the promise to resolve. This prevents the error from\n // being displayed in the console, but does not prevent it from being\n // caught by a client who is waiting for it.\n // Note: any `.then` and `.finally` attached to the `done` promise\n // will cause the error to be thrown as uncaught anyways.\n this._done.promise.catch(() => {\n /* no-op */\n });\n this._done.reject(\n new Error(\n `Canceled future for ${this.msg.header.msg_type} message before replies were done`\n )\n );\n }\n super.dispose();\n }\n\n /**\n * Handle an incoming kernel message.\n */\n async handleMsg(msg: KernelMessage.IMessage): Promise<void> {\n switch (msg.channel) {\n case 'control':\n case 'shell':\n if (\n msg.channel === this.msg.channel &&\n (\n msg.parent_header as KernelMessage.IHeader<KernelMessage.MessageType>\n ).msg_id === this.msg.header.msg_id\n ) {\n await this._handleReply(msg as REPLY);\n }\n break;\n case 'stdin':\n await this._handleStdin(msg as KernelMessage.IStdinMessage);\n break;\n case 'iopub':\n await this._handleIOPub(msg as KernelMessage.IIOPubMessage);\n break;\n default:\n break;\n }\n }\n\n private async _handleReply(msg: REPLY): Promise<void> {\n const reply = this._reply;\n if (reply) {\n // tslint:disable-next-line:await-promise\n await reply(msg);\n }\n this._replyMsg = msg;\n this._setFlag(Private.KernelFutureFlag.GotReply);\n if (this._testFlag(Private.KernelFutureFlag.GotIdle)) {\n this._handleDone();\n }\n }\n\n private async _handleStdin(msg: KernelMessage.IStdinMessage): Promise<void> {\n this._kernel.hasPendingInput = true;\n const stdin = this._stdin;\n if (stdin) {\n // tslint:disable-next-line:await-promise\n await stdin(msg);\n }\n }\n\n private async _handleIOPub(msg: KernelMessage.IIOPubMessage): Promise<void> {\n const process = await this._hooks.process(msg);\n const iopub = this._iopub;\n if (process && iopub) {\n // tslint:disable-next-line:await-promise\n await iopub(msg);\n }\n if (\n KernelMessage.isStatusMsg(msg) &&\n msg.content.execution_state === 'idle'\n ) {\n this._setFlag(Private.KernelFutureFlag.GotIdle);\n if (this._testFlag(Private.KernelFutureFlag.GotReply)) {\n this._handleDone();\n }\n }\n }\n\n private _handleDone(): void {\n if (this._testFlag(Private.KernelFutureFlag.IsDone)) {\n return;\n }\n this._setFlag(Private.KernelFutureFlag.IsDone);\n this._done.resolve(this._replyMsg);\n if (this._disposeOnDone) {\n this.dispose();\n }\n }\n\n /**\n * Test whether the given future flag is set.\n */\n private _testFlag(flag: Private.KernelFutureFlag): boolean {\n // tslint:disable-next-line\n return (this._status & flag) !== 0;\n }\n\n /**\n * Set the given future flag.\n */\n private _setFlag(flag: Private.KernelFutureFlag): void {\n // tslint:disable-next-line\n this._status |= flag;\n }\n\n private _msg: REQUEST;\n private _status = 0;\n private _stdin: (\n msg: KernelMessage.IStdinMessage\n ) => void | PromiseLike<void> = Private.noOp;\n private _iopub: (\n msg: KernelMessage.IIOPubMessage\n ) => void | PromiseLike<void> = Private.noOp;\n private _reply: (msg: REPLY) => void | PromiseLike<void> = Private.noOp;\n private _done = new PromiseDelegate<REPLY>();\n private _replyMsg: REPLY;\n private _hooks = new Private.HookList<KernelMessage.IIOPubMessage>();\n private _disposeOnDone = true;\n private _kernel: Kernel.IKernelConnection;\n}\n\nexport class KernelControlFutureHandler<\n REQUEST extends\n KernelMessage.IControlMessage = KernelMessage.IControlMessage,\n REPLY extends KernelMessage.IControlMessage = KernelMessage.IControlMessage\n >\n extends KernelFutureHandler<REQUEST, REPLY>\n implements Kernel.IControlFuture<REQUEST, REPLY> {}\n\nexport class KernelShellFutureHandler<\n REQUEST extends KernelMessage.IShellMessage = KernelMessage.IShellMessage,\n REPLY extends KernelMessage.IShellMessage = KernelMessage.IShellMessage\n >\n extends KernelFutureHandler<REQUEST, REPLY>\n implements Kernel.IShellFuture<REQUEST, REPLY> {}\n\nnamespace Private {\n /**\n * A no-op function.\n */\n export const noOp = (): void => {\n /* no-op */\n };\n\n /**\n * Defer a computation.\n *\n * #### NOTES\n * We can't just use requestAnimationFrame since it is not available in node.\n * This implementation is from Phosphor:\n * https://github.com/phosphorjs/phosphor/blob/e88e4321289bb1198f3098e7bda40736501f2ed8/tests/test-messaging/src/index.spec.ts#L63\n */\n const defer = (() => {\n const ok = typeof requestAnimationFrame === 'function';\n return ok ? requestAnimationFrame : setImmediate;\n })();\n\n export class HookList<T> {\n /**\n * Register a hook.\n *\n * @param hook - The callback to register.\n */\n add(hook: (msg: T) => boolean | PromiseLike<boolean>): void {\n this.remove(hook);\n this._hooks.push(hook);\n }\n\n /**\n * Remove a hook, if it exists in the hook list.\n *\n * @param hook - The callback to remove.\n */\n remove(hook: (msg: T) => boolean | PromiseLike<boolean>): void {\n const index = this._hooks.indexOf(hook);\n if (index >= 0) {\n this._hooks[index] = null;\n this._scheduleCompact();\n }\n }\n\n /**\n * Process a message through the hooks.\n *\n * @returns a promise resolving to false if any hook resolved as false,\n * otherwise true\n *\n * #### Notes\n * The most recently registered hook is run first. A hook can return a\n * boolean or a promise to a boolean, in which case processing pauses until\n * the promise is fulfilled. If a hook return value resolves to false, any\n * later hooks will not run and the function will return a promise resolving\n * to false. If a hook throws an error, the error is logged to the console\n * and the next hook is run. If a hook is registered during the hook\n * processing, it will not run until the next message. If a hook is removed\n * during the hook processing, it will be deactivated immediately.\n */\n async process(msg: T): Promise<boolean> {\n // Wait until we can start a new process run.\n await this._processing;\n\n // Start the next process run.\n const processing = new PromiseDelegate<void>();\n this._processing = processing.promise;\n\n let continueHandling: boolean;\n\n // Call the end hook (most recently-added) first. Starting at the end also\n // guarantees that hooks added during the processing will not be run in\n // this process run.\n for (let i = this._hooks.length - 1; i >= 0; i--) {\n const hook = this._hooks[i];\n\n // If the hook has been removed, continue to the next one.\n if (hook === null) {\n continue;\n }\n\n // Execute the hook and log any errors.\n try {\n // tslint:disable-next-line:await-promise\n continueHandling = await hook(msg);\n } catch (err) {\n continueHandling = true;\n console.error(err);\n }\n\n // If the hook resolved to false, stop processing and return.\n if (continueHandling === false) {\n processing.resolve(undefined);\n return false;\n }\n }\n\n // All hooks returned true (or errored out), so return true.\n processing.resolve(undefined);\n return true;\n }\n\n /**\n * Schedule a cleanup of the list, removing any hooks that have been nulled out.\n */\n private _scheduleCompact(): void {\n if (!this._compactScheduled) {\n this._compactScheduled = true;\n\n // Schedule a compaction in between processing runs. We do the\n // scheduling in an animation frame to rate-limit our compactions. If we\n // need to compact more frequently, we can change this to directly\n // schedule the compaction.\n defer(() => {\n this._processing = this._processing.then(() => {\n this._compactScheduled = false;\n this._compact();\n });\n });\n }\n }\n\n /**\n * Compact the list, removing any nulls.\n */\n private _compact(): void {\n let numNulls = 0;\n for (let i = 0, len = this._hooks.length; i < len; i++) {\n const hook = this._hooks[i];\n if (this._hooks[i] === null) {\n numNulls++;\n } else {\n this._hooks[i - numNulls] = hook;\n }\n }\n this._hooks.length -= numNulls;\n }\n\n private _hooks: (((msg: T) => boolean | PromiseLike<boolean>) | null)[] =\n [];\n private _compactScheduled: boolean;\n private _processing: Promise<void>;\n }\n\n /**\n * Bit flags for the kernel future state.\n */\n export enum KernelFutureFlag {\n GotReply = 0x1,\n GotIdle = 0x2,\n IsDone = 0x4,\n DisposeOnDone = 0x8\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { ISpecModel, ISpecModels } from './restapi';\nimport { validateProperty } from '../validate';\n\n/**\n * Validate a server kernelspec model to a client side model.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function validateSpecModel(data: any): ISpecModel {\n const spec = data.spec;\n if (!spec) {\n throw new Error('Invalid kernel spec');\n }\n validateProperty(data, 'name', 'string');\n validateProperty(data, 'resources', 'object');\n validateProperty(spec, 'language', 'string');\n validateProperty(spec, 'display_name', 'string');\n validateProperty(spec, 'argv', 'array');\n\n let metadata: any = null;\n if (spec.hasOwnProperty('metadata')) {\n validateProperty(spec, 'metadata', 'object');\n metadata = spec.metadata;\n }\n\n let env: any = null;\n if (spec.hasOwnProperty('env')) {\n validateProperty(spec, 'env', 'object');\n env = spec.env;\n }\n return {\n name: data.name,\n resources: data.resources,\n language: spec.language,\n display_name: spec.display_name,\n argv: spec.argv,\n metadata,\n env\n };\n}\n\n/**\n * Validate a `Kernel.ISpecModels` object.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function validateSpecModels(data: any): ISpecModels {\n if (!data.hasOwnProperty('kernelspecs')) {\n throw new Error('No kernelspecs found');\n }\n let keys = Object.keys(data.kernelspecs);\n const kernelspecs: { [key: string]: ISpecModel } = Object.create(null);\n let defaultSpec = data.default;\n\n for (let i = 0; i < keys.length; i++) {\n const ks = data.kernelspecs[keys[i]];\n try {\n kernelspecs[keys[i]] = validateSpecModel(ks);\n } catch (err) {\n // Remove the errant kernel spec.\n console.warn(`Removing errant kernel spec: ${keys[i]}`);\n }\n }\n keys = Object.keys(kernelspecs);\n if (!keys.length) {\n throw new Error('No valid kernelspecs found');\n }\n if (\n !defaultSpec ||\n typeof defaultSpec !== 'string' ||\n !(defaultSpec in kernelspecs)\n ) {\n defaultSpec = keys[0];\n console.warn(`Default kernel not found, using '${keys[0]}'`);\n }\n return {\n default: defaultSpec,\n kernelspecs\n };\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { ServerConnection } from '../serverconnection';\nimport { validateSpecModels } from './validate';\n\nimport { URLExt } from '@jupyterlab/coreutils';\nimport { PartialJSONObject } from '@lumino/coreutils';\n\n/**\n * The url for the kernelspec service.\n */\nconst KERNELSPEC_SERVICE_URL = 'api/kernelspecs';\n\n/**\n * Fetch all of the kernel specs.\n *\n * @param settings - The optional server settings.\n * @param useCache - Whether to use the cache. If false, always request.\n *\n * @returns A promise that resolves with the kernel specs.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernelspecs).\n */\nexport async function getSpecs(\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<ISpecModels> {\n const url = URLExt.join(settings.baseUrl, KERNELSPEC_SERVICE_URL);\n const response = await ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n return validateSpecModels(data);\n}\n\n/**\n * Kernel Spec interface.\n *\n * #### Notes\n * See [Kernel specs](https://jupyter-client.readthedocs.io/en/latest/kernels.html#kernelspecs).\n */\nexport interface ISpecModel extends PartialJSONObject {\n /**\n * The name of the kernel spec.\n */\n readonly name: string;\n\n /**\n * The name of the language of the kernel.\n */\n readonly language: string;\n\n /**\n * A list of command line arguments used to start the kernel.\n */\n readonly argv: string[];\n\n /**\n * The kernel\u2019s name as it should be displayed in the UI.\n */\n readonly display_name: string;\n\n /**\n * A dictionary of environment variables to set for the kernel.\n */\n readonly env?: PartialJSONObject;\n\n /**\n * A mapping of resource file name to download path.\n */\n readonly resources: { [key: string]: string };\n\n /**\n * A dictionary of additional attributes about this kernel; used by clients to aid in kernel selection.\n */\n readonly metadata?: PartialJSONObject;\n}\n\n/**\n * The available kernelSpec models.\n *\n * #### Notes\n * See the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernelspecs).\n */\nexport interface ISpecModels extends PartialJSONObject {\n /**\n * The name of the default kernel spec.\n */\n default: string;\n\n /**\n * A mapping of kernel spec name to spec.\n */\n readonly kernelspecs: { [key: string]: ISpecModel | undefined };\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { JSONExt } from '@lumino/coreutils';\nimport { Poll } from '@lumino/polling';\nimport { ISignal, Signal } from '@lumino/signaling';\n\nimport { ServerConnection } from '../serverconnection';\nimport * as KernelSpec from './kernelspec';\nimport * as restapi from './restapi';\nimport { BaseManager } from '../basemanager';\n/**\n * An implementation of a kernel spec manager.\n */\nexport class KernelSpecManager\n extends BaseManager\n implements KernelSpec.IManager\n{\n /**\n * Construct a new kernel spec manager.\n *\n * @param options - The default options for kernel.\n */\n constructor(options: KernelSpecManager.IOptions = {}) {\n super(options);\n\n // Initialize internal data.\n this._ready = Promise.all([this.requestSpecs()])\n .then(_ => undefined)\n .catch(_ => undefined)\n .then(() => {\n if (this.isDisposed) {\n return;\n }\n this._isReady = true;\n });\n\n this._pollSpecs = new Poll({\n auto: false,\n factory: () => this.requestSpecs(),\n frequency: {\n interval: 61 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:KernelSpecManager#specs`,\n standby: options.standby ?? 'when-hidden'\n });\n void this.ready.then(() => {\n void this._pollSpecs.start();\n });\n }\n\n /**\n * The server settings for the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Test whether the manager is ready.\n */\n get isReady(): boolean {\n return this._isReady;\n }\n\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready(): Promise<void> {\n return this._ready;\n }\n\n /**\n * Get the most recently fetched kernel specs.\n */\n get specs(): restapi.ISpecModels | null {\n return this._specs;\n }\n\n /**\n * A signal emitted when the specs change.\n */\n get specsChanged(): ISignal<this, restapi.ISpecModels> {\n return this._specsChanged;\n }\n\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure(): ISignal<this, Error> {\n return this._connectionFailure;\n }\n\n /**\n * Dispose of the resources used by the manager.\n */\n dispose(): void {\n this._pollSpecs.dispose();\n super.dispose();\n }\n\n /**\n * Force a refresh of the specs from the server.\n *\n * @returns A promise that resolves when the specs are fetched.\n *\n * #### Notes\n * This is intended to be called only in response to a user action,\n * since the manager maintains its internal state.\n */\n async refreshSpecs(): Promise<void> {\n await this._pollSpecs.refresh();\n await this._pollSpecs.tick;\n }\n\n /**\n * Execute a request to the server to poll specs and update state.\n */\n protected async requestSpecs(): Promise<void> {\n const specs = await restapi.getSpecs(this.serverSettings);\n if (this.isDisposed) {\n return;\n }\n if (!JSONExt.deepEqual(specs, this._specs)) {\n this._specs = specs;\n this._specsChanged.emit(specs);\n }\n }\n\n private _isReady = false;\n private _connectionFailure = new Signal<this, Error>(this);\n\n private _pollSpecs: Poll;\n private _ready: Promise<void>;\n\n private _specs: restapi.ISpecModels | null = null;\n private _specsChanged = new Signal<this, restapi.ISpecModels>(this);\n}\n\n/**\n * The namespace for `KernelManager` class statics.\n */\nexport namespace KernelSpecManager {\n /**\n * The options used to initialize a KernelManager.\n */\n export interface IOptions extends BaseManager.IOptions {\n /**\n * When the manager stops polling the API. Defaults to `when-hidden`.\n */\n standby?: Poll.Standby | (() => boolean | Poll.Standby);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport * as KernelSpec from './kernelspec';\nimport * as KernelSpecAPI from './restapi';\n\nexport * from './manager';\nexport { KernelSpec, KernelSpecAPI };\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { URLExt } from '@jupyterlab/coreutils';\n\nimport { JSONExt, JSONObject, PromiseDelegate, UUID } from '@lumino/coreutils';\n\nimport { ISignal, Signal } from '@lumino/signaling';\n\nimport { ServerConnection } from '..';\n\nimport { CommHandler } from './comm';\n\nimport * as Kernel from './kernel';\n\nimport * as KernelMessage from './messages';\n\nimport {\n KernelControlFutureHandler,\n KernelFutureHandler,\n KernelShellFutureHandler\n} from './future';\n\nimport * as validate from './validate';\nimport { KernelSpec, KernelSpecAPI } from '../kernelspec';\n\nimport { KERNEL_SERVICE_URL, KernelAPIClient } from './restapi';\n\n// Stub for requirejs.\ndeclare let requirejs: any;\n\nconst KERNEL_INFO_TIMEOUT = 3000;\nconst RESTARTING_KERNEL_SESSION = '_RESTARTING_';\nconst STARTING_KERNEL_SESSION = '';\n\n/**\n * Implementation of the Kernel object.\n *\n * #### Notes\n * Messages from the server are handled in the order they were received and\n * asynchronously. Any message handler can return a promise, and message\n * handling will pause until the promise is fulfilled.\n */\nexport class KernelConnection implements Kernel.IKernelConnection {\n /**\n * Construct a kernel object.\n */\n constructor(options: Kernel.IKernelConnection.IOptions) {\n this._name = options.model.name;\n this._id = options.model.id;\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n this._kernelAPIClient =\n options.kernelAPIClient ??\n new KernelAPIClient({ serverSettings: this.serverSettings });\n this._clientId = options.clientId ?? UUID.uuid4();\n this._username = options.username ?? '';\n this.handleComms = options.handleComms ?? true;\n this._subshellId = options.subshellId ?? null;\n\n this._createSocket();\n }\n\n get disposed(): ISignal<this, void> {\n return this._disposed;\n }\n\n /**\n * The server settings for the kernel.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Handle comm messages\n *\n * #### Notes\n * The comm message protocol currently has implicit assumptions that only\n * one kernel connection is handling comm messages. This option allows a\n * kernel connection to opt out of handling comms.\n *\n * See https://github.com/jupyter/jupyter_client/issues/263\n */\n readonly handleComms: boolean;\n\n /**\n * A signal emitted when the kernel status changes.\n */\n get statusChanged(): ISignal<this, KernelMessage.Status> {\n return this._statusChanged;\n }\n\n /**\n * A signal emitted when the kernel status changes.\n */\n get connectionStatusChanged(): ISignal<this, Kernel.ConnectionStatus> {\n return this._connectionStatusChanged;\n }\n\n /**\n * A signal emitted for iopub kernel messages.\n *\n * #### Notes\n * This signal is emitted after the iopub message is handled asynchronously.\n */\n get iopubMessage(): ISignal<this, KernelMessage.IIOPubMessage> {\n return this._iopubMessage;\n }\n\n /**\n * A signal emitted for unhandled kernel message.\n *\n * #### Notes\n * This signal is emitted for a message that was not handled. It is emitted\n * during the asynchronous message handling code.\n */\n get unhandledMessage(): ISignal<this, KernelMessage.IMessage> {\n return this._unhandledMessage;\n }\n\n /**\n * The kernel model\n */\n get model(): Kernel.IModel {\n return (\n this._model || {\n id: this.id,\n name: this.name,\n reason: this._reason\n }\n );\n }\n\n /**\n * A signal emitted for any kernel message.\n *\n * #### Notes\n * This signal is emitted when a message is received, before it is handled\n * asynchronously.\n *\n * This message is emitted when a message is queued for sending (either in\n * the websocket buffer, or our own pending message buffer). The message may\n * actually be sent across the wire at a later time.\n *\n * The message emitted in this signal should not be modified in any way.\n */\n get anyMessage(): ISignal<this, Kernel.IAnyMessageArgs> {\n return this._anyMessage;\n }\n\n /**\n * A signal emitted when a kernel has pending inputs from the user.\n */\n get pendingInput(): ISignal<this, boolean> {\n return this._pendingInput;\n }\n\n /**\n * The id of the server-side kernel.\n */\n get id(): string {\n return this._id;\n }\n\n /**\n * The name of the server-side kernel.\n */\n get name(): string {\n return this._name;\n }\n\n /**\n * The client username.\n */\n get username(): string {\n return this._username;\n }\n\n /**\n * The client unique id.\n */\n get clientId(): string {\n return this._clientId;\n }\n\n /**\n * The subshell ID.\n */\n get subshellId(): string | null {\n return this._subshellId;\n }\n\n /**\n * Set the subshell ID.\n */\n set subshellId(value: string | null) {\n this._subshellId = value;\n }\n\n /**\n * The current status of the kernel.\n */\n get status(): KernelMessage.Status {\n return this._status;\n }\n\n /**\n * The current connection status of the kernel connection.\n */\n get connectionStatus(): Kernel.ConnectionStatus {\n return this._connectionStatus;\n }\n\n /**\n * Test whether the kernel has been disposed.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * The cached kernel info.\n *\n * @returns A promise that resolves to the kernel info.\n */\n get info(): Promise<KernelMessage.IInfoReply> {\n return this._info.promise;\n }\n\n /**\n * The kernel spec.\n *\n * @returns A promise that resolves to the kernel spec.\n */\n get spec(): Promise<KernelSpec.ISpecModel | undefined> {\n if (this._specPromise) {\n return this._specPromise;\n }\n this._specPromise = KernelSpecAPI.getSpecs(this.serverSettings).then(\n specs => {\n return specs.kernelspecs[this._name];\n }\n );\n return this._specPromise;\n }\n\n /**\n * Check if this kernel supports JEP 91 kernel subshells.\n */\n get supportsSubshells(): boolean {\n return this._supportsSubshells;\n }\n\n /**\n * Clone the current kernel with a new clientId.\n */\n clone(\n options: Pick<\n Kernel.IKernelConnection.IOptions,\n 'clientId' | 'username' | 'handleComms'\n > = {}\n ): Kernel.IKernelConnection {\n return new KernelConnection({\n model: this.model,\n username: this.username,\n serverSettings: this.serverSettings,\n // handleComms defaults to false since that is safer\n handleComms: false,\n kernelAPIClient: this._kernelAPIClient,\n ...options\n });\n }\n\n /**\n * Dispose of the resources held by the kernel.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n\n const cleanup = () => {\n this._isDisposed = true;\n this._disposed.emit();\n\n this._updateConnectionStatus('disconnected');\n this._clearKernelState();\n this._pendingMessages = [];\n this._clearSocket();\n\n // Clear Lumino signals\n Signal.clearData(this);\n };\n\n if (this._subshellId !== null) {\n const future = this.requestDeleteSubshell(\n { subshell_id: this._subshellId },\n true\n );\n future.onReply = (msg: KernelMessage.IDeleteSubshellReplyMsg): void => {\n // Ignore the response and clean up.\n cleanup();\n };\n } else {\n cleanup();\n }\n }\n\n /**\n * Send a shell message to the kernel.\n *\n * #### Notes\n * Send a message to the kernel's shell channel, yielding a future object\n * for accepting replies.\n *\n * If `expectReply` is given and `true`, the future is disposed when both a\n * shell reply and an idle status message are received. If `expectReply`\n * is not given or is `false`, the future is resolved when an idle status\n * message is received.\n * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.\n * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.\n *\n * All replies are validated as valid kernel messages.\n *\n * If the kernel status is `dead`, this will throw an error.\n */\n sendShellMessage<T extends KernelMessage.ShellMessageType>(\n msg: KernelMessage.IShellMessage<T>,\n expectReply = false,\n disposeOnDone = true\n ): Kernel.IShellFuture<KernelMessage.IShellMessage<T>> {\n return this._sendKernelShellControl(\n KernelShellFutureHandler,\n msg,\n expectReply,\n disposeOnDone\n ) as Kernel.IShellFuture<KernelMessage.IShellMessage<T>>;\n }\n\n /**\n * Send a control message to the kernel.\n *\n * #### Notes\n * Send a message to the kernel's control channel, yielding a future object\n * for accepting replies.\n *\n * If `expectReply` is given and `true`, the future is disposed when both a\n * control reply and an idle status message are received. If `expectReply`\n * is not given or is `false`, the future is resolved when an idle status\n * message is received.\n * If `disposeOnDone` is not given or is `true`, the Future is disposed at this point.\n * If `disposeOnDone` is given and `false`, it is up to the caller to dispose of the Future.\n *\n * All replies are validated as valid kernel messages.\n *\n * If the kernel status is `dead`, this will throw an error.\n */\n sendControlMessage<T extends KernelMessage.ControlMessageType>(\n msg: KernelMessage.IControlMessage<T>,\n expectReply = false,\n disposeOnDone = true\n ): Kernel.IControlFuture<KernelMessage.IControlMessage<T>> {\n return this._sendKernelShellControl(\n KernelControlFutureHandler,\n msg,\n expectReply,\n disposeOnDone\n ) as Kernel.IControlFuture<KernelMessage.IControlMessage<T>>;\n }\n\n private _sendKernelShellControl<\n REQUEST extends KernelMessage.IShellControlMessage,\n REPLY extends KernelMessage.IShellControlMessage,\n KFH extends new (...params: any[]) => KernelFutureHandler<REQUEST, REPLY>,\n T extends KernelMessage.IMessage\n >(\n ctor: KFH,\n msg: T,\n expectReply = false,\n disposeOnDone = true\n ): Kernel.IFuture<\n KernelMessage.IShellControlMessage,\n KernelMessage.IShellControlMessage\n > {\n this._sendMessage(msg);\n this._anyMessage.emit({ msg, direction: 'send' });\n\n const future = new ctor(\n () => {\n const msgId = msg.header.msg_id;\n this._futures.delete(msgId);\n // Remove stored display id information.\n const displayIds = this._msgIdToDisplayIds.get(msgId);\n if (!displayIds) {\n return;\n }\n displayIds.forEach(displayId => {\n const msgIds = this._displayIdToParentIds.get(displayId);\n if (msgIds) {\n const idx = msgIds.indexOf(msgId);\n if (idx === -1) {\n return;\n }\n if (msgIds.length === 1) {\n this._displayIdToParentIds.delete(displayId);\n } else {\n msgIds.splice(idx, 1);\n this._displayIdToParentIds.set(displayId, msgIds);\n }\n }\n });\n this._msgIdToDisplayIds.delete(msgId);\n },\n msg,\n expectReply,\n disposeOnDone,\n this\n );\n this._futures.set(msg.header.msg_id, future);\n return future;\n }\n\n /**\n * Send a message on the websocket.\n *\n * If queue is true, queue the message for later sending if we cannot send\n * now. Otherwise throw an error.\n *\n * #### Notes\n * As an exception to the queueing, if we are sending a kernel_info_request\n * message while we think the kernel is restarting, we send the message\n * immediately without queueing. This is so that we can trigger a message\n * back, which will then clear the kernel restarting state.\n */\n private _sendMessage(msg: KernelMessage.IMessage, queue = true) {\n if (this.status === 'dead') {\n throw new Error('Kernel is dead');\n }\n\n // If we have a kernel_info_request and we are starting or restarting, send the\n // kernel_info_request immediately if we can, and if not throw an error so\n // we can retry later. On restarting we do this because we must get at least one message\n // from the kernel to reset the kernel session (thus clearing the restart\n // status sentinel).\n if (\n (this._kernelSession === STARTING_KERNEL_SESSION ||\n this._kernelSession === RESTARTING_KERNEL_SESSION) &&\n KernelMessage.isInfoRequestMsg(msg)\n ) {\n if (this.connectionStatus === 'connected') {\n this._ws!.send(\n this.serverSettings.serializer.serialize(msg, this._ws!.protocol)\n );\n return;\n } else {\n throw new Error('Could not send message: status is not connected');\n }\n }\n\n // If there are pending messages, add to the queue so we keep messages in order\n if (queue && this._pendingMessages.length > 0) {\n this._pendingMessages.push(msg);\n return;\n }\n\n // Send if the ws allows it, otherwise queue the message.\n if (\n this.connectionStatus === 'connected' &&\n this._kernelSession !== RESTARTING_KERNEL_SESSION\n ) {\n this._ws!.send(\n this.serverSettings.serializer.serialize(msg, this._ws!.protocol)\n );\n } else if (queue) {\n this._pendingMessages.push(msg);\n } else {\n throw new Error('Could not send message');\n }\n }\n\n /**\n * Interrupt a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * It is assumed that the API call does not mutate the kernel id or name.\n *\n * The promise will be rejected if the kernel status is `Dead` or if the\n * request fails or the response is invalid.\n */\n async interrupt(): Promise<void> {\n this.hasPendingInput = false;\n if (this.status === 'dead') {\n throw new Error('Kernel is dead');\n }\n return this._kernelAPIClient.interrupt(this.id);\n }\n\n /**\n * Request a kernel restart.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels)\n * and validates the response model.\n *\n * Any existing Future or Comm objects are cleared once the kernel has\n * actually be restarted.\n *\n * The promise is fulfilled on a valid server response (after the kernel restarts)\n * and rejected otherwise.\n *\n * It is assumed that the API call does not mutate the kernel id or name.\n *\n * The promise will be rejected if the request fails or the response is\n * invalid.\n */\n async restart(): Promise<void> {\n if (this.status === 'dead') {\n throw new Error('Kernel is dead');\n }\n this._updateStatus('restarting');\n this._clearKernelState();\n this._kernelSession = RESTARTING_KERNEL_SESSION;\n await this._kernelAPIClient.restart(this.id);\n // Reconnect to the kernel to address cases where kernel ports\n // have changed during the restart.\n await this.reconnect();\n this.hasPendingInput = false;\n }\n\n /**\n * Reconnect to a kernel.\n *\n * #### Notes\n * This may try multiple times to reconnect to a kernel, and will sever any\n * existing connection.\n */\n reconnect(): Promise<void> {\n this._errorIfDisposed();\n const result = new PromiseDelegate<void>();\n\n // Set up a listener for the connection status changing, which accepts or\n // rejects after the retries are done.\n const fulfill = (sender: this, status: Kernel.ConnectionStatus) => {\n if (status === 'connected') {\n result.resolve();\n this.connectionStatusChanged.disconnect(fulfill, this);\n } else if (status === 'disconnected') {\n result.reject(new Error('Kernel connection disconnected'));\n this.connectionStatusChanged.disconnect(fulfill, this);\n }\n };\n this.connectionStatusChanged.connect(fulfill, this);\n\n // Reset the reconnect limit so we start the connection attempts fresh\n this._reconnectAttempt = 0;\n\n // Start the reconnection process, which will also clear any existing\n // connection.\n this._reconnect();\n\n // Return the promise that should resolve on connection or reject if the\n // retries don't work.\n return result.promise;\n }\n\n /**\n * Shutdown a kernel.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/kernels).\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n *\n * On a valid response, disposes this kernel connection.\n *\n * If the kernel is already `dead`, disposes this kernel connection without\n * a server request.\n */\n async shutdown(): Promise<void> {\n if (this.status !== 'dead') {\n await this._kernelAPIClient.shutdown(this.id);\n }\n this.handleShutdown();\n }\n\n /**\n * Handles a kernel shutdown.\n *\n * #### Notes\n * This method should be called if we know from outside information that a\n * kernel is dead (for example, we cannot find the kernel model on the\n * server).\n */\n handleShutdown(): void {\n this._updateStatus('dead');\n this.dispose();\n }\n\n /**\n * Send a `kernel_info_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#kernel-info).\n *\n * Fulfills with the `kernel_info_response` content when the shell reply is\n * received and validated.\n */\n async requestKernelInfo(): Promise<KernelMessage.IInfoReplyMsg | undefined> {\n const msg = KernelMessage.createMessage({\n msgType: 'kernel_info_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n subshellId: this._subshellId,\n content: {}\n });\n let reply: KernelMessage.IInfoReplyMsg | undefined;\n try {\n reply = (await Private.handleShellMessage(this, msg)) as\n | KernelMessage.IInfoReplyMsg\n | undefined;\n } catch (e) {\n // If we rejected because the future was disposed, ignore and return.\n if (this.isDisposed) {\n return;\n } else {\n throw e;\n }\n }\n this._errorIfDisposed();\n\n if (!reply) {\n return;\n }\n\n // Kernels sometimes do not include a status field on kernel_info_reply\n // messages, so set a default for now.\n // See https://github.com/jupyterlab/jupyterlab/issues/6760\n if (reply.content.status === undefined) {\n (reply.content as any).status = 'ok';\n }\n\n if (reply.content.status !== 'ok') {\n this._info.reject('Kernel info reply errored');\n return reply;\n }\n\n this._info.resolve(reply.content);\n\n this._kernelSession = reply.header.session;\n\n const supportedFeatures = reply.content.supported_features;\n this._supportsSubshells =\n supportedFeatures !== undefined &&\n supportedFeatures.includes('kernel subshells');\n\n return reply;\n }\n\n /**\n * Send a `complete_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#completion).\n *\n * Fulfills with the `complete_reply` content when the shell reply is\n * received and validated.\n */\n requestComplete(\n content: KernelMessage.ICompleteRequestMsg['content']\n ): Promise<KernelMessage.ICompleteReplyMsg> {\n const msg = KernelMessage.createMessage({\n msgType: 'complete_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n subshellId: this._subshellId,\n content\n });\n return Private.handleShellMessage(\n this,\n msg\n ) as Promise<KernelMessage.ICompleteReplyMsg>;\n }\n\n /**\n * Send an `inspect_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#introspection).\n *\n * Fulfills with the `inspect_reply` content when the shell reply is\n * received and validated.\n */\n requestInspect(\n content: KernelMessage.IInspectRequestMsg['content']\n ): Promise<KernelMessage.IInspectReplyMsg> {\n const msg = KernelMessage.createMessage({\n msgType: 'inspect_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n subshellId: this._subshellId,\n content: content\n });\n return Private.handleShellMessage(\n this,\n msg\n ) as Promise<KernelMessage.IInspectReplyMsg>;\n }\n\n /**\n * Send a `history_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#history).\n *\n * Fulfills with the `history_reply` content when the shell reply is\n * received and validated.\n */\n requestHistory(\n content: KernelMessage.IHistoryRequestMsg['content']\n ): Promise<KernelMessage.IHistoryReplyMsg> {\n const msg = KernelMessage.createMessage({\n msgType: 'history_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n subshellId: this._subshellId,\n content\n });\n return Private.handleShellMessage(\n this,\n msg\n ) as Promise<KernelMessage.IHistoryReplyMsg>;\n }\n\n /**\n * Send an `execute_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#execute).\n *\n * Future `onReply` is called with the `execute_reply` content when the\n * shell reply is received and validated. The future will resolve when\n * this message is received and the `idle` iopub status is received.\n * The future will also be disposed at this point unless `disposeOnDone`\n * is specified and `false`, in which case it is up to the caller to dispose\n * of the future.\n *\n * **See also:** [[IExecuteReply]]\n */\n requestExecute(\n content: KernelMessage.IExecuteRequestMsg['content'],\n disposeOnDone: boolean = true,\n metadata?: JSONObject\n ): Kernel.IShellFuture<\n KernelMessage.IExecuteRequestMsg,\n KernelMessage.IExecuteReplyMsg\n > {\n const defaults: JSONObject = {\n silent: false,\n store_history: true,\n user_expressions: {},\n allow_stdin: true,\n stop_on_error: false\n };\n const msg = KernelMessage.createMessage({\n msgType: 'execute_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n subshellId: this._subshellId,\n content: { ...defaults, ...content },\n metadata\n });\n return this.sendShellMessage(\n msg,\n true,\n disposeOnDone\n ) as Kernel.IShellFuture<\n KernelMessage.IExecuteRequestMsg,\n KernelMessage.IExecuteReplyMsg\n >;\n }\n\n /**\n * Send an experimental `debug_request` message.\n *\n * @hidden\n *\n * #### Notes\n * Debug messages are experimental messages that are not in the official\n * kernel message specification. As such, this function is *NOT* considered\n * part of the public API, and may change without notice.\n */\n requestDebug(\n content: KernelMessage.IDebugRequestMsg['content'],\n disposeOnDone: boolean = true\n ): Kernel.IControlFuture<\n KernelMessage.IDebugRequestMsg,\n KernelMessage.IDebugReplyMsg\n > {\n const msg = KernelMessage.createMessage({\n msgType: 'debug_request',\n channel: 'control',\n username: this._username,\n session: this._clientId,\n content\n });\n return this.sendControlMessage(\n msg,\n true,\n disposeOnDone\n ) as Kernel.IControlFuture<\n KernelMessage.IDebugRequestMsg,\n KernelMessage.IDebugReplyMsg\n >;\n }\n\n /**\n * Send a `create_subshell_request` message.\n *\n * https://github.com/jupyter/enhancement-proposals/pull/91\n */\n requestCreateSubshell(\n content: KernelMessage.ICreateSubshellRequestMsg['content'],\n disposeOnDone: boolean = true\n ): Kernel.IControlFuture<\n KernelMessage.ICreateSubshellRequestMsg,\n KernelMessage.ICreateSubshellReplyMsg\n > {\n if (!this.supportsSubshells) {\n throw new Error('Kernel subshells are not supported');\n }\n\n const msg = KernelMessage.createMessage({\n msgType: 'create_subshell_request',\n channel: 'control',\n username: this._username,\n session: this._clientId,\n content\n });\n return this.sendControlMessage(\n msg,\n true,\n disposeOnDone\n ) as Kernel.IControlFuture<\n KernelMessage.ICreateSubshellRequestMsg,\n KernelMessage.ICreateSubshellReplyMsg\n >;\n }\n\n /**\n * Send a `delete_subshell_request` message.\n *\n * https://github.com/jupyter/enhancement-proposals/pull/91\n */\n requestDeleteSubshell(\n content: KernelMessage.IDeleteSubshellRequestMsg['content'],\n disposeOnDone: boolean = true\n ): Kernel.IControlFuture<\n KernelMessage.IDeleteSubshellRequestMsg,\n KernelMessage.IDeleteSubshellReplyMsg\n > {\n if (!this.supportsSubshells) {\n throw new Error('Kernel subshells are not supported');\n }\n\n const msg = KernelMessage.createMessage({\n msgType: 'delete_subshell_request',\n channel: 'control',\n username: this._username,\n session: this._clientId,\n content\n });\n return this.sendControlMessage(\n msg,\n true,\n disposeOnDone\n ) as Kernel.IControlFuture<\n KernelMessage.IDeleteSubshellRequestMsg,\n KernelMessage.IDeleteSubshellReplyMsg\n >;\n }\n\n /**\n * Send a `list_subshell_request` message.\n *\n * https://github.com/jupyter/enhancement-proposals/pull/91\n */\n requestListSubshell(\n content: KernelMessage.IListSubshellRequestMsg['content'],\n disposeOnDone: boolean = true\n ): Kernel.IControlFuture<\n KernelMessage.IListSubshellRequestMsg,\n KernelMessage.IListSubshellReplyMsg\n > {\n if (!this.supportsSubshells) {\n throw new Error('Kernel subshells are not supported');\n }\n\n const msg = KernelMessage.createMessage({\n msgType: 'list_subshell_request',\n channel: 'control',\n username: this._username,\n session: this._clientId,\n content\n });\n return this.sendControlMessage(\n msg,\n true,\n disposeOnDone\n ) as Kernel.IControlFuture<\n KernelMessage.IListSubshellRequestMsg,\n KernelMessage.IListSubshellReplyMsg\n >;\n }\n\n /**\n * Send an `is_complete_request` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#code-completeness).\n *\n * Fulfills with the `is_complete_response` content when the shell reply is\n * received and validated.\n */\n requestIsComplete(\n content: KernelMessage.IIsCompleteRequestMsg['content']\n ): Promise<KernelMessage.IIsCompleteReplyMsg> {\n const msg = KernelMessage.createMessage({\n msgType: 'is_complete_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n subshellId: this._subshellId,\n content\n });\n return Private.handleShellMessage(\n this,\n msg\n ) as Promise<KernelMessage.IIsCompleteReplyMsg>;\n }\n\n /**\n * Send a `comm_info_request` message.\n *\n * #### Notes\n * Fulfills with the `comm_info_reply` content when the shell reply is\n * received and validated.\n */\n requestCommInfo(\n content: KernelMessage.ICommInfoRequestMsg['content']\n ): Promise<KernelMessage.ICommInfoReplyMsg> {\n const msg = KernelMessage.createMessage({\n msgType: 'comm_info_request',\n channel: 'shell',\n username: this._username,\n session: this._clientId,\n subshellId: this._subshellId,\n content\n });\n return Private.handleShellMessage(\n this,\n msg\n ) as Promise<KernelMessage.ICommInfoReplyMsg>;\n }\n\n /**\n * Send an `input_reply` message.\n *\n * #### Notes\n * See [Messaging in Jupyter](https://jupyter-client.readthedocs.io/en/latest/messaging.html#messages-on-the-stdin-router-dealer-sockets).\n */\n sendInputReply(\n content: KernelMessage.IInputReplyMsg['content'],\n parent_header: KernelMessage.IInputReplyMsg['parent_header']\n ): void {\n const msg = KernelMessage.createMessage({\n msgType: 'input_reply',\n channel: 'stdin',\n username: this._username,\n session: this._clientId,\n content\n });\n msg.parent_header = parent_header;\n\n this._sendMessage(msg);\n this._anyMessage.emit({ msg, direction: 'send' });\n\n this.hasPendingInput = false;\n }\n\n /**\n * Create a new comm.\n *\n * #### Notes\n * If a client-side comm already exists with the given commId, an error is thrown.\n * If the kernel does not handle comms, an error is thrown.\n */\n createComm(targetName: string, commId: string = UUID.uuid4()): Kernel.IComm {\n if (!this.handleComms) {\n throw new Error('Comms are disabled on this kernel connection');\n }\n if (this._comms.has(commId)) {\n throw new Error('Comm is already created');\n }\n\n const comm = new CommHandler(targetName, commId, this, () => {\n this._unregisterComm(commId);\n });\n this._comms.set(commId, comm);\n return comm;\n }\n\n /**\n * Check if a comm exists.\n */\n hasComm(commId: string): boolean {\n return this._comms.has(commId);\n }\n\n /**\n * Register a comm target handler.\n *\n * @param targetName - The name of the comm target.\n *\n * @param callback - The callback invoked for a comm open message.\n *\n * @returns A disposable used to unregister the comm target.\n *\n * #### Notes\n * Only one comm target can be registered to a target name at a time, an\n * existing callback for the same target name will be overridden. A registered\n * comm target handler will take precedence over a comm which specifies a\n * `target_module`.\n *\n * If the callback returns a promise, kernel message processing will pause\n * until the returned promise is fulfilled.\n */\n registerCommTarget(\n targetName: string,\n callback: (\n comm: Kernel.IComm,\n msg: KernelMessage.ICommOpenMsg\n ) => void | PromiseLike<void>\n ): void {\n if (!this.handleComms) {\n return;\n }\n\n this._targetRegistry[targetName] = callback;\n }\n\n /**\n * Remove a comm target handler.\n *\n * @param targetName - The name of the comm target to remove.\n *\n * @param callback - The callback to remove.\n *\n * #### Notes\n * The comm target is only removed if the callback argument matches.\n */\n removeCommTarget(\n targetName: string,\n callback: (\n comm: Kernel.IComm,\n msg: KernelMessage.ICommOpenMsg\n ) => void | PromiseLike<void>\n ): void {\n if (!this.handleComms) {\n return;\n }\n\n if (!this.isDisposed && this._targetRegistry[targetName] === callback) {\n delete this._targetRegistry[targetName];\n }\n }\n\n /**\n * Register an IOPub message hook.\n *\n * @param msg_id - The parent_header message id the hook will intercept.\n *\n * @param hook - The callback invoked for the message.\n *\n * #### Notes\n * The IOPub hook system allows you to preempt the handlers for IOPub\n * messages that are responses to a given message id.\n *\n * The most recently registered hook is run first. A hook can return a\n * boolean or a promise to a boolean, in which case all kernel message\n * processing pauses until the promise is fulfilled. If a hook return value\n * resolves to false, any later hooks will not run and the function will\n * return a promise resolving to false. If a hook throws an error, the error\n * is logged to the console and the next hook is run. If a hook is\n * registered during the hook processing, it will not run until the next\n * message. If a hook is removed during the hook processing, it will be\n * deactivated immediately.\n *\n * See also [[IFuture.registerMessageHook]].\n */\n registerMessageHook(\n msgId: string,\n hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>\n ): void {\n const future = this._futures?.get(msgId);\n if (future) {\n future.registerMessageHook(hook);\n }\n }\n\n /**\n * Remove an IOPub message hook.\n *\n * @param msg_id - The parent_header message id the hook intercepted.\n *\n * @param hook - The callback invoked for the message.\n *\n */\n removeMessageHook(\n msgId: string,\n hook: (msg: KernelMessage.IIOPubMessage) => boolean | PromiseLike<boolean>\n ): void {\n const future = this._futures?.get(msgId);\n if (future) {\n future.removeMessageHook(hook);\n }\n }\n\n /**\n * Remove the input guard, if any.\n */\n removeInputGuard() {\n this.hasPendingInput = false;\n }\n\n /**\n * Handle a message with a display id.\n *\n * @returns Whether the message was handled.\n */\n private async _handleDisplayId(\n displayId: string,\n msg: KernelMessage.IMessage\n ): Promise<boolean> {\n const msgId = (msg.parent_header as KernelMessage.IHeader).msg_id;\n let parentIds = this._displayIdToParentIds.get(displayId);\n if (parentIds) {\n // We've seen it before, update existing outputs with same display_id\n // by handling display_data as update_display_data.\n const updateMsg: KernelMessage.IMessage = {\n header: JSONExt.deepCopy(\n msg.header as unknown as JSONObject\n ) as unknown as KernelMessage.IHeader,\n parent_header: JSONExt.deepCopy(\n msg.parent_header as unknown as JSONObject\n ) as unknown as KernelMessage.IHeader,\n metadata: JSONExt.deepCopy(msg.metadata),\n content: JSONExt.deepCopy(msg.content as JSONObject),\n channel: msg.channel,\n buffers: msg.buffers ? msg.buffers.slice() : []\n };\n (updateMsg.header as any).msg_type = 'update_display_data';\n\n await Promise.all(\n parentIds.map(async parentId => {\n const future = this._futures && this._futures.get(parentId);\n if (future) {\n await future.handleMsg(updateMsg);\n }\n })\n );\n }\n\n // We're done here if it's update_display.\n if (msg.header.msg_type === 'update_display_data') {\n // It's an update, don't proceed to the normal display.\n return true;\n }\n\n // Regular display_data with id, record it for future updating\n // in _displayIdToParentIds for future lookup.\n parentIds = this._displayIdToParentIds.get(displayId) ?? [];\n if (parentIds.indexOf(msgId) === -1) {\n parentIds.push(msgId);\n }\n this._displayIdToParentIds.set(displayId, parentIds);\n\n // Add to our map of display ids for this message.\n const displayIds = this._msgIdToDisplayIds.get(msgId) ?? [];\n if (displayIds.indexOf(msgId) === -1) {\n displayIds.push(msgId);\n }\n this._msgIdToDisplayIds.set(msgId, displayIds);\n\n // Let the message propagate to the intended recipient.\n return false;\n }\n\n /**\n * Forcefully clear the socket state.\n *\n * #### Notes\n * This will clear all socket state without calling any handlers and will\n * not update the connection status. If you call this method, you are\n * responsible for updating the connection status as needed and recreating\n * the socket if you plan to reconnect.\n */\n private _clearSocket(): void {\n if (this._ws !== null) {\n // Clear the websocket event handlers and the socket itself.\n this._ws.onopen = this._noOp;\n this._ws.onclose = this._noOp;\n this._ws.onerror = this._noOp;\n this._ws.onmessage = this._noOp;\n this._ws.close();\n this._ws = null;\n }\n }\n\n /**\n * Handle status iopub messages from the kernel.\n */\n private _updateStatus(status: KernelMessage.Status): void {\n if (this._status === status || this._status === 'dead') {\n return;\n }\n\n this._status = status;\n Private.logKernelStatus(this);\n this._statusChanged.emit(status);\n if (status === 'dead') {\n this.dispose();\n }\n }\n\n /**\n * Send pending messages to the kernel.\n */\n private _sendPending(): void {\n // We check to make sure we are still connected each time. For\n // example, if a websocket buffer overflows, it may close, so we should\n // stop sending messages.\n while (\n this.connectionStatus === 'connected' &&\n this._kernelSession !== RESTARTING_KERNEL_SESSION &&\n this._pendingMessages.length > 0\n ) {\n this._sendMessage(this._pendingMessages[0], false);\n\n // We shift the message off the queue after the message is sent so that\n // if there is an exception, the message is still pending.\n this._pendingMessages.shift();\n }\n }\n\n /**\n * Clear the internal state.\n */\n private _clearKernelState(): void {\n this._kernelSession = '';\n this._pendingMessages = [];\n this._futures.forEach(future => {\n future.dispose();\n });\n this._comms.forEach(comm => {\n comm.dispose();\n });\n this._msgChain = Promise.resolve();\n this._futures = new Map<\n string,\n KernelFutureHandler<\n KernelMessage.IShellControlMessage,\n KernelMessage.IShellControlMessage\n >\n >();\n this._comms = new Map<string, Kernel.IComm>();\n this._displayIdToParentIds.clear();\n this._msgIdToDisplayIds.clear();\n }\n\n /**\n * Check to make sure it is okay to proceed to handle a message.\n *\n * #### Notes\n * Because we handle messages asynchronously, before a message is handled the\n * kernel might be disposed or restarted (and have a different session id).\n * This function throws an error in each of these cases. This is meant to be\n * called at the start of an asynchronous message handler to cancel message\n * processing if the message no longer is valid.\n */\n private _assertCurrentMessage(msg: KernelMessage.IMessage) {\n this._errorIfDisposed();\n\n if (msg.header.session !== this._kernelSession) {\n throw new Error(\n `Canceling handling of old message: ${msg.header.msg_type}`\n );\n }\n }\n\n /**\n * Handle a `comm_open` kernel message.\n */\n private async _handleCommOpen(\n msg: KernelMessage.ICommOpenMsg\n ): Promise<void> {\n this._assertCurrentMessage(msg);\n const content = msg.content;\n const comm = new CommHandler(\n content.target_name,\n content.comm_id,\n this,\n () => {\n this._unregisterComm(content.comm_id);\n }\n );\n this._comms.set(content.comm_id, comm);\n\n try {\n const target = await Private.loadObject(\n content.target_name,\n content.target_module,\n this._targetRegistry\n );\n await target(comm, msg);\n } catch (e) {\n // Close the comm asynchronously. We cannot block message processing on\n // kernel messages to wait for another kernel message.\n comm.close();\n console.error('Exception opening new comm');\n throw e;\n }\n }\n\n /**\n * Handle 'comm_close' kernel message.\n */\n private async _handleCommClose(\n msg: KernelMessage.ICommCloseMsg\n ): Promise<void> {\n this._assertCurrentMessage(msg);\n const content = msg.content;\n const comm = this._comms.get(content.comm_id);\n if (!comm) {\n console.error('Comm not found for comm id ' + content.comm_id);\n return;\n }\n this._unregisterComm(comm.commId);\n const onClose = comm.onClose;\n if (onClose) {\n // tslint:disable-next-line:await-promise\n await onClose(msg);\n }\n (comm as CommHandler).dispose();\n }\n\n /**\n * Handle a 'comm_msg' kernel message.\n */\n private async _handleCommMsg(msg: KernelMessage.ICommMsgMsg): Promise<void> {\n this._assertCurrentMessage(msg);\n const content = msg.content;\n const comm = this._comms.get(content.comm_id);\n if (!comm) {\n return;\n }\n const onMsg = comm.onMsg;\n if (onMsg) {\n // tslint:disable-next-line:await-promise\n await onMsg(msg);\n }\n }\n\n /**\n * Unregister a comm instance.\n */\n private _unregisterComm(commId: string) {\n this._comms.delete(commId);\n }\n\n /**\n * Create the kernel websocket connection and add socket status handlers.\n */\n private _createSocket = (useProtocols = true) => {\n this._errorIfDisposed();\n\n // Make sure the socket is clear\n this._clearSocket();\n\n // Update the connection status to reflect opening a new connection.\n this._updateConnectionStatus('connecting');\n\n const settings = this.serverSettings;\n const partialUrl = URLExt.join(\n settings.wsUrl,\n KERNEL_SERVICE_URL,\n encodeURIComponent(this._id)\n );\n\n // Strip any authentication from the display string.\n const display = partialUrl.replace(/^((?:\\w+:)?\\/\\/)(?:[^@\\/]+@)/, '$1');\n console.debug(`Starting WebSocket: ${display}`);\n\n let url = URLExt.join(\n partialUrl,\n 'channels?session_id=' + encodeURIComponent(this._clientId)\n );\n\n // If token authentication is in use.\n const token = settings.token;\n if (settings.appendToken && token !== '') {\n url = url + `&token=${encodeURIComponent(token)}`;\n }\n\n // Try opening the websocket with our list of subprotocols.\n // If the server doesn't handle subprotocols,\n // the accepted protocol will be ''.\n // But we cannot send '' as a subprotocol, so if connection fails,\n // reconnect without subprotocols.\n const supportedProtocols = useProtocols ? this._supportedProtocols : [];\n this._ws = new settings.WebSocket(url, supportedProtocols);\n\n // Ensure incoming binary messages are not Blobs\n this._ws.binaryType = 'arraybuffer';\n\n let alreadyCalledOnclose = false;\n\n const getKernelModel = async (evt: Event) => {\n if (this._isDisposed) {\n return;\n }\n this._reason = '';\n this._model = undefined;\n try {\n const model = await this._kernelAPIClient.getModel(this._id);\n this._model = model;\n if (model?.execution_state === 'dead') {\n this._updateStatus('dead');\n } else {\n this._onWSClose(evt);\n }\n } catch (err) {\n // Try again, if there is a network failure\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (\n err instanceof ServerConnection.NetworkError ||\n err.response?.status === 503 ||\n err.response?.status === 424\n ) {\n const timeout = Private.getRandomIntInclusive(10, 30) * 1e3;\n setTimeout(getKernelModel, timeout, evt);\n } else {\n this._reason = 'Kernel died unexpectedly';\n this._updateStatus('dead');\n }\n }\n return;\n };\n\n const earlyClose = async (evt: Event) => {\n // If the websocket was closed early, that could mean\n // that the kernel is actually dead. Try getting\n // information about the kernel from the API call,\n // if that fails, then assume the kernel is dead,\n // otherwise just follow the typical websocket closed\n // protocol.\n if (alreadyCalledOnclose) {\n return;\n }\n alreadyCalledOnclose = true;\n await getKernelModel(evt);\n\n return;\n };\n\n this._ws.onmessage = this._onWSMessage;\n this._ws.onopen = this._onWSOpen;\n this._ws.onclose = earlyClose;\n this._ws.onerror = earlyClose;\n };\n\n /**\n * Handle connection status changes.\n */\n private _updateConnectionStatus(\n connectionStatus: Kernel.ConnectionStatus\n ): void {\n if (this._connectionStatus === connectionStatus) {\n return;\n }\n\n this._connectionStatus = connectionStatus;\n\n // If we are not 'connecting', reset any reconnection attempts.\n if (connectionStatus !== 'connecting') {\n this._reconnectAttempt = 0;\n clearTimeout(this._reconnectTimeout);\n }\n\n if (this.status !== 'dead') {\n if (connectionStatus === 'connected') {\n let restarting = this._kernelSession === RESTARTING_KERNEL_SESSION;\n\n // Send a kernel info request to make sure we send at least one\n // message to get kernel status back. Always request kernel info\n // first, to get kernel status back and ensure iopub is fully\n // established. If we are restarting, this message will skip the queue\n // and be sent immediately.\n let p = this.requestKernelInfo();\n\n // Send any pending messages after the kernelInfo resolves, or after a\n // timeout as a failsafe.\n\n let sendPendingCalled = false;\n let sendPendingOnce = () => {\n if (sendPendingCalled) {\n return;\n }\n sendPendingCalled = true;\n if (restarting && this._kernelSession === RESTARTING_KERNEL_SESSION) {\n // We were restarting and a message didn't arrive to set the\n // session, but we just assume the restart succeeded and send any\n // pending messages.\n\n // FIXME: it would be better to retry the kernel_info_request here\n this._kernelSession = '';\n }\n clearTimeout(timeoutHandle);\n if (this._pendingMessages.length > 0) {\n this._sendPending();\n }\n };\n void p.then(sendPendingOnce);\n // FIXME: if sent while zmq subscriptions are not established,\n // kernelInfo may not resolve, so use a timeout to ensure we don't hang forever.\n // It may be preferable to retry kernelInfo rather than give up after one timeout.\n let timeoutHandle = setTimeout(sendPendingOnce, KERNEL_INFO_TIMEOUT);\n } else {\n // If the connection is down, then we do not know what is happening\n // with the kernel, so set the status to unknown.\n this._updateStatus('unknown');\n }\n }\n\n // Notify others that the connection status changed.\n this._connectionStatusChanged.emit(connectionStatus);\n }\n\n private async _handleMessage(msg: KernelMessage.IMessage): Promise<void> {\n let handled = false;\n\n // Check to see if we have a display_id we need to reroute.\n if (\n msg.parent_header &&\n msg.channel === 'iopub' &&\n (KernelMessage.isDisplayDataMsg(msg) ||\n KernelMessage.isUpdateDisplayDataMsg(msg) ||\n KernelMessage.isExecuteResultMsg(msg))\n ) {\n // display_data messages may re-route based on their display_id.\n const transient = (msg.content.transient ?? {}) as JSONObject;\n const displayId = transient['display_id'] as string;\n if (displayId) {\n handled = await this._handleDisplayId(displayId, msg);\n // The await above may make this message out of date, so check again.\n this._assertCurrentMessage(msg);\n }\n }\n\n if (!handled && msg.parent_header) {\n const parentHeader = msg.parent_header as KernelMessage.IHeader;\n const future = this._futures?.get(parentHeader.msg_id);\n if (future) {\n await future.handleMsg(msg);\n this._assertCurrentMessage(msg);\n } else {\n // If the message was sent by us and was not iopub, it is orphaned.\n const owned = parentHeader.session === this.clientId;\n if (msg.channel !== 'iopub' && owned) {\n this._unhandledMessage.emit(msg);\n }\n }\n }\n if (msg.channel === 'iopub') {\n switch (msg.header.msg_type) {\n case 'status': {\n // Updating the status is synchronous, and we call no async user code\n const executionState = (msg as KernelMessage.IStatusMsg).content\n .execution_state;\n if (executionState === 'restarting') {\n // The kernel has been auto-restarted by the server. After\n // processing for this message is completely done, we want to\n // handle this restart, so we don't await, but instead schedule\n // the work as a microtask (i.e., in a promise resolution). We\n // schedule this here so that it comes before any microtasks that\n // might be scheduled in the status signal emission below.\n void Promise.resolve().then(async () => {\n this._updateStatus('autorestarting');\n this._clearKernelState();\n\n // We must reconnect since the kernel connection information may have\n // changed, and the server only refreshes its zmq connection when a new\n // websocket is opened.\n await this.reconnect();\n });\n }\n this._updateStatus(executionState);\n break;\n }\n case 'comm_open':\n if (this.handleComms) {\n await this._handleCommOpen(msg as KernelMessage.ICommOpenMsg);\n }\n break;\n case 'comm_msg':\n if (this.handleComms) {\n await this._handleCommMsg(msg as KernelMessage.ICommMsgMsg);\n }\n break;\n case 'comm_close':\n if (this.handleComms) {\n await this._handleCommClose(msg as KernelMessage.ICommCloseMsg);\n }\n break;\n default:\n break;\n }\n // If the message was a status dead message, we might have disposed ourselves.\n if (!this.isDisposed) {\n this._assertCurrentMessage(msg);\n // the message wouldn't be emitted if we were disposed anyway.\n this._iopubMessage.emit(msg as KernelMessage.IIOPubMessage);\n }\n }\n }\n\n /**\n * Attempt a connection if we have not exhausted connection attempts.\n */\n private _reconnect() {\n this._errorIfDisposed();\n\n // Clear any existing reconnection attempt\n clearTimeout(this._reconnectTimeout);\n\n // Update the connection status and schedule a possible reconnection.\n if (this._reconnectAttempt < this._reconnectLimit) {\n this._updateConnectionStatus('connecting');\n\n // The first reconnect attempt should happen immediately, and subsequent\n // attempts should pick a random number in a growing range so that we\n // don't overload the server with synchronized reconnection attempts\n // across multiple kernels.\n const timeout = Private.getRandomIntInclusive(\n 0,\n 1e3 * (Math.pow(2, this._reconnectAttempt) - 1)\n );\n console.warn(\n `Connection lost, reconnecting in ${Math.floor(\n timeout / 1000\n )} seconds.`\n );\n // Try reconnection with subprotocols if the server had supported them.\n // Otherwise, try reconnection without subprotocols.\n const useProtocols = this._selectedProtocol !== '' ? true : false;\n this._reconnectTimeout = setTimeout(\n this._createSocket,\n timeout,\n useProtocols\n );\n this._reconnectAttempt += 1;\n } else {\n this._updateConnectionStatus('disconnected');\n }\n\n // Clear the websocket event handlers and the socket itself.\n this._clearSocket();\n }\n\n /**\n * Utility function to throw an error if this instance is disposed.\n */\n private _errorIfDisposed() {\n if (this.isDisposed) {\n throw new Error('Kernel connection is disposed');\n }\n }\n\n // Make websocket callbacks arrow functions so they bind `this`.\n\n /**\n * Handle a websocket open event.\n */\n private _onWSOpen = (evt: Event) => {\n if (\n this._ws!.protocol !== '' &&\n !this._supportedProtocols.includes(this._ws!.protocol)\n ) {\n console.log(\n 'Server selected unknown kernel wire protocol:',\n this._ws!.protocol\n );\n this._updateStatus('dead');\n throw new Error(`Unknown kernel wire protocol: ${this._ws!.protocol}`);\n }\n // Remember the kernel wire protocol selected by the server.\n this._selectedProtocol = this._ws!.protocol;\n this._ws!.onclose = this._onWSClose;\n this._ws!.onerror = this._onWSClose;\n this._updateConnectionStatus('connected');\n };\n\n /**\n * Handle a websocket message, validating and routing appropriately.\n */\n private _onWSMessage = (evt: MessageEvent) => {\n // Notify immediately if there is an error with the message.\n let msg: KernelMessage.IMessage;\n try {\n msg = this.serverSettings.serializer.deserialize(\n evt.data,\n this._ws!.protocol\n );\n validate.validateMessage(msg);\n } catch (error) {\n error.message = `Kernel message validation error: ${error.message}`;\n // We throw the error so that it bubbles up to the top, and displays the right stack.\n throw error;\n }\n\n // Update the current kernel session id\n this._kernelSession = msg.header.session;\n\n // Handle the message asynchronously, in the order received.\n this._msgChain = this._msgChain\n .then(() => {\n // Return so that any promises from handling a message are fulfilled\n // before proceeding to the next message.\n return this._handleMessage(msg);\n })\n .catch(error => {\n // Log any errors in handling the message, thus resetting the _msgChain\n // promise so we can process more messages.\n // Ignore the \"Canceled\" errors that are thrown during kernel dispose.\n if (error.message.startsWith('Canceled future for ')) {\n console.error(error);\n }\n });\n\n // Emit the message receive signal\n this._anyMessage.emit({ msg, direction: 'recv' });\n };\n\n /**\n * Handle a websocket close event.\n */\n private _onWSClose = (evt: Event) => {\n if (!this.isDisposed) {\n this._reconnect();\n }\n };\n\n get hasPendingInput(): boolean {\n return this._hasPendingInput;\n }\n set hasPendingInput(value: boolean) {\n this._hasPendingInput = value;\n this._pendingInput.emit(value);\n }\n\n private _id = '';\n private _name = '';\n private _model: Kernel.IModel | undefined;\n private _status: KernelMessage.Status = 'unknown';\n private _connectionStatus: Kernel.ConnectionStatus = 'connecting';\n private _kernelSession = '';\n private _clientId: string;\n private _isDisposed = false;\n /**\n * Websocket to communicate with kernel.\n */\n private _ws: WebSocket | null = null;\n private _kernelAPIClient: Kernel.IKernelAPIClient;\n private _username = '';\n private _reconnectLimit = 7;\n private _reconnectAttempt = 0;\n private _reconnectTimeout: any = null;\n private _supportedProtocols: string[] = Object.values(\n KernelMessage.supportedKernelWebSocketProtocols\n );\n private _selectedProtocol: string = '';\n\n private _futures = new Map<\n string,\n KernelFutureHandler<\n KernelMessage.IShellControlMessage,\n KernelMessage.IShellControlMessage\n >\n >();\n private _comms = new Map<string, Kernel.IComm>();\n private _targetRegistry: {\n [key: string]: (\n comm: Kernel.IComm,\n msg: KernelMessage.ICommOpenMsg\n ) => void;\n } = Object.create(null);\n private _info = new PromiseDelegate<KernelMessage.IInfoReply>();\n private _pendingMessages: KernelMessage.IMessage[] = [];\n private _specPromise: Promise<KernelSpec.ISpecModel | undefined>;\n private _statusChanged = new Signal<this, KernelMessage.Status>(this);\n private _connectionStatusChanged = new Signal<this, Kernel.ConnectionStatus>(\n this\n );\n private _disposed = new Signal<this, void>(this);\n private _iopubMessage = new Signal<this, KernelMessage.IIOPubMessage>(this);\n private _anyMessage = new Signal<this, Kernel.IAnyMessageArgs>(this);\n private _pendingInput = new Signal<this, boolean>(this);\n private _unhandledMessage = new Signal<this, KernelMessage.IMessage>(this);\n private _displayIdToParentIds = new Map<string, string[]>();\n private _msgIdToDisplayIds = new Map<string, string[]>();\n private _msgChain: Promise<void> = Promise.resolve();\n private _hasPendingInput = false;\n private _reason = '';\n private _noOp = () => {\n /* no-op */\n };\n\n private _supportsSubshells = false;\n private _subshellId: string | null;\n}\n\n/**\n * A private namespace for the Kernel.\n */\nnamespace Private {\n /**\n * Log the current kernel status.\n */\n export function logKernelStatus(kernel: Kernel.IKernelConnection): void {\n switch (kernel.status) {\n case 'idle':\n case 'busy':\n case 'unknown':\n return;\n default:\n console.debug(`Kernel: ${kernel.status} (${kernel.id})`);\n break;\n }\n }\n\n /**\n * Send a kernel message to the kernel and resolve the reply message.\n */\n export async function handleShellMessage<\n T extends KernelMessage.ShellMessageType\n >(\n kernel: Kernel.IKernelConnection,\n msg: KernelMessage.IShellMessage<T>\n ): Promise<KernelMessage.IShellMessage<KernelMessage.ShellMessageType>> {\n const future = kernel.sendShellMessage(msg, true);\n return future.done;\n }\n\n /**\n * Try to load an object from a module or a registry.\n *\n * Try to load an object from a module asynchronously if a module\n * is specified, otherwise tries to load an object from the global\n * registry, if the global registry is provided.\n *\n * #### Notes\n * Loading a module uses requirejs.\n */\n export function loadObject(\n name: string,\n moduleName: string | undefined,\n registry?: { [key: string]: any }\n ): Promise<any> {\n return new Promise((resolve, reject) => {\n // Try loading the module using require.js\n if (moduleName) {\n if (typeof requirejs === 'undefined') {\n throw new Error('requirejs not found');\n }\n requirejs(\n [moduleName],\n (mod: any) => {\n if (mod[name] === void 0) {\n const msg = `Object '${name}' not found in module '${moduleName}'`;\n reject(new Error(msg));\n } else {\n resolve(mod[name]);\n }\n },\n reject\n );\n } else {\n if (registry?.[name]) {\n resolve(registry[name]);\n } else {\n reject(new Error(`Object '${name}' not found in registry`));\n }\n }\n });\n }\n\n /**\n * Get a random integer between min and max, inclusive of both.\n *\n * #### Notes\n * From\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive\n *\n * From the MDN page: It might be tempting to use Math.round() to accomplish\n * that, but doing so would cause your random numbers to follow a non-uniform\n * distribution, which may not be acceptable for your needs.\n */\n export function getRandomIntInclusive(min: number, max: number): number {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { Poll } from '@lumino/polling';\nimport { ISignal, Signal } from '@lumino/signaling';\nimport { ServerConnection } from '..';\nimport * as Kernel from './kernel';\nimport { BaseManager } from '../basemanager';\nimport { IKernelOptions, KernelAPIClient } from './restapi';\nimport { KernelConnection } from './default';\n\n/**\n * An implementation of a kernel manager.\n */\nexport class KernelManager extends BaseManager implements Kernel.IManager {\n /**\n * Construct a new kernel manager.\n *\n * @param options - The default options for kernel.\n */\n constructor(options: KernelManager.IOptions = {}) {\n super(options);\n\n this._kernelAPIClient =\n options.kernelAPIClient ??\n new KernelAPIClient({ serverSettings: this.serverSettings });\n\n // Start model and specs polling with exponential backoff.\n this._pollModels = new Poll({\n auto: false,\n factory: () => this.requestRunning(),\n frequency: {\n interval: 10 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:KernelManager#models`,\n standby: options.standby ?? 'when-hidden'\n });\n\n // Initialize internal data.\n this._ready = (async () => {\n await this._pollModels.start();\n await this._pollModels.tick;\n this._isReady = true;\n })();\n }\n\n /**\n * The server settings for the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Test whether the manager is ready.\n */\n get isReady(): boolean {\n return this._isReady;\n }\n\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready(): Promise<void> {\n return this._ready;\n }\n\n /**\n * A signal emitted when the running kernels change.\n */\n get runningChanged(): ISignal<this, Kernel.IModel[]> {\n return this._runningChanged;\n }\n\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure(): ISignal<this, Error> {\n return this._connectionFailure;\n }\n\n /**\n * Dispose of the resources used by the manager.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this._models.clear();\n this._kernelConnections.forEach(x => x.dispose());\n this._pollModels.dispose();\n super.dispose();\n }\n\n /**\n * Connect to an existing kernel.\n *\n * @returns The new kernel connection.\n *\n * #### Notes\n * This will use the manager's server settings and ignore any server\n * settings passed in the options.\n */\n connectTo(\n options: Omit<Kernel.IKernelConnection.IOptions, 'serverSettings'>\n ): Kernel.IKernelConnection {\n const { id } = options.model;\n\n let handleComms = options.handleComms ?? true;\n // By default, handle comms only if no other kernel connection is.\n if (options.handleComms === undefined) {\n for (const kc of this._kernelConnections) {\n if (kc.id === id && kc.handleComms) {\n handleComms = false;\n break;\n }\n }\n }\n const kernelConnection = new KernelConnection({\n handleComms,\n ...options,\n serverSettings: this.serverSettings,\n kernelAPIClient: this._kernelAPIClient\n });\n this._onStarted(kernelConnection);\n if (!this._models.has(id)) {\n // We trust the user to connect to an existing kernel, but we verify\n // asynchronously.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n return kernelConnection;\n }\n\n /**\n * Create an iterator over the most recent running kernels.\n *\n * @returns A new iterator over the running kernels.\n */\n running(): IterableIterator<Kernel.IModel> {\n return this._models.values();\n }\n\n /**\n * The number of running kernels.\n */\n get runningCount(): number {\n return this._models.size;\n }\n\n /**\n * Force a refresh of the running kernels.\n *\n * @returns A promise that resolves when the running list has been refreshed.\n *\n * #### Notes\n * This is not typically meant to be called by the user, since the\n * manager maintains its own internal state.\n */\n async refreshRunning(): Promise<void> {\n await this._pollModels.refresh();\n await this._pollModels.tick;\n }\n\n /**\n * Start a new kernel.\n *\n * @param createOptions - The kernel creation options\n *\n * @param connectOptions - The kernel connection options\n *\n * @returns A promise that resolves with the kernel connection.\n *\n * #### Notes\n * The manager `serverSettings` will be always be used.\n */\n async startNew(\n createOptions: IKernelOptions = {},\n connectOptions: Omit<\n Kernel.IKernelConnection.IOptions,\n 'model' | 'serverSettings'\n > = {}\n ): Promise<Kernel.IKernelConnection> {\n const model = await this._kernelAPIClient.startNew(createOptions);\n return this.connectTo({\n ...connectOptions,\n model\n });\n }\n\n /**\n * Shut down a kernel by id.\n *\n * @param id - The id of the target kernel.\n *\n * @returns A promise that resolves when the operation is complete.\n */\n async shutdown(id: string): Promise<void> {\n await this._kernelAPIClient.shutdown(id);\n await this.refreshRunning();\n }\n\n /**\n * Shut down all kernels.\n *\n * @returns A promise that resolves when all of the kernels are shut down.\n */\n async shutdownAll(): Promise<void> {\n // Update the list of models to make sure our list is current.\n await this.refreshRunning();\n\n // Shut down all models.\n await Promise.all(\n [...this._models.keys()].map(id => this._kernelAPIClient.shutdown(id))\n );\n\n // Update the list of models to clear out our state.\n await this.refreshRunning();\n }\n\n /**\n * Find a kernel by id.\n *\n * @param id - The id of the target kernel.\n *\n * @returns A promise that resolves with the kernel's model.\n */\n async findById(id: string): Promise<Kernel.IModel | undefined> {\n if (this._models.has(id)) {\n return this._models.get(id);\n }\n await this.refreshRunning();\n return this._models.get(id);\n }\n\n /**\n * Execute a request to the server to poll running kernels and update state.\n */\n protected async requestRunning(): Promise<void> {\n let models: Kernel.IModel[];\n try {\n models = await this._kernelAPIClient.listRunning();\n } catch (err) {\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (\n err instanceof ServerConnection.NetworkError ||\n err.response?.status === 503 ||\n err.response?.status === 424\n ) {\n this._connectionFailure.emit(err);\n }\n throw err;\n }\n\n if (this.isDisposed) {\n return;\n }\n\n if (\n this._models.size === models.length &&\n models.every(model => {\n const existing = this._models.get(model.id);\n if (!existing) {\n return false;\n }\n return (\n existing.connections === model.connections &&\n existing.execution_state === model.execution_state &&\n existing.last_activity === model.last_activity &&\n existing.name === model.name &&\n existing.reason === model.reason &&\n existing.traceback === model.traceback\n );\n })\n ) {\n // Identical models list (presuming models does not contain duplicate\n // ids), so just return\n return;\n }\n\n this._models = new Map(models.map(x => [x.id, x]));\n\n // For any kernel connection to a kernel that doesn't exist, notify it of\n // the shutdown.\n this._kernelConnections.forEach(kc => {\n if (!this._models.has(kc.id)) {\n kc.handleShutdown();\n }\n });\n\n this._runningChanged.emit(models);\n }\n\n /**\n * Handle a kernel starting.\n */\n private _onStarted(kernelConnection: KernelConnection): void {\n this._kernelConnections.add(kernelConnection);\n kernelConnection.statusChanged.connect(this._onStatusChanged, this);\n kernelConnection.disposed.connect(this._onDisposed, this);\n }\n\n private _onDisposed(kernelConnection: KernelConnection) {\n this._kernelConnections.delete(kernelConnection);\n // A dispose emission could mean the server session is deleted, or that\n // the kernel JS object is disposed and the kernel still exists on the\n // server, so we refresh from the server to make sure we reflect the\n // server state.\n\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n\n private _onStatusChanged(\n kernelConnection: KernelConnection,\n status: Kernel.Status\n ) {\n if (status === 'dead') {\n // We asynchronously update our list of kernels, which asynchronously\n // will dispose them. We do not want to immediately dispose them because\n // there may be other signal handlers that want to be called.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n }\n\n private _isReady = false;\n private _ready: Promise<void>;\n private _kernelConnections = new Set<KernelConnection>();\n private _models = new Map<string, Kernel.IModel>();\n private _pollModels: Poll;\n private _runningChanged = new Signal<this, Kernel.IModel[]>(this);\n private _connectionFailure = new Signal<this, Error>(this);\n private _kernelAPIClient: Kernel.IKernelAPIClient;\n}\n\n/**\n * The namespace for `KernelManager` class statics.\n */\nexport namespace KernelManager {\n /**\n * The options used to initialize a KernelManager.\n */\n export interface IOptions extends BaseManager.IOptions {\n /**\n * When the manager stops polling the API. Defaults to `when-hidden`.\n */\n standby?: Poll.Standby | (() => boolean | Poll.Standby);\n\n /**\n * The kernel API client.\n */\n kernelAPIClient?: Kernel.IKernelAPIClient;\n }\n\n /**\n * A no-op kernel manager to be used when starting kernels.\n */\n export class NoopManager extends KernelManager {\n /**\n * Whether the manager is active.\n */\n get isActive(): boolean {\n return false;\n }\n\n /**\n * Used for testing.\n */\n get parentReady(): Promise<void> {\n return super.ready;\n }\n\n /**\n * Start a new kernel - throws an error since it is not supported.\n */\n async startNew(\n createOptions: IKernelOptions = {},\n connectOptions: Omit<\n Kernel.IKernelConnection.IOptions,\n 'model' | 'serverSettings'\n > = {}\n ): Promise<Kernel.IKernelConnection> {\n return Promise.reject(\n new Error('Not implemented in no-op Kernel Manager')\n );\n }\n\n /**\n * Connect to an existing kernel - throws an error since it is not supported.\n */\n connectTo(\n options: Omit<Kernel.IKernelConnection.IOptions, 'serverSettings'>\n ): Kernel.IKernelConnection {\n throw new Error('Not implemented in no-op Kernel Manager');\n }\n\n /**\n * Shut down a kernel by id - throws an error since it is not supported.\n */\n async shutdown(id: string): Promise<void> {\n return Promise.reject(\n new Error('Not implemented in no-op Kernel Manager')\n );\n }\n\n /**\n * A promise that fulfills when the manager is ready (never).\n */\n get ready(): Promise<void> {\n return this.parentReady.then(() => this._readyPromise);\n }\n\n /**\n * Execute a request to the server to poll running kernels and update state.\n */\n protected async requestRunning(): Promise<void> {\n return Promise.resolve();\n }\n\n private _readyPromise = new Promise<void>(() => {\n /* no-op */\n });\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n// Namespace some of our modules for convenience and backwards compatibility.\nimport * as Kernel from './kernel';\nimport * as KernelMessage from './messages';\nimport * as KernelAPI from './restapi';\nimport { KernelConnection } from './default';\n\nexport * from './manager';\nexport { Kernel, KernelMessage, KernelAPI, KernelConnection };\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { PageConfig, URLExt } from '@jupyterlab/coreutils';\n\nimport { ServerConnection } from '../serverconnection';\n\n/**\n * The url for the lab build service.\n */\nconst BUILD_SETTINGS_URL = 'api/build';\n\n/**\n * The build API service manager.\n */\nexport class BuildManager {\n /**\n * Create a new setting manager.\n */\n constructor(options: BuildManager.IOptions = {}) {\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n const { baseUrl, appUrl } = this.serverSettings;\n this._url = URLExt.join(baseUrl, appUrl, BUILD_SETTINGS_URL);\n }\n\n /**\n * The server settings used to make API requests.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Test whether the build service is available.\n */\n get isAvailable(): boolean {\n return PageConfig.getOption('buildAvailable').toLowerCase() === 'true';\n }\n\n /**\n * Test whether to check build status automatically.\n */\n get shouldCheck(): boolean {\n return PageConfig.getOption('buildCheck').toLowerCase() === 'true';\n }\n\n /**\n * Get whether the application should be built.\n */\n getStatus(): Promise<BuildManager.IStatus> {\n const { _url, serverSettings } = this;\n const promise = ServerConnection.makeRequest(_url, {}, serverSettings);\n\n return promise\n .then(response => {\n if (response.status !== 200) {\n throw new ServerConnection.ResponseError(response);\n }\n\n return response.json();\n })\n .then(data => {\n if (typeof data.status !== 'string') {\n throw new Error('Invalid data');\n }\n if (typeof data.message !== 'string') {\n throw new Error('Invalid data');\n }\n return data;\n });\n }\n\n /**\n * Build the application.\n */\n build(): Promise<void> {\n const { _url, serverSettings } = this;\n const init = { method: 'POST' };\n const promise = ServerConnection.makeRequest(_url, init, serverSettings);\n\n return promise.then(response => {\n if (response.status === 400) {\n throw new ServerConnection.ResponseError(response, 'Build aborted');\n }\n if (response.status !== 200) {\n const message = `Build failed with ${response.status}.\n\n If you are experiencing the build failure after installing an extension (or trying to include previously installed extension after updating JupyterLab) please check the extension repository for new installation instructions as many extensions migrated to the prebuilt extensions system which no longer requires rebuilding JupyterLab (but uses a different installation procedure, typically involving a package manager such as 'pip' or 'conda').\n\n If you specifically intended to install a source extension, please run 'jupyter lab build' on the server for full output.`;\n throw new ServerConnection.ResponseError(response, message);\n }\n });\n }\n\n /**\n * Cancel an active build.\n */\n cancel(): Promise<void> {\n const { _url, serverSettings } = this;\n const init = { method: 'DELETE' };\n const promise = ServerConnection.makeRequest(_url, init, serverSettings);\n\n return promise.then(response => {\n if (response.status !== 204) {\n throw new ServerConnection.ResponseError(response);\n }\n });\n }\n\n private _url = '';\n}\n\n/**\n * A namespace for `BuildManager` statics.\n */\nexport namespace BuildManager {\n /**\n * The instantiation options for a setting manager.\n */\n export interface IOptions {\n /**\n * The server settings used to make API requests.\n */\n serverSettings?: ServerConnection.ISettings;\n }\n\n /**\n * The build status response from the server.\n */\n export interface IStatus {\n /**\n * Whether a build is needed.\n */\n readonly status: 'stable' | 'needed' | 'building';\n\n /**\n * The message associated with the build status.\n */\n readonly message: string;\n }\n}\n\n/**\n * A namespace for builder API interfaces.\n */\nexport namespace Builder {\n /**\n * The interface for the build manager.\n */\n export interface IManager extends BuildManager {}\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { URLExt } from '@jupyterlab/coreutils';\n\nimport { ServerConnection } from '../serverconnection';\n\nimport { PromiseDelegate } from '@lumino/coreutils';\n\n/**\n * The url for the lab nbconvert service.\n */\nconst NBCONVERT_SETTINGS_URL = 'api/nbconvert';\n\n/**\n * The nbconvert API service manager.\n */\nexport class NbConvertManager {\n /**\n * Create a new nbconvert manager.\n */\n constructor(options: NbConvertManager.IOptions = {}) {\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n }\n\n /**\n * The server settings used to make API requests.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Fetch and cache the export formats from the expensive nbconvert handler.\n */\n protected async fetchExportFormats(): Promise<NbConvertManager.IExportFormats> {\n this._requestingFormats = new PromiseDelegate();\n this._exportFormats = null;\n const base = this.serverSettings.baseUrl;\n const url = URLExt.join(base, NBCONVERT_SETTINGS_URL);\n const { serverSettings } = this;\n const response = await ServerConnection.makeRequest(\n url,\n {},\n serverSettings\n );\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n const exportList: NbConvertManager.IExportFormats = {};\n const keys = Object.keys(data);\n keys.forEach(function (key) {\n const mimeType: string = data[key].output_mimetype;\n exportList[key] = { output_mimetype: mimeType };\n });\n this._exportFormats = exportList;\n this._requestingFormats.resolve(exportList);\n return exportList;\n }\n\n /**\n * Get the list of export formats, preferring pre-cached ones.\n */\n async getExportFormats(\n force: boolean = true\n ): Promise<NbConvertManager.IExportFormats> {\n if (this._requestingFormats) {\n return this._requestingFormats.promise;\n }\n\n if (force || !this._exportFormats) {\n return await this.fetchExportFormats();\n }\n\n return this._exportFormats;\n }\n\n protected _requestingFormats: PromiseDelegate<NbConvertManager.IExportFormats> | null;\n protected _exportFormats: NbConvertManager.IExportFormats | null = null;\n}\n\n/**\n * A namespace for `BuildManager` statics.\n */\nexport namespace NbConvertManager {\n /**\n * The instantiation options for a setting manager.\n */\n export interface IOptions {\n /**\n * The server settings used to make API requests.\n */\n serverSettings?: ServerConnection.ISettings;\n }\n\n /**\n * A namespace for nbconvert API interfaces.\n */\n export interface IExportFormats {\n /**\n * The list of supported export formats.\n */\n [key: string]: { output_mimetype: string };\n }\n}\n\n/**\n * A namespace for builder API interfaces.\n */\nexport namespace NbConvert {\n /**\n * The interface for the build manager.\n */\n export interface IManager extends NbConvertManager {}\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { validateModel as validateKernelModel } from '../kernel/validate';\n\nimport * as Session from './session';\n\nimport { validateProperty } from '../validate';\n\n/**\n * Validate an `Session.IModel` object.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function validateModel(data: any): asserts data is Session.IModel {\n validateProperty(data, 'id', 'string');\n validateProperty(data, 'type', 'string');\n validateProperty(data, 'name', 'string');\n validateProperty(data, 'path', 'string');\n validateProperty(data, 'kernel', 'object');\n validateKernelModel(data.kernel);\n}\n\n/**\n * Update model from legacy session data.\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function updateLegacySessionModel(data: any): void {\n if (data.path === undefined && data.notebook !== undefined) {\n data.path = data.notebook.path;\n data.type = 'notebook';\n data.name = '';\n }\n}\n\n/**\n * Validate an array of `Session.IModel` objects.\n */\nexport function validateModels(\n models: Session.IModel[]\n): asserts models is Session.IModel[] {\n if (!Array.isArray(models)) {\n throw new Error('Invalid session list');\n }\n models.forEach(d => validateModel(d));\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { ServerConnection } from '../serverconnection';\nimport { Session } from '.';\nimport { URLExt } from '@jupyterlab/coreutils';\nimport { updateLegacySessionModel, validateModel } from './validate';\n\ntype DeepPartial<T> = {\n [P in keyof T]?: DeepPartial<T[P]>;\n};\n\n/**\n * The url for the session service.\n */\nexport const SESSION_SERVICE_URL = 'api/sessions';\n\n/**\n * List the running sessions.\n */\nexport async function listRunning(\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<Session.IModel[]> {\n const url = URLExt.join(settings.baseUrl, SESSION_SERVICE_URL);\n const response = await ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n if (!Array.isArray(data)) {\n throw new Error('Invalid Session list');\n }\n data.forEach(m => {\n updateLegacySessionModel(m);\n validateModel(m);\n });\n return data;\n}\n\n/**\n * Get a session url.\n */\nexport function getSessionUrl(baseUrl: string, id: string): string {\n const servicesBase = URLExt.join(baseUrl, SESSION_SERVICE_URL);\n const result = URLExt.join(servicesBase, id);\n if (!result.startsWith(servicesBase)) {\n throw new Error('Can only be used for services requests');\n }\n return result;\n}\n\n/**\n * Shut down a session by id.\n */\nexport async function shutdownSession(\n id: string,\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<void> {\n const url = getSessionUrl(settings.baseUrl, id);\n const init = { method: 'DELETE' };\n const response = await ServerConnection.makeRequest(url, init, settings);\n\n if (response.status === 404) {\n const data = await response.json();\n const msg =\n data.message ?? `The session \"${id}\"\" does not exist on the server`;\n console.warn(msg);\n } else if (response.status === 410) {\n throw new ServerConnection.ResponseError(\n response,\n 'The kernel was deleted but the session was not'\n );\n } else if (response.status !== 204) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\n\n/**\n * Get a full session model from the server by session id string.\n */\nexport async function getSessionModel(\n id: string,\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<Session.IModel> {\n const url = getSessionUrl(settings.baseUrl, id);\n const response = await ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n updateLegacySessionModel(data);\n validateModel(data);\n return data;\n}\n\n/**\n * Create a new session, or return an existing session if the session path\n * already exists.\n */\nexport async function startSession(\n options: Session.ISessionOptions,\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<Session.IModel> {\n const url = URLExt.join(settings.baseUrl, SESSION_SERVICE_URL);\n const init = {\n method: 'POST',\n body: JSON.stringify(options)\n };\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 201) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n updateLegacySessionModel(data);\n validateModel(data);\n return data;\n}\n\n/**\n * Send a PATCH to the server, updating the session path or the kernel.\n */\nexport async function updateSession(\n model: Pick<Session.IModel, 'id'> & DeepPartial<Omit<Session.IModel, 'id'>>,\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<Session.IModel> {\n const url = getSessionUrl(settings.baseUrl, model.id);\n const init = {\n method: 'PATCH',\n body: JSON.stringify(model)\n };\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n updateLegacySessionModel(data);\n validateModel(data);\n return data;\n}\n\n/**\n * The session API client.\n *\n * #### Notes\n * Use this class to interact with the Jupyter Server Session API.\n * This class adheres to the Jupyter Server API endpoints.\n */\nexport class SessionAPIClient {\n /**\n * Create a new session API client.\n *\n * @param options - The options used to create the client.\n */\n constructor(options: { serverSettings?: ServerConnection.ISettings }) {\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n }\n\n /**\n * The server settings used by the client.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * List the running sessions.\n *\n * @returns A promise that resolves with the list of running session models.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/sessions) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async listRunning(): Promise<Session.IModel[]> {\n return listRunning(this.serverSettings);\n }\n\n /**\n * Get a session model.\n *\n * @param id - The id of the session of interest.\n *\n * @returns A promise that resolves with the session model.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/sessions) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async getModel(id: string): Promise<Session.IModel> {\n return getSessionModel(id, this.serverSettings);\n }\n\n /**\n * Create a new session.\n *\n * @param options - The options used to create the session.\n *\n * @returns A promise that resolves with the session model.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/sessions) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async startNew(options: Session.ISessionOptions): Promise<Session.IModel> {\n return startSession(options, this.serverSettings);\n }\n\n /**\n * Shut down a session by id.\n *\n * @param id - The id of the session to shut down.\n *\n * @returns A promise that resolves when the session is shut down.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/sessions) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async shutdown(id: string): Promise<void> {\n return shutdownSession(id, this.serverSettings);\n }\n\n /**\n * Update a session by id.\n *\n * @param model - The session model to update.\n *\n * @returns A promise that resolves with the updated session model.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/sessions) and validates the response model.\n *\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async update(\n model: Pick<Session.IModel, 'id'> & DeepPartial<Omit<Session.IModel, 'id'>>\n ): Promise<Session.IModel> {\n return updateSession(model, this.serverSettings);\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { ISignal, Signal } from '@lumino/signaling';\n\nimport { Kernel, KernelMessage } from '../kernel';\n\nimport { ServerConnection } from '..';\n\nimport * as Session from './session';\n\nimport { UUID } from '@lumino/coreutils';\nimport { SessionAPIClient } from './restapi';\n\ntype DeepPartial<T> = {\n [P in keyof T]?: DeepPartial<T[P]>;\n};\n\n/**\n * Session object for accessing the session REST api. The session\n * should be used to start kernels and then shut them down -- for\n * all other kernel operations, the kernel object should be used.\n */\nexport class SessionConnection implements Session.ISessionConnection {\n /**\n * Construct a new session.\n */\n constructor(options: Session.ISessionConnection.IOptions) {\n this._id = options.model.id;\n this._name = options.model.name;\n this._path = options.model.path;\n this._type = options.model.type;\n this._username = options.username ?? '';\n this._clientId = options.clientId ?? UUID.uuid4();\n this._connectToKernel = options.connectToKernel;\n this._kernelConnectionOptions = options.kernelConnectionOptions ?? {};\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n this._sessionAPIClient =\n options.sessionAPIClient ??\n new SessionAPIClient({ serverSettings: this.serverSettings });\n this.setupKernel(options.model.kernel);\n }\n\n /**\n * A signal emitted when the session is disposed.\n */\n get disposed(): ISignal<this, void> {\n return this._disposed;\n }\n\n /**\n * A signal emitted when the kernel changes.\n */\n get kernelChanged(): ISignal<\n this,\n Session.ISessionConnection.IKernelChangedArgs\n > {\n return this._kernelChanged;\n }\n\n /**\n * A signal proxied from the connection about the kernel status.\n */\n get statusChanged(): ISignal<this, Kernel.Status> {\n return this._statusChanged;\n }\n\n /**\n * A signal proxied from the kernel about the connection status.\n */\n get connectionStatusChanged(): ISignal<this, Kernel.ConnectionStatus> {\n return this._connectionStatusChanged;\n }\n\n /**\n * A signal proxied from the kernel pending input.\n */\n get pendingInput(): ISignal<this, boolean> {\n return this._pendingInput;\n }\n\n /**\n * A signal proxied from the kernel about iopub kernel messages.\n */\n get iopubMessage(): ISignal<this, KernelMessage.IIOPubMessage> {\n return this._iopubMessage;\n }\n\n /**\n * A signal proxied from the kernel for an unhandled kernel message.\n */\n get unhandledMessage(): ISignal<this, KernelMessage.IMessage> {\n return this._unhandledMessage;\n }\n\n /**\n * A signal proxied from the kernel emitted for any kernel message.\n *\n * #### Notes\n * The behavior is undefined if the message is modified during message\n * handling. As such, it should be treated as read-only.\n */\n get anyMessage(): ISignal<this, Kernel.IAnyMessageArgs> {\n return this._anyMessage;\n }\n\n /**\n * A signal emitted when a session property changes.\n */\n get propertyChanged(): ISignal<this, 'path' | 'name' | 'type'> {\n return this._propertyChanged;\n }\n\n /**\n * Get the session id.\n */\n get id(): string {\n return this._id;\n }\n\n /**\n * Get the session kernel connection object.\n *\n * #### Notes\n * This is a read-only property, and can be altered by [changeKernel].\n */\n get kernel(): Kernel.IKernelConnection | null {\n return this._kernel;\n }\n\n /**\n * Get the session path.\n */\n get path(): string {\n return this._path;\n }\n\n /**\n * Get the session type.\n */\n get type(): string {\n return this._type;\n }\n\n /**\n * Get the session name.\n */\n get name(): string {\n return this._name;\n }\n\n /**\n * Get the model associated with the session.\n */\n get model(): Session.IModel {\n return {\n id: this.id,\n kernel: this.kernel && { id: this.kernel.id, name: this.kernel.name },\n path: this._path,\n type: this._type,\n name: this._name\n };\n }\n\n /**\n * The server settings of the session.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Test whether the session has been disposed.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * Update the session based on a session model from the server.\n *\n * #### Notes\n * This only updates this session connection instance. Use `setPath`,\n * `setName`, `setType`, and `changeKernel` to change the session values on\n * the server.\n */\n update(model: Session.IModel): void {\n const oldModel = this.model;\n this._path = model.path;\n this._name = model.name;\n this._type = model.type;\n\n if (\n (this._kernel === null && model.kernel !== null) ||\n (this._kernel !== null && model.kernel === null) ||\n (this._kernel !== null &&\n model.kernel !== null &&\n this._kernel.id !== model.kernel.id)\n ) {\n if (this._kernel !== null) {\n this._kernel.dispose();\n }\n const oldValue = this._kernel || null;\n this.setupKernel(model.kernel);\n const newValue = this._kernel || null;\n this._kernelChanged.emit({ name: 'kernel', oldValue, newValue });\n }\n\n this._handleModelChange(oldModel);\n }\n\n /**\n * Dispose of the resources held by the session.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n this._disposed.emit();\n\n if (this._kernel) {\n this._kernel.dispose();\n const oldValue = this._kernel;\n this._kernel = null;\n const newValue = this._kernel;\n this._kernelChanged.emit({ name: 'kernel', oldValue, newValue });\n }\n\n Signal.clearData(this);\n }\n\n /**\n * Change the session path.\n *\n * @param path - The new session path.\n *\n * @returns A promise that resolves when the session has renamed.\n *\n * #### Notes\n * This uses the Jupyter REST API, and the response is validated.\n * The promise is fulfilled on a valid response and rejected otherwise.\n */\n async setPath(path: string): Promise<void> {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ path });\n }\n\n /**\n * Change the session name.\n */\n async setName(name: string): Promise<void> {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ name });\n }\n\n /**\n * Change the session type.\n */\n async setType(type: string): Promise<void> {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._patch({ type });\n }\n\n /**\n * Change the kernel.\n *\n * @param options - The name or id of the new kernel.\n *\n * #### Notes\n * This shuts down the existing kernel and creates a new kernel,\n * keeping the existing session ID and session path.\n */\n async changeKernel(\n options: Partial<Kernel.IModel>\n ): Promise<Kernel.IKernelConnection | null> {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n\n await this._patch({ kernel: options });\n return this.kernel;\n }\n\n /**\n * Kill the kernel and shutdown the session.\n *\n * @returns - The promise fulfilled on a valid response from the server.\n *\n * #### Notes\n * Uses the [Jupyter Server API](https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter-server/jupyter_server/main/jupyter_server/services/api/api.yaml#!/sessions), and validates the response.\n * Disposes of the session and emits a [sessionDied] signal on success.\n */\n async shutdown(): Promise<void> {\n if (this.isDisposed) {\n throw new Error('Session is disposed');\n }\n await this._sessionAPIClient.shutdown(this.id);\n this.dispose();\n }\n\n /**\n * Create a new kernel connection and connect to its signals.\n *\n * #### Notes\n * This method is not meant to be subclassed.\n */\n protected setupKernel(model: Kernel.IModel | null): void {\n if (model === null) {\n this._kernel = null;\n return;\n }\n const kc = this._connectToKernel({\n ...this._kernelConnectionOptions,\n model,\n username: this._username,\n clientId: this._clientId,\n serverSettings: this.serverSettings\n });\n this._kernel = kc;\n kc.statusChanged.connect(this.onKernelStatus, this);\n kc.connectionStatusChanged.connect(this.onKernelConnectionStatus, this);\n kc.pendingInput.connect(this.onPendingInput, this);\n kc.unhandledMessage.connect(this.onUnhandledMessage, this);\n kc.iopubMessage.connect(this.onIOPubMessage, this);\n kc.anyMessage.connect(this.onAnyMessage, this);\n }\n\n /**\n * Handle to changes in the Kernel status.\n */\n protected onKernelStatus(\n sender: Kernel.IKernelConnection,\n state: Kernel.Status\n ): void {\n this._statusChanged.emit(state);\n }\n\n /**\n * Handle to changes in the Kernel status.\n */\n protected onKernelConnectionStatus(\n sender: Kernel.IKernelConnection,\n state: Kernel.ConnectionStatus\n ): void {\n this._connectionStatusChanged.emit(state);\n }\n\n /**\n * Handle a change in the pendingInput.\n */\n protected onPendingInput(sender: Kernel.IKernelConnection, state: boolean) {\n this._pendingInput.emit(state);\n }\n\n /**\n * Handle iopub kernel messages.\n */\n protected onIOPubMessage(\n sender: Kernel.IKernelConnection,\n msg: KernelMessage.IIOPubMessage\n ): void {\n this._iopubMessage.emit(msg);\n }\n\n /**\n * Handle unhandled kernel messages.\n */\n protected onUnhandledMessage(\n sender: Kernel.IKernelConnection,\n msg: KernelMessage.IMessage\n ): void {\n this._unhandledMessage.emit(msg);\n }\n\n /**\n * Handle any kernel messages.\n */\n protected onAnyMessage(\n sender: Kernel.IKernelConnection,\n args: Kernel.IAnyMessageArgs\n ): void {\n this._anyMessage.emit(args);\n }\n\n /**\n * Send a PATCH to the server, updating the session path or the kernel.\n */\n private async _patch(\n body: DeepPartial<Session.IModel>\n ): Promise<Session.IModel> {\n const model = await this._sessionAPIClient.update({\n ...body,\n id: this._id\n });\n this.update(model);\n return model;\n }\n\n /**\n * Handle a change to the model.\n */\n private _handleModelChange(oldModel: Session.IModel): void {\n if (oldModel.name !== this._name) {\n this._propertyChanged.emit('name');\n }\n if (oldModel.type !== this._type) {\n this._propertyChanged.emit('type');\n }\n if (oldModel.path !== this._path) {\n this._propertyChanged.emit('path');\n }\n }\n\n private _id = '';\n private _path = '';\n private _name = '';\n private _type = '';\n private _username: string;\n private _clientId: string;\n private _kernel: Kernel.IKernelConnection | null = null;\n private _isDisposed = false;\n private _disposed = new Signal<this, void>(this);\n private _kernelChanged = new Signal<\n this,\n Session.ISessionConnection.IKernelChangedArgs\n >(this);\n private _statusChanged = new Signal<this, Kernel.Status>(this);\n private _connectionStatusChanged = new Signal<this, Kernel.ConnectionStatus>(\n this\n );\n private _pendingInput = new Signal<this, boolean>(this);\n private _iopubMessage = new Signal<this, KernelMessage.IIOPubMessage>(this);\n private _unhandledMessage = new Signal<this, KernelMessage.IMessage>(this);\n private _anyMessage = new Signal<this, Kernel.IAnyMessageArgs>(this);\n private _propertyChanged = new Signal<this, 'path' | 'name' | 'type'>(this);\n private _connectToKernel: (\n options: Kernel.IKernelConnection.IOptions\n ) => Kernel.IKernelConnection;\n private _kernelConnectionOptions: Omit<\n Kernel.IKernelConnection.IOptions,\n 'model' | 'username' | 'clientId' | 'serverSettings'\n >;\n private _sessionAPIClient: Session.ISessionAPIClient;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { Poll } from '@lumino/polling';\nimport { ISignal, Signal } from '@lumino/signaling';\nimport { ServerConnection } from '../serverconnection';\nimport * as Session from './session';\nimport { BaseManager } from '../basemanager';\nimport { SessionConnection } from './default';\nimport { SessionAPIClient } from './restapi';\nimport { Kernel } from '../kernel';\n\n/**\n * An implementation of a session manager.\n */\nexport class SessionManager extends BaseManager implements Session.IManager {\n /**\n * Construct a new session manager.\n *\n * @param options - The default options for each session.\n */\n constructor(options: SessionManager.IOptions) {\n super(options);\n\n this._kernelManager = options.kernelManager;\n this._sessionAPIClient =\n options.sessionAPIClient ??\n new SessionAPIClient({ serverSettings: options.serverSettings });\n\n // Start model polling with exponential backoff.\n this._pollModels = new Poll({\n auto: false,\n factory: () => this.requestRunning(),\n frequency: {\n interval: 10 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:SessionManager#models`,\n standby: options.standby ?? 'when-hidden'\n });\n\n // Initialize internal data.\n this._ready = (async () => {\n await this._pollModels.start();\n await this._pollModels.tick;\n if (this._kernelManager.isActive) {\n await this._kernelManager.ready;\n }\n this._isReady = true;\n })();\n }\n\n /**\n * The server settings for the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Test whether the manager is ready.\n */\n get isReady(): boolean {\n return this._isReady;\n }\n\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready(): Promise<void> {\n return this._ready;\n }\n\n /**\n * A signal emitted when the running sessions change.\n */\n get runningChanged(): ISignal<this, Session.IModel[]> {\n return this._runningChanged;\n }\n\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure(): ISignal<this, Error> {\n return this._connectionFailure;\n }\n\n /**\n * Dispose of the resources used by the manager.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this._models.clear();\n this._sessionConnections.forEach(x => x.dispose());\n this._pollModels.dispose();\n super.dispose();\n }\n\n /*\n * Connect to a running session. See also [[connectToSession]].\n */\n connectTo(\n options: Omit<\n Session.ISessionConnection.IOptions,\n 'connectToKernel' | 'serverSettings'\n >\n ): Session.ISessionConnection {\n const sessionConnection = new SessionConnection({\n ...options,\n connectToKernel: this._connectToKernel,\n serverSettings: this.serverSettings,\n sessionAPIClient: this._sessionAPIClient\n });\n this._onStarted(sessionConnection);\n if (!this._models.has(options.model.id)) {\n // We trust the user to connect to an existing session, but we verify\n // asynchronously.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n\n return sessionConnection;\n }\n\n /**\n * Create an iterator over the most recent running sessions.\n *\n * @returns A new iterator over the running sessions.\n */\n running(): IterableIterator<Session.IModel> {\n return this._models.values();\n }\n\n /**\n * Force a refresh of the running sessions.\n *\n * @returns A promise that with the list of running sessions.\n *\n * #### Notes\n * This is not typically meant to be called by the user, since the\n * manager maintains its own internal state.\n */\n async refreshRunning(): Promise<void> {\n await this._pollModels.refresh();\n await this._pollModels.tick;\n }\n\n /**\n * Start a new session. See also [[startNewSession]].\n *\n * @param createOptions - Options for creating the session\n *\n * @param connectOptions - Options for connecting to the session\n */\n async startNew(\n createOptions: Session.ISessionOptions,\n connectOptions: Omit<\n Session.ISessionConnection.IOptions,\n 'model' | 'connectToKernel' | 'serverSettings'\n > = {}\n ): Promise<Session.ISessionConnection> {\n const model = await this._sessionAPIClient.startNew(createOptions);\n await this.refreshRunning();\n return this.connectTo({ ...connectOptions, model });\n }\n\n /**\n * Shut down a session by id.\n */\n async shutdown(id: string): Promise<void> {\n await this._sessionAPIClient.shutdown(id);\n await this.refreshRunning();\n }\n\n /**\n * Shut down all sessions.\n *\n * @returns A promise that resolves when all of the kernels are shut down.\n */\n async shutdownAll(): Promise<void> {\n // Update the list of models to make sure our list is current.\n await this.refreshRunning();\n\n // Shut down all models.\n await Promise.all(\n [...this._models.keys()].map(id => this._sessionAPIClient.shutdown(id))\n );\n\n // Update the list of models to clear out our state.\n await this.refreshRunning();\n }\n\n /**\n * Find a session associated with a path and stop it if it is the only session\n * using that kernel.\n *\n * @param path - The path in question.\n *\n * @returns A promise that resolves when the relevant sessions are stopped.\n */\n async stopIfNeeded(path: string): Promise<void> {\n try {\n const sessions = await this._sessionAPIClient.listRunning();\n const matches = sessions.filter(value => value.path === path);\n if (matches.length === 1) {\n const id = matches[0].id;\n await this.shutdown(id);\n }\n } catch (error) {\n /* Always succeed. */\n }\n }\n\n /**\n * Find a session by id.\n */\n async findById(id: string): Promise<Session.IModel | undefined> {\n if (this._models.has(id)) {\n return this._models.get(id);\n }\n await this.refreshRunning();\n return this._models.get(id);\n }\n\n /**\n * Find a session by path.\n */\n async findByPath(path: string): Promise<Session.IModel | undefined> {\n for (const m of this._models.values()) {\n if (m.path === path) {\n return m;\n }\n }\n await this.refreshRunning();\n for (const m of this._models.values()) {\n if (m.path === path) {\n return m;\n }\n }\n return undefined;\n }\n\n /**\n * Execute a request to the server to poll running kernels and update state.\n */\n protected async requestRunning(): Promise<void> {\n let models: Session.IModel[];\n try {\n models = await this._sessionAPIClient.listRunning();\n } catch (err) {\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (\n err instanceof ServerConnection.NetworkError ||\n err.response?.status === 503 ||\n err.response?.status === 424\n ) {\n this._connectionFailure.emit(err);\n }\n throw err;\n }\n\n if (this.isDisposed) {\n return;\n }\n\n if (\n this._models.size === models.length &&\n models.every(model => {\n const existing = this._models.get(model.id);\n if (!existing) {\n return false;\n }\n return (\n existing.kernel?.id === model.kernel?.id &&\n existing.kernel?.name === model.kernel?.name &&\n existing.name === model.name &&\n existing.path === model.path &&\n existing.type === model.type\n );\n })\n ) {\n // Identical models list (presuming models does not contain duplicate\n // ids), so just return\n return;\n }\n\n this._models = new Map(models.map(x => [x.id, x]));\n\n this._sessionConnections.forEach(sc => {\n if (this._models.has(sc.id)) {\n sc.update(this._models.get(sc.id)!);\n } else {\n sc.dispose();\n }\n });\n\n this._runningChanged.emit(models);\n }\n\n /**\n * Handle a session starting.\n */\n private _onStarted(sessionConnection: SessionConnection): void {\n this._sessionConnections.add(sessionConnection);\n sessionConnection.disposed.connect(this._onDisposed, this);\n sessionConnection.propertyChanged.connect(this._onChanged, this);\n sessionConnection.kernelChanged.connect(this._onChanged, this);\n }\n\n private _onDisposed(sessionConnection: SessionConnection) {\n this._sessionConnections.delete(sessionConnection);\n // A session termination emission could mean the server session is deleted,\n // or that the session JS object is disposed and the session still exists on\n // the server, so we refresh from the server to make sure we reflect the\n // server state.\n\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n\n private _onChanged() {\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n\n private _isReady = false;\n private _sessionConnections = new Set<SessionConnection>();\n private _models = new Map<string, Session.IModel>();\n private _pollModels: Poll;\n private _ready: Promise<void>;\n private _runningChanged = new Signal<this, Session.IModel[]>(this);\n private _connectionFailure = new Signal<this, Error>(this);\n\n // We define these here so they bind `this` correctly\n private readonly _connectToKernel = (\n options: Omit<Kernel.IKernelConnection.IOptions, 'serverSettings'>\n ) => {\n return this._kernelManager.connectTo(options);\n };\n\n private _kernelManager: Kernel.IManager;\n private _sessionAPIClient: Session.ISessionAPIClient;\n}\n\n/**\n * The namespace for `SessionManager` class statics.\n */\nexport namespace SessionManager {\n /**\n * The options used to initialize a SessionManager.\n */\n export interface IOptions extends BaseManager.IOptions {\n /**\n * When the manager stops polling the API. Defaults to `when-hidden`.\n */\n standby?: Poll.Standby | (() => boolean | Poll.Standby);\n\n /**\n * Kernel Manager\n */\n kernelManager: Kernel.IManager;\n\n /**\n * The session API client.\n */\n sessionAPIClient?: Session.ISessionAPIClient;\n }\n\n /**\n * A no-op session manager to be used when starting sessions is not supported.\n */\n export class NoopManager extends SessionManager {\n /**\n * Whether the manager is active.\n */\n get isActive(): boolean {\n return false;\n }\n\n /**\n * Used for testing.\n */\n get parentReady(): Promise<void> {\n return super.ready;\n }\n\n /**\n * Start a new session - throw an error since it is not supported.\n */\n async startNew(\n createOptions: Session.ISessionOptions,\n connectOptions: Omit<\n Session.ISessionConnection.IOptions,\n 'model' | 'connectToKernel' | 'serverSettings'\n > = {}\n ): Promise<Session.ISessionConnection> {\n return Promise.reject(\n new Error('Not implemented in no-op Session Manager')\n );\n }\n\n /*\n * Connect to a running session - throw an error since it is not supported.\n */\n connectTo(\n options: Omit<\n Session.ISessionConnection.IOptions,\n 'connectToKernel' | 'serverSettings'\n >\n ): Session.ISessionConnection {\n throw Error('Not implemented in no-op Session Manager');\n }\n\n /**\n * A promise that fulfills when the manager is ready (never).\n */\n get ready(): Promise<void> {\n return this.parentReady.then(() => this._readyPromise);\n }\n\n /**\n * Shut down a session by id - throw an error since it is not supported.\n */\n async shutdown(id: string): Promise<void> {\n return Promise.reject(\n new Error('Not implemented in no-op Session Manager')\n );\n }\n\n /**\n * Execute a request to the server to poll running sessions and update state.\n */\n protected async requestRunning(): Promise<void> {\n return Promise.resolve();\n }\n\n private _readyPromise = new Promise<void>(() => {\n /* no-op */\n });\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport * as Session from './session';\nimport * as SessionAPI from './restapi';\n\nexport * from './manager';\nexport { Session, SessionAPI };\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { IDataConnector } from './interfaces';\n\n/**\n * An abstract class that adheres to the data connector interface.\n *\n * @typeparam T - The basic entity response type a service's connector.\n *\n * @typeparam U - The basic entity request type, which is conventionally the\n * same as the response type but may be different if a service's implementation\n * requires input data to be different from output responses. Defaults to `T`.\n *\n * @typeparam V - The basic token applied to a request, conventionally a string\n * ID or filter, but may be set to a different type when an implementation\n * requires it. Defaults to `string`.\n *\n * @typeparam W - The type of the optional `query` parameter of the `list`\n * method. Defaults to `string`.\n *\n * #### Notes\n * The only abstract method in this class is the `fetch` method, which must be\n * reimplemented by all subclasses. The `remove` and `save` methods have a\n * default implementation that returns a promise that will always reject. This\n * class is a convenience superclass for connectors that only need to `fetch`.\n */\nexport abstract class DataConnector<T, U = T, V = string, W = string>\n implements IDataConnector<T, U, V, W>\n{\n /**\n * Retrieve an item from the data connector.\n *\n * @param id - The identifier used to retrieve an item.\n *\n * @returns A promise that resolves with a data payload if available.\n *\n * #### Notes\n * The promise returned by this method may be rejected if an error occurs in\n * retrieving the data. Nonexistence of an `id` will succeed with `undefined`.\n */\n abstract fetch(id: V): Promise<T | undefined>;\n\n /**\n * Retrieve the list of items available from the data connector.\n *\n * @param query - The optional query filter to apply to the connector request.\n *\n * @returns A promise that always rejects with an error.\n *\n * #### Notes\n * Subclasses should reimplement if they support a back-end that can list.\n */\n async list(query?: W): Promise<{ ids: V[]; values: T[] }> {\n throw new Error('DataConnector#list method has not been implemented.');\n }\n\n /**\n * Remove a value using the data connector.\n *\n * @param id - The identifier for the data being removed.\n *\n * @returns A promise that always rejects with an error.\n *\n * #### Notes\n * Subclasses should reimplement if they support a back-end that can remove.\n */\n async remove(id: V): Promise<any> {\n throw new Error('DataConnector#remove method has not been implemented.');\n }\n\n /**\n * Save a value using the data connector.\n *\n * @param id - The identifier for the data being saved.\n *\n * @param value - The data being saved.\n *\n * @returns A promise that always rejects with an error.\n *\n * #### Notes\n * Subclasses should reimplement if they support a back-end that can save.\n */\n async save(id: V, value: U): Promise<any> {\n throw new Error('DataConnector#save method has not been implemented.');\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/*-----------------------------------------------------------------------------\n| Copyright (c) 2014-2017, PhosphorJS Contributors\n|\n| Distributed under the terms of the BSD 3-Clause License.\n|\n| The full license is in the file LICENSE, distributed with this software.\n|----------------------------------------------------------------------------*/\n\n/**\n * @packageDocumentation\n * @module properties\n */\n\n/**\n * A class which attaches a value to an external object.\n *\n * #### Notes\n * Attached properties are used to extend the state of an object with\n * semantic data from an unrelated class. They also encapsulate value\n * creation, coercion, and notification.\n *\n * Because attached property values are stored in a hash table, which\n * in turn is stored in a WeakMap keyed on the owner object, there is\n * non-trivial storage overhead involved in their use. The pattern is\n * therefore best used for the storage of rare data.\n */\nexport class AttachedProperty<T, U> {\n /**\n * Construct a new attached property.\n *\n * @param options - The options for initializing the property.\n */\n constructor(options: AttachedProperty.IOptions<T, U>) {\n this.name = options.name;\n this._create = options.create;\n this._coerce = options.coerce || null;\n this._compare = options.compare || null;\n this._changed = options.changed || null;\n }\n\n /**\n * The human readable name for the property.\n */\n readonly name: string;\n\n /**\n * Get the current value of the property for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * @returns The current value of the property.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and assigned as the current value of the property.\n */\n get(owner: T): U {\n let value: U;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n value = map[this._pid];\n } else {\n value = map[this._pid] = this._createValue(owner);\n }\n return value;\n }\n\n /**\n * Set the current value of the property for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * @param value - The value for the property.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and used as the previous value for the comparison.\n */\n set(owner: T, value: U): void {\n let oldValue: U;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n oldValue = map[this._pid];\n } else {\n oldValue = map[this._pid] = this._createValue(owner);\n }\n let newValue = this._coerceValue(owner, value);\n this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));\n }\n\n /**\n * Explicitly coerce the current property value for a given owner.\n *\n * @param owner - The property owner of interest.\n *\n * #### Notes\n * If the value has not yet been set, the default value will be\n * computed and used as the previous value for the comparison.\n */\n coerce(owner: T): void {\n let oldValue: U;\n let map = Private.ensureMap(owner);\n if (this._pid in map) {\n oldValue = map[this._pid];\n } else {\n oldValue = map[this._pid] = this._createValue(owner);\n }\n let newValue = this._coerceValue(owner, oldValue);\n this._maybeNotify(owner, oldValue, (map[this._pid] = newValue));\n }\n\n /**\n * Get or create the default value for the given owner.\n */\n private _createValue(owner: T): U {\n let create = this._create;\n return create(owner);\n }\n\n /**\n * Coerce the value for the given owner.\n */\n private _coerceValue(owner: T, value: U): U {\n let coerce = this._coerce;\n return coerce ? coerce(owner, value) : value;\n }\n\n /**\n * Compare the old value and new value for equality.\n */\n private _compareValue(oldValue: U, newValue: U): boolean {\n let compare = this._compare;\n return compare ? compare(oldValue, newValue) : oldValue === newValue;\n }\n\n /**\n * Run the change notification if the given values are different.\n */\n private _maybeNotify(owner: T, oldValue: U, newValue: U): void {\n let changed = this._changed;\n if (changed && !this._compareValue(oldValue, newValue)) {\n changed(owner, oldValue, newValue);\n }\n }\n\n private _pid = Private.nextPID();\n private _create: (owner: T) => U;\n private _coerce: ((owner: T, value: U) => U) | null;\n private _compare: ((oldValue: U, newValue: U) => boolean) | null;\n private _changed: ((owner: T, oldValue: U, newValue: U) => void) | null;\n}\n\n/**\n * The namespace for the `AttachedProperty` class statics.\n */\nexport namespace AttachedProperty {\n /**\n * The options object used to initialize an attached property.\n */\n export interface IOptions<T, U> {\n /**\n * The human readable name for the property.\n *\n * #### Notes\n * By convention, this should be the same as the name used to define\n * the public accessor for the property value.\n *\n * This **does not** have an effect on the property lookup behavior.\n * Multiple properties may share the same name without conflict.\n */\n name: string;\n\n /**\n * A factory function used to create the default property value.\n *\n * #### Notes\n * This will be called whenever the property value is required,\n * but has not yet been set for a given owner.\n */\n create: (owner: T) => U;\n\n /**\n * A function used to coerce a supplied value into the final value.\n *\n * #### Notes\n * This will be called whenever the property value is changed, or\n * when the property is explicitly coerced. The return value will\n * be used as the final value of the property.\n *\n * This will **not** be called for the initial default value.\n */\n coerce?: (owner: T, value: U) => U;\n\n /**\n * A function used to compare two values for equality.\n *\n * #### Notes\n * This is called to determine if the property value has changed.\n * It should return `true` if the given values are equivalent, or\n * `false` if they are different.\n *\n * If this is not provided, it defaults to the `===` operator.\n */\n compare?: (oldValue: U, newValue: U) => boolean;\n\n /**\n * A function called when the property value has changed.\n *\n * #### Notes\n * This will be invoked when the property value is changed and the\n * comparator indicates that the old value is not equal to the new\n * value.\n *\n * This will **not** be called for the initial default value.\n */\n changed?: (owner: T, oldValue: U, newValue: U) => void;\n }\n\n /**\n * Clear the stored property data for the given owner.\n *\n * @param owner - The property owner of interest.\n *\n * #### Notes\n * This will clear all property values for the owner, but it will\n * **not** run the change notification for any of the properties.\n */\n export function clearData(owner: unknown): void {\n Private.ownerData.delete(owner);\n }\n}\n\n/**\n * The namespace for the module implementation details.\n */\nnamespace Private {\n /**\n * A typedef for a mapping of property id to property value.\n */\n export type PropertyMap = { [key: string]: any };\n\n /**\n * A weak mapping of property owner to property map.\n */\n export const ownerData = new WeakMap<any, PropertyMap>();\n\n /**\n * A function which computes successive unique property ids.\n */\n export const nextPID = (() => {\n let id = 0;\n return () => {\n let rand = Math.random();\n let stem = `${rand}`.slice(2);\n return `pid-${stem}-${id++}`;\n };\n })();\n\n /**\n * Lookup the data map for the property owner.\n *\n * This will create the map if one does not already exist.\n */\n export function ensureMap(owner: unknown): PropertyMap {\n let map = ownerData.get(owner);\n if (map) {\n return map;\n }\n map = Object.create(null) as PropertyMap;\n ownerData.set(owner, map);\n return map;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { PromiseDelegate } from '@lumino/coreutils';\nimport { IObservableDisposable } from '@lumino/disposable';\nimport { AttachedProperty } from '@lumino/properties';\nimport { ISignal, Signal } from '@lumino/signaling';\nimport { IObjectPool, IRestorable } from './interfaces';\n\n/**\n * An object pool that supports restoration.\n *\n * @typeparam T - The type of object being tracked.\n */\nexport class RestorablePool<\n T extends IObservableDisposable = IObservableDisposable\n >\n implements IObjectPool<T>, IRestorable<T>\n{\n /**\n * Create a new restorable pool.\n *\n * @param options - The instantiation options for a restorable pool.\n */\n constructor(options: RestorablePool.IOptions) {\n this.namespace = options.namespace;\n }\n\n /**\n * A namespace for all tracked objects.\n */\n readonly namespace: string;\n\n /**\n * A signal emitted when an object object is added.\n *\n * #### Notes\n * This signal will only fire when an object is added to the pool.\n * It will not fire if an object injected into the pool.\n */\n get added(): ISignal<this, T> {\n return this._added;\n }\n\n /**\n * The current object.\n *\n * #### Notes\n * The restorable pool does not set `current`. It is intended for client use.\n *\n * If `current` is set to an object that does not exist in the pool, it is a\n * no-op.\n */\n get current(): T | null {\n return this._current;\n }\n set current(obj: T | null) {\n if (this._current === obj) {\n return;\n }\n if (obj !== null && this._objects.has(obj)) {\n this._current = obj;\n this._currentChanged.emit(this._current);\n }\n }\n\n /**\n * A signal emitted when the current widget changes.\n */\n get currentChanged(): ISignal<this, T | null> {\n return this._currentChanged;\n }\n\n /**\n * Test whether the pool is disposed.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * A promise resolved when the restorable pool has been restored.\n */\n get restored(): Promise<void> {\n return this._restored.promise;\n }\n\n /**\n * The number of objects held by the pool.\n */\n get size(): number {\n return this._objects.size;\n }\n\n /**\n * A signal emitted when an object is updated.\n */\n get updated(): ISignal<this, T> {\n return this._updated;\n }\n\n /**\n * Add a new object to the pool.\n *\n * @param obj - The object object being added.\n *\n * #### Notes\n * The object passed into the pool is added synchronously; its existence in\n * the pool can be checked with the `has()` method. The promise this method\n * returns resolves after the object has been added and saved to an underlying\n * restoration connector, if one is available.\n */\n async add(obj: T): Promise<void> {\n if (obj.isDisposed) {\n const warning = 'A disposed object cannot be added.';\n console.warn(warning, obj);\n throw new Error(warning);\n }\n\n if (this._objects.has(obj)) {\n const warning = 'This object already exists in the pool.';\n console.warn(warning, obj);\n throw new Error(warning);\n }\n\n this._objects.add(obj);\n obj.disposed.connect(this._onInstanceDisposed, this);\n\n if (Private.injectedProperty.get(obj)) {\n return;\n }\n\n if (this._restore) {\n const { connector } = this._restore;\n const objName = this._restore.name(obj);\n\n if (objName) {\n const name = `${this.namespace}:${objName}`;\n const data = this._restore.args?.(obj);\n\n Private.nameProperty.set(obj, name);\n await connector.save(name, { data });\n }\n }\n\n // Emit the added signal.\n this._added.emit(obj);\n }\n\n /**\n * Dispose of the resources held by the pool.\n *\n * #### Notes\n * Disposing a pool does not affect the underlying data in the data connector,\n * it simply disposes the client-side pool without making any connector calls.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this._current = null;\n this._isDisposed = true;\n this._objects.clear();\n Signal.clearData(this);\n }\n\n /**\n * Find the first object in the pool that satisfies a filter function.\n *\n * @param fn The filter function to call on each object.\n */\n find(fn: (obj: T) => boolean): T | undefined {\n const values = this._objects.values();\n for (const value of values) {\n if (fn(value)) {\n return value;\n }\n }\n return undefined;\n }\n\n /**\n * Iterate through each object in the pool.\n *\n * @param fn - The function to call on each object.\n */\n forEach(fn: (obj: T) => void): void {\n this._objects.forEach(fn);\n }\n\n /**\n * Filter the objects in the pool based on a predicate.\n *\n * @param fn - The function by which to filter.\n */\n filter(fn: (obj: T) => boolean): T[] {\n const filtered: T[] = [];\n this.forEach(obj => {\n if (fn(obj)) {\n filtered.push(obj);\n }\n });\n return filtered;\n }\n\n /**\n * Inject an object into the restorable pool without the pool handling its\n * restoration lifecycle.\n *\n * @param obj - The object to inject into the pool.\n */\n inject(obj: T): Promise<void> {\n Private.injectedProperty.set(obj, true);\n return this.add(obj);\n }\n\n /**\n * Check if this pool has the specified object.\n *\n * @param obj - The object whose existence is being checked.\n */\n has(obj: T): boolean {\n return this._objects.has(obj);\n }\n\n /**\n * Restore the objects in this pool's namespace.\n *\n * @param options - The configuration options that describe restoration.\n *\n * @returns A promise that resolves when restoration has completed.\n *\n * #### Notes\n * This function should almost never be invoked by client code. Its primary\n * use case is to be invoked by a layout restorer plugin that handles\n * multiple restorable pools and, when ready, asks them each to restore their\n * respective objects.\n */\n async restore(options: IRestorable.IOptions<T>): Promise<any> {\n if (this._hasRestored) {\n throw new Error('This pool has already been restored.');\n }\n\n this._hasRestored = true;\n\n const { command, connector, registry, when } = options;\n const namespace = this.namespace;\n const promises = when\n ? [connector.list(namespace)].concat(when)\n : [connector.list(namespace)];\n\n this._restore = options;\n\n const [saved] = await Promise.all(promises);\n const values = await Promise.all(\n saved.ids.map(async (id, index) => {\n const value = saved.values[index];\n const args = value && (value as any).data;\n\n if (args === undefined) {\n return connector.remove(id);\n }\n\n // Execute the command and if it fails, delete the state restore data.\n return registry\n .execute(command, args)\n .catch(() => connector.remove(id));\n })\n );\n this._restored.resolve();\n return values;\n }\n\n /**\n * Save the restore data for a given object.\n *\n * @param obj - The object being saved.\n */\n async save(obj: T): Promise<void> {\n const injected = Private.injectedProperty.get(obj);\n\n if (!this._restore || !this.has(obj) || injected) {\n return;\n }\n\n const { connector } = this._restore;\n const objName = this._restore.name(obj);\n const oldName = Private.nameProperty.get(obj);\n const newName = objName ? `${this.namespace}:${objName}` : '';\n\n if (oldName && oldName !== newName) {\n await connector.remove(oldName);\n }\n\n // Set the name property irrespective of whether the new name is null.\n Private.nameProperty.set(obj, newName);\n\n if (newName) {\n const data = this._restore.args?.(obj);\n await connector.save(newName, { data });\n }\n\n if (oldName !== newName) {\n this._updated.emit(obj);\n }\n }\n\n /**\n * Clean up after disposed objects.\n */\n private _onInstanceDisposed(obj: T): void {\n this._objects.delete(obj);\n\n if (obj === this._current) {\n this._current = null;\n this._currentChanged.emit(this._current);\n }\n\n if (Private.injectedProperty.get(obj)) {\n return;\n }\n\n if (!this._restore) {\n return;\n }\n\n const { connector } = this._restore;\n const name = Private.nameProperty.get(obj);\n\n if (name) {\n void connector.remove(name);\n }\n }\n\n private _added = new Signal<this, T>(this);\n private _current: T | null = null;\n private _currentChanged = new Signal<this, T | null>(this);\n private _hasRestored = false;\n private _isDisposed = false;\n private _objects = new Set<T>();\n private _restore: IRestorable.IOptions<T> | null = null;\n private _restored = new PromiseDelegate<void>();\n private _updated = new Signal<this, T>(this);\n}\n\n/**\n * A namespace for `RestorablePool` statics.\n */\nexport namespace RestorablePool {\n /**\n * The instantiation options for the restorable pool.\n */\n export interface IOptions {\n /**\n * A namespace designating objects from this pool.\n */\n namespace: string;\n }\n}\n\n/*\n * A namespace for private data.\n */\nnamespace Private {\n /**\n * An attached property to indicate whether an object has been injected.\n */\n export const injectedProperty = new AttachedProperty<\n IObservableDisposable,\n boolean\n >({\n name: 'injected',\n create: () => false\n });\n\n /**\n * An attached property for an object's ID.\n */\n export const nameProperty = new AttachedProperty<\n IObservableDisposable,\n string\n >({\n name: 'name',\n create: () => ''\n });\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { ReadonlyPartialJSONValue } from '@lumino/coreutils';\nimport { ISignal, Signal } from '@lumino/signaling';\nimport { IDataConnector } from './interfaces';\nimport { IStateDB } from './tokens';\n\n/**\n * The default concrete implementation of a state database.\n */\nexport class StateDB<\n T extends ReadonlyPartialJSONValue = ReadonlyPartialJSONValue\n> implements IStateDB<T>\n{\n /**\n * Create a new state database.\n *\n * @param options - The instantiation options for a state database.\n */\n constructor(options: StateDB.IOptions<T> = {}) {\n const { connector, transform } = options;\n\n this._connector = connector || new StateDB.Connector();\n if (!transform) {\n this._ready = Promise.resolve(undefined);\n } else {\n this._ready = transform.then(transformation => {\n const { contents, type } = transformation;\n\n switch (type) {\n case 'cancel':\n return;\n case 'clear':\n return this._clear();\n case 'merge':\n return this._merge(contents || {});\n case 'overwrite':\n return this._overwrite(contents || {});\n default:\n return;\n }\n });\n }\n }\n\n /**\n * A signal that emits the change type any time a value changes.\n */\n get changed(): ISignal<this, StateDB.Change> {\n return this._changed;\n }\n\n /**\n * Clear the entire database.\n */\n async clear(): Promise<void> {\n await this._ready;\n await this._clear();\n }\n\n /**\n * Retrieve a saved bundle from the database.\n *\n * @param id - The identifier used to retrieve a data bundle.\n *\n * @returns A promise that bears a data payload if available.\n *\n * #### Notes\n * The `id` values of stored items in the state database are formatted:\n * `'namespace:identifier'`, which is the same convention that command\n * identifiers in JupyterLab use as well. While this is not a technical\n * requirement for `fetch()`, `remove()`, and `save()`, it *is* necessary for\n * using the `list(namespace: string)` method.\n *\n * The promise returned by this method may be rejected if an error occurs in\n * retrieving the data. Non-existence of an `id` will succeed with the `value`\n * `undefined`.\n */\n async fetch(id: string): Promise<T | undefined> {\n await this._ready;\n return this._fetch(id);\n }\n\n /**\n * Retrieve all the saved bundles for a namespace.\n *\n * @param namespace The namespace prefix to retrieve.\n *\n * @returns A promise that bears a collection of payloads for a namespace.\n *\n * #### Notes\n * Namespaces are entirely conventional entities. The `id` values of stored\n * items in the state database are formatted: `'namespace:identifier'`, which\n * is the same convention that command identifiers in JupyterLab use as well.\n *\n * If there are any errors in retrieving the data, they will be logged to the\n * console in order to optimistically return any extant data without failing.\n * This promise will always succeed.\n */\n async list(namespace: string): Promise<{ ids: string[]; values: T[] }> {\n await this._ready;\n return this._list(namespace);\n }\n\n /**\n * Remove a value from the database.\n *\n * @param id - The identifier for the data being removed.\n *\n * @returns A promise that is rejected if remove fails and succeeds otherwise.\n */\n async remove(id: string): Promise<void> {\n await this._ready;\n await this._remove(id);\n this._changed.emit({ id, type: 'remove' });\n }\n\n /**\n * Save a value in the database.\n *\n * @param id - The identifier for the data being saved.\n *\n * @param value - The data being saved.\n *\n * @returns A promise that is rejected if saving fails and succeeds otherwise.\n *\n * #### Notes\n * The `id` values of stored items in the state database are formatted:\n * `'namespace:identifier'`, which is the same convention that command\n * identifiers in JupyterLab use as well. While this is not a technical\n * requirement for `fetch()`, `remove()`, and `save()`, it *is* necessary for\n * using the `list(namespace: string)` method.\n */\n async save(id: string, value: T): Promise<void> {\n await this._ready;\n await this._save(id, value);\n this._changed.emit({ id, type: 'save' });\n }\n\n /**\n * Return a serialized copy of the state database's entire contents.\n *\n * @returns A promise that resolves with the database contents as JSON.\n */\n async toJSON(): Promise<{ readonly [id: string]: T }> {\n await this._ready;\n\n const { ids, values } = await this._list();\n\n return values.reduce(\n (acc, val, idx) => {\n acc[ids[idx]] = val;\n return acc;\n },\n {} as { [id: string]: T }\n );\n }\n\n /**\n * Clear the entire database.\n */\n private async _clear(): Promise<void> {\n await Promise.all((await this._list()).ids.map(id => this._remove(id)));\n }\n\n /**\n * Fetch a value from the database.\n */\n private async _fetch(id: string): Promise<T | undefined> {\n const value = await this._connector.fetch(id);\n\n if (value) {\n return (JSON.parse(value) as Private.Envelope).v as T;\n }\n }\n\n /**\n * Fetch a list from the database.\n */\n private async _list(namespace = ''): Promise<{ ids: string[]; values: T[] }> {\n const { ids, values } = await this._connector.list(namespace);\n\n return {\n ids,\n values: values.map(val => (JSON.parse(val) as Private.Envelope).v as T)\n };\n }\n\n /**\n * Merge data into the state database.\n */\n private async _merge(contents: StateDB.Content<T>): Promise<void> {\n await Promise.all(\n Object.keys(contents).map(\n key => contents[key] && this._save(key, contents[key]!)\n )\n );\n }\n\n /**\n * Overwrite the entire database with new contents.\n */\n private async _overwrite(contents: StateDB.Content<T>): Promise<void> {\n await this._clear();\n await this._merge(contents);\n }\n\n /**\n * Remove a key in the database.\n */\n private async _remove(id: string): Promise<void> {\n return this._connector.remove(id);\n }\n\n /**\n * Save a key and its value in the database.\n */\n private async _save(id: string, value: T): Promise<void> {\n return this._connector.save(id, JSON.stringify({ v: value }));\n }\n\n private _changed = new Signal<this, StateDB.Change>(this);\n private _connector: IDataConnector<string>;\n private _ready: Promise<void>;\n}\n\n/**\n * A namespace for StateDB statics.\n */\nexport namespace StateDB {\n /**\n * A state database change.\n */\n export type Change = {\n /**\n * The key of the database item that was changed.\n *\n * #### Notes\n * This field is set to `null` for global changes (i.e. `clear`).\n */\n id: string | null;\n\n /**\n * The type of change.\n */\n type: 'clear' | 'remove' | 'save';\n };\n\n /**\n * A data transformation that can be applied to a state database.\n */\n export type DataTransform<\n T extends ReadonlyPartialJSONValue = ReadonlyPartialJSONValue\n > = {\n /*\n * The change operation being applied.\n */\n type: 'cancel' | 'clear' | 'merge' | 'overwrite';\n\n /**\n * The contents of the change operation.\n */\n contents: Content<T> | null;\n };\n\n /**\n * Database content map\n */\n export type Content<T> = { [id: string]: T | undefined };\n\n /**\n * The instantiation options for a state database.\n */\n export interface IOptions<\n T extends ReadonlyPartialJSONValue = ReadonlyPartialJSONValue\n > {\n /**\n * Optional string key/value connector. Defaults to in-memory connector.\n */\n connector?: IDataConnector<string>;\n\n /**\n * An optional promise that resolves with a data transformation that is\n * applied to the database contents before the database begins resolving\n * client requests.\n */\n transform?: Promise<DataTransform<T>>;\n }\n\n /**\n * An in-memory string key/value data connector.\n */\n export class Connector implements IDataConnector<string> {\n /**\n * Retrieve an item from the data connector.\n */\n async fetch(id: string): Promise<string> {\n return this._storage[id];\n }\n\n /**\n * Retrieve the list of items available from the data connector.\n *\n * @param namespace - If not empty, only keys whose first token before `:`\n * exactly match `namespace` will be returned, e.g. `foo` in `foo:bar`.\n */\n async list(namespace = ''): Promise<{ ids: string[]; values: string[] }> {\n return Object.keys(this._storage).reduce(\n (acc, val) => {\n if (namespace === '' ? true : namespace === val.split(':')[0]) {\n acc.ids.push(val);\n acc.values.push(this._storage[val]);\n }\n return acc;\n },\n { ids: [] as string[], values: [] as string[] }\n );\n }\n\n /**\n * Remove a value using the data connector.\n */\n async remove(id: string): Promise<void> {\n delete this._storage[id];\n }\n\n /**\n * Save a value using the data connector.\n */\n async save(id: string, value: string): Promise<void> {\n this._storage[id] = value;\n }\n\n private _storage: { [key: string]: string } = {};\n }\n}\n\n/*\n * A namespace for private module data.\n */\nnamespace Private {\n /**\n * An envelope around a JSON value stored in the state database.\n */\n export type Envelope = { readonly v: ReadonlyPartialJSONValue };\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { ReadonlyPartialJSONValue, Token } from '@lumino/coreutils';\nimport { IDataConnector } from './interfaces';\n\n/**\n * The default state database token.\n */\nexport const IStateDB = new Token<IStateDB>(\n '@jupyterlab/coreutils:IStateDB',\n `A service for the JupyterLab state database.\n Use this if you want to store data that will persist across page loads.\n See \"state database\" for more information.`\n);\n\n/**\n * The description of a state database.\n */\nexport interface IStateDB<\n T extends ReadonlyPartialJSONValue = ReadonlyPartialJSONValue\n> extends IDataConnector<T> {\n /**\n * Return a serialized copy of the state database's entire contents.\n *\n * @returns A promise that bears the database contents as JSON.\n */\n toJSON(): Promise<{ [id: string]: T }>;\n}\n", "/* -----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|----------------------------------------------------------------------------*/\n/**\n * @packageDocumentation\n * @module statedb\n */\n\nexport * from './dataconnector';\nexport * from './interfaces';\nexport * from './restorablepool';\nexport * from './statedb';\nexport * from './tokens';\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { URLExt } from '@jupyterlab/coreutils';\n\nimport { ISettingRegistry } from '@jupyterlab/settingregistry';\n\nimport { DataConnector } from '@jupyterlab/statedb';\n\nimport { ServerConnection } from '../serverconnection';\n\n/**\n * The url for the lab settings service.\n */\nconst SERVICE_SETTINGS_URL = 'api/settings';\n\n/**\n * The settings API service manager.\n */\nexport class SettingManager extends DataConnector<\n ISettingRegistry.IPlugin,\n string\n> {\n /**\n * Create a new setting manager.\n */\n constructor(options: SettingManager.IOptions = {}) {\n super();\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n }\n\n /**\n * The server settings used to make API requests.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Fetch a plugin's settings.\n *\n * @param id - The plugin's ID.\n *\n * @returns A promise that resolves if successful.\n */\n async fetch(id: string): Promise<ISettingRegistry.IPlugin> {\n if (!id) {\n throw new Error('Plugin `id` parameter is required for settings fetch.');\n }\n\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const response = await makeRequest(url, {}, serverSettings);\n\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n\n // Assert what type the server response is returning.\n return response.json() as Promise<ISettingRegistry.IPlugin>;\n }\n\n /**\n * Fetch the list of all plugin setting bundles.\n *\n * @returns A promise that resolves if successful.\n */\n async list(\n query?: 'ids'\n ): Promise<{ ids: string[]; values: ISettingRegistry.IPlugin[] }> {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, '', query === 'ids');\n const response = await makeRequest(url, {}, serverSettings);\n\n if (response.status !== 200) {\n throw new ResponseError(response);\n }\n\n const json = await response.json();\n const ids =\n json?.['settings']?.map(\n (plugin: ISettingRegistry.IPlugin) => plugin.id\n ) ?? [];\n\n let values: ISettingRegistry.IPlugin[] = [];\n if (!query) {\n values =\n json?.['settings']?.map((plugin: ISettingRegistry.IPlugin) => {\n plugin.data = { composite: {}, user: {} };\n return plugin;\n }) ?? [];\n }\n\n return { ids, values };\n }\n\n /**\n * Save a plugin's settings.\n *\n * @param id - The plugin's ID.\n *\n * @param raw - The user setting values as a raw string of JSON with comments.\n *\n * @returns A promise that resolves if successful.\n */\n async save(id: string, raw: string): Promise<void> {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n // NOTE: 'raw' is JSON5 (not valid JSON), so we encode it as a string in a valid JSON body\n const init = { body: JSON.stringify({ raw }), method: 'PUT' };\n const response = await makeRequest(url, init, serverSettings);\n\n if (response.status !== 204) {\n throw new ResponseError(response);\n }\n }\n}\n\n/**\n * A namespace for `SettingManager` statics.\n */\nexport namespace SettingManager {\n /**\n * The instantiation options for a setting manager.\n */\n export interface IOptions {\n /**\n * The server settings used to make API requests.\n */\n serverSettings?: ServerConnection.ISettings;\n }\n}\n\n/**\n * A namespace for setting API interfaces.\n */\nexport namespace Setting {\n /**\n * The interface for the setting system manager.\n */\n export interface IManager extends SettingManager {}\n}\n\n/**\n * A namespace for private data.\n */\nnamespace Private {\n /**\n * Get the url for a plugin's settings.\n */\n export function url(base: string, id: string, idsOnly?: boolean): string {\n const idsOnlyParam = idsOnly\n ? URLExt.objectToQueryString({ ids_only: true })\n : '';\n const settingsBase = URLExt.join(base, SERVICE_SETTINGS_URL);\n const result = URLExt.join(settingsBase, id);\n if (!result.startsWith(settingsBase)) {\n throw new Error('Can only be used for workspaces requests');\n }\n return `${result}${idsOnlyParam}`;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { PageConfig, URLExt } from '@jupyterlab/coreutils';\nimport { ServerConnection } from '../serverconnection';\n\n/**\n * The url for the terminal service.\n */\nexport const TERMINAL_SERVICE_URL = 'api/terminals';\n\n/**\n * Whether the terminal service is available.\n */\nexport function isAvailable(): boolean {\n const available = String(PageConfig.getOption('terminalsAvailable'));\n return available.toLowerCase() === 'true';\n}\n\n/**\n * The server model for a terminal session.\n */\nexport interface IModel {\n /**\n * The name of the terminal session.\n */\n readonly name: string;\n}\n\n/**\n * Start a new terminal session.\n *\n * @param settings - The server settings to use.\n *\n * @param name - The name of the target terminal.\n *\n * @param cwd - The path in which the terminal will start.\n *\n * @returns A promise that resolves with the session model.\n */\nexport async function startNew(\n settings: ServerConnection.ISettings = ServerConnection.makeSettings(),\n name?: string,\n cwd?: string\n): Promise<IModel> {\n Private.errorIfNotAvailable();\n const url = URLExt.join(settings.baseUrl, TERMINAL_SERVICE_URL);\n const init = {\n method: 'POST',\n body: JSON.stringify({ name, cwd })\n };\n\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n // TODO: Validate model\n return data;\n}\n\n/**\n * List the running terminal sessions.\n *\n * @param settings - The server settings to use.\n *\n * @returns A promise that resolves with the list of running session models.\n */\nexport async function listRunning(\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<IModel[]> {\n Private.errorIfNotAvailable();\n const url = URLExt.join(settings.baseUrl, TERMINAL_SERVICE_URL);\n const response = await ServerConnection.makeRequest(url, {}, settings);\n if (response.status !== 200) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n const data = await response.json();\n\n if (!Array.isArray(data)) {\n throw new Error('Invalid terminal list');\n }\n\n // TODO: validate each model\n return data;\n}\n\n/**\n * Shut down a terminal session by name.\n *\n * @param name - The name of the target session.\n *\n * @param settings - The server settings to use.\n *\n * @returns A promise that resolves when the session is shut down.\n */\nexport async function shutdownTerminal(\n name: string,\n settings: ServerConnection.ISettings = ServerConnection.makeSettings()\n): Promise<void> {\n Private.errorIfNotAvailable();\n const workspacesBase = URLExt.join(settings.baseUrl, TERMINAL_SERVICE_URL);\n const url = URLExt.join(workspacesBase, name);\n if (!url.startsWith(workspacesBase)) {\n throw new Error('Can only be used for terminal requests');\n }\n const init = { method: 'DELETE' };\n const response = await ServerConnection.makeRequest(url, init, settings);\n if (response.status === 404) {\n const data = await response.json();\n const msg =\n data.message ??\n `The terminal session \"${name}\"\" does not exist on the server`;\n console.warn(msg);\n } else if (response.status !== 204) {\n const err = await ServerConnection.ResponseError.create(response);\n throw err;\n }\n}\n\nnamespace Private {\n /**\n * Throw an error if terminals are not available.\n */\n export function errorIfNotAvailable(): void {\n if (!isAvailable()) {\n throw new Error('Terminals Unavailable');\n }\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { JSONPrimitive } from '@lumino/coreutils';\n\nimport { IObservableDisposable } from '@lumino/disposable';\n\nimport { ISignal } from '@lumino/signaling';\n\nimport { ServerConnection } from '..';\n\nimport { IManager as IBaseManager } from '../basemanager';\n\nimport { IModel, isAvailable } from './restapi';\nexport { IModel, isAvailable };\n\nexport namespace ITerminal {\n export interface IOptions {\n /**\n * The terminal name.\n */\n name?: string;\n /**\n * The terminal current directory.\n */\n cwd?: string;\n }\n}\n\n/**\n * An interface for a terminal session.\n */\nexport interface ITerminalConnection extends IObservableDisposable {\n /**\n * A signal emitted when a message is received from the server.\n */\n messageReceived: ISignal<ITerminalConnection, IMessage>;\n\n /**\n * Get the name of the terminal session.\n */\n readonly name: string;\n\n /**\n * The model associated with the session.\n */\n readonly model: IModel;\n\n /**\n * The server settings for the session.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * The current connection status of the terminal.\n */\n readonly connectionStatus: ConnectionStatus;\n\n /**\n * A signal emitted when the terminal connection status changes.\n */\n connectionStatusChanged: ISignal<this, ConnectionStatus>;\n\n /**\n * Send a message to the terminal session.\n */\n send(message: IMessage): void;\n\n /**\n * Reconnect to the terminal.\n *\n * @returns A promise that resolves when the terminal has reconnected.\n */\n reconnect(): Promise<void>;\n\n /**\n * Shut down the terminal session.\n */\n shutdown(): Promise<void>;\n}\n\nexport namespace ITerminalConnection {\n export interface IOptions {\n /**\n * Terminal model.\n */\n model: IModel;\n\n /**\n * The server settings.\n */\n serverSettings?: ServerConnection.ISettings;\n }\n}\n\n/**\n * A message from the terminal session.\n */\nexport interface IMessage {\n /**\n * The type of the message.\n */\n readonly type: MessageType;\n\n /**\n * The content of the message.\n */\n readonly content?: JSONPrimitive[];\n}\n\n/**\n * Valid message types for the terminal.\n */\nexport type MessageType = 'stdout' | 'disconnect' | 'set_size' | 'stdin';\n\n/**\n * The interface for a terminal manager.\n *\n * #### Notes\n * The manager is responsible for maintaining the state of running\n * terminal sessions.\n */\nexport interface IManager extends IBaseManager {\n /**\n * A signal emitted when the running terminals change.\n */\n runningChanged: ISignal<IManager, IModel[]>;\n\n /**\n * A signal emitted when there is a connection failure.\n */\n connectionFailure: ISignal<IManager, ServerConnection.NetworkError>;\n\n /**\n * Test whether the manager is ready.\n */\n readonly isReady: boolean;\n\n /**\n * A promise that fulfills when the manager is ready.\n */\n readonly ready: Promise<void>;\n\n /**\n * Whether the terminal service is available.\n */\n isAvailable(): boolean;\n\n /**\n * Create an iterator over the known running terminals.\n *\n * @returns A new iterator over the running terminals.\n */\n running(): IterableIterator<IModel>;\n\n /**\n * Create a new terminal session.\n *\n * @param options - The options used to create the terminal.\n *\n * @returns A promise that resolves with the terminal connection instance.\n *\n * #### Notes\n * The manager `serverSettings` will be always be used.\n */\n startNew(options?: ITerminal.IOptions): Promise<ITerminalConnection>;\n\n /*\n * Connect to a running session.\n *\n * @param options - The options used to connect to the terminal.\n *\n * @returns The new terminal connection instance.\n */\n connectTo(\n options: Omit<ITerminalConnection.IOptions, 'serverSettings'>\n ): ITerminalConnection;\n\n /**\n * Shut down a terminal session by name.\n *\n * @param name - The name of the terminal session.\n *\n * @returns A promise that resolves when the session is shut down.\n */\n shutdown(name: string): Promise<void>;\n\n /**\n * Shut down all terminal sessions.\n *\n * @returns A promise that resolves when all of the sessions are shut down.\n */\n shutdownAll(): Promise<void>;\n\n /**\n * Force a refresh of the running terminal sessions.\n *\n * @returns A promise that with the list of running sessions.\n *\n * #### Notes\n * This is not typically meant to be called by the user, since the\n * manager maintains its own internal state.\n */\n refreshRunning(): Promise<void>;\n}\n\n/**\n * The valid terminal connection states.\n *\n * #### Notes\n * The status states are:\n * * `connected`: The terminal connection is live.\n * * `connecting`: The terminal connection is not live, but we are attempting\n * to reconnect to the terminal.\n * * `disconnected`: The terminal connection is down, we are not\n * trying to reconnect.\n */\nexport type ConnectionStatus = 'connected' | 'connecting' | 'disconnected';\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { URLExt } from '@jupyterlab/coreutils';\n\nimport { JSONPrimitive, PromiseDelegate } from '@lumino/coreutils';\n\nimport { ISignal, Signal } from '@lumino/signaling';\n\nimport { ServerConnection } from '..';\n\nimport * as Terminal from './terminal';\nimport { shutdownTerminal, TERMINAL_SERVICE_URL } from './restapi';\n\n/**\n * An implementation of a terminal interface.\n */\nexport class TerminalConnection implements Terminal.ITerminalConnection {\n /**\n * Construct a new terminal session.\n */\n constructor(options: Terminal.ITerminalConnection.IOptions) {\n this._name = options.model.name;\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n this._createSocket();\n }\n\n /**\n * A signal emitted when the session is disposed.\n */\n get disposed(): ISignal<this, void> {\n return this._disposed;\n }\n\n /**\n * A signal emitted when a message is received from the server.\n */\n get messageReceived(): ISignal<this, Terminal.IMessage> {\n return this._messageReceived;\n }\n\n /**\n * Get the name of the terminal session.\n */\n get name(): string {\n return this._name;\n }\n\n /**\n * Get the model for the terminal session.\n */\n get model(): Terminal.IModel {\n return { name: this._name };\n }\n\n /**\n * The server settings for the session.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Test whether the session is disposed.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * Dispose of the resources held by the session.\n */\n dispose(): void {\n if (this._isDisposed) {\n return;\n }\n\n this._isDisposed = true;\n this._disposed.emit();\n\n this._updateConnectionStatus('disconnected');\n this._clearSocket();\n\n Signal.clearData(this);\n }\n\n /**\n * Send a message to the terminal session.\n *\n * #### Notes\n * If the connection is down, the message will be queued for sending when\n * the connection comes back up.\n */\n send(message: Terminal.IMessage): void {\n this._sendMessage(message);\n }\n\n /**\n * Send a message on the websocket, or possibly queue for later sending.\n *\n * @param queue - whether to queue the message if it cannot be sent\n */\n _sendMessage(message: Terminal.IMessage, queue = true): void {\n if (this._isDisposed || !message.content) {\n return;\n }\n if (this.connectionStatus === 'connected' && this._ws) {\n const msg = [message.type, ...message.content];\n this._ws.send(JSON.stringify(msg));\n } else if (queue) {\n this._pendingMessages.push(message);\n } else {\n throw new Error(`Could not send message: ${JSON.stringify(message)}`);\n }\n }\n\n /**\n * Send pending messages to the kernel.\n */\n private _sendPending(): void {\n // We check to make sure we are still connected each time. For\n // example, if a websocket buffer overflows, it may close, so we should\n // stop sending messages.\n while (\n this.connectionStatus === 'connected' &&\n this._pendingMessages.length > 0\n ) {\n this._sendMessage(this._pendingMessages[0], false);\n\n // We shift the message off the queue after the message is sent so that\n // if there is an exception, the message is still pending.\n this._pendingMessages.shift();\n }\n }\n\n /**\n * Reconnect to a terminal.\n *\n * #### Notes\n * This may try multiple times to reconnect to a terminal, and will sever\n * any existing connection.\n */\n reconnect(): Promise<void> {\n this._errorIfDisposed();\n const result = new PromiseDelegate<void>();\n\n // Set up a listener for the connection status changing, which accepts or\n // rejects after the retries are done.\n const fulfill = (sender: this, status: Terminal.ConnectionStatus) => {\n if (status === 'connected') {\n result.resolve();\n this.connectionStatusChanged.disconnect(fulfill, this);\n } else if (status === 'disconnected') {\n result.reject(new Error('Terminal connection disconnected'));\n this.connectionStatusChanged.disconnect(fulfill, this);\n }\n };\n this.connectionStatusChanged.connect(fulfill, this);\n\n // Reset the reconnect limit so we start the connection attempts fresh\n this._reconnectAttempt = 0;\n\n // Start the reconnection process, which will also clear any existing\n // connection.\n this._reconnect();\n\n // Return the promise that should resolve on connection or reject if the\n // retries don't work.\n return result.promise;\n }\n\n /**\n * Attempt a connection if we have not exhausted connection attempts.\n */\n _reconnect(): void {\n this._errorIfDisposed();\n\n // Clear any existing reconnection attempt\n clearTimeout(this._reconnectTimeout);\n\n // Update the connection status and schedule a possible reconnection.\n if (this._reconnectAttempt < this._reconnectLimit) {\n this._updateConnectionStatus('connecting');\n\n // The first reconnect attempt should happen immediately, and subsequent\n // attempts should pick a random number in a growing range so that we\n // don't overload the server with synchronized reconnection attempts\n // across multiple kernels.\n const timeout = Private.getRandomIntInclusive(\n 0,\n 1e3 * (Math.pow(2, this._reconnectAttempt) - 1)\n );\n console.error(\n `Connection lost, reconnecting in ${Math.floor(\n timeout / 1000\n )} seconds.`\n );\n this._reconnectTimeout = setTimeout(this._createSocket, timeout);\n this._reconnectAttempt += 1;\n } else {\n this._updateConnectionStatus('disconnected');\n }\n\n // Clear the websocket event handlers and the socket itself.\n this._clearSocket();\n }\n\n /**\n * Forcefully clear the socket state.\n *\n * #### Notes\n * This will clear all socket state without calling any handlers and will\n * not update the connection status. If you call this method, you are\n * responsible for updating the connection status as needed and recreating\n * the socket if you plan to reconnect.\n */\n private _clearSocket(): void {\n if (this._ws !== null) {\n // Clear the websocket event handlers and the socket itself.\n this._ws.onopen = this._noOp;\n this._ws.onclose = this._noOp;\n this._ws.onerror = this._noOp;\n this._ws.onmessage = this._noOp;\n this._ws.close();\n this._ws = null;\n }\n }\n\n /**\n * Shut down the terminal session.\n */\n async shutdown(): Promise<void> {\n await shutdownTerminal(this.name, this.serverSettings);\n this.dispose();\n }\n\n /**\n * Clone the current terminal connection.\n */\n clone(): Terminal.ITerminalConnection {\n return new TerminalConnection(this);\n }\n\n /**\n * Create the terminal websocket connection and add socket status handlers.\n *\n * #### Notes\n * You are responsible for updating the connection status as appropriate.\n */\n private _createSocket = () => {\n this._errorIfDisposed();\n\n // Make sure the socket is clear\n this._clearSocket();\n\n // Update the connection status to reflect opening a new connection.\n this._updateConnectionStatus('connecting');\n\n const name = this._name;\n const settings = this.serverSettings;\n\n let url = URLExt.join(\n settings.wsUrl,\n 'terminals',\n 'websocket',\n encodeURIComponent(name)\n );\n\n // If token authentication is in use.\n const token = settings.token;\n if (settings.appendToken && token !== '') {\n url = url + `?token=${encodeURIComponent(token)}`;\n }\n\n this._ws = new settings.WebSocket(url);\n\n this._ws.onmessage = this._onWSMessage;\n this._ws.onclose = this._onWSClose;\n this._ws.onerror = this._onWSClose;\n };\n\n // Websocket messages events are defined as variables to bind `this`\n private _onWSMessage = (event: MessageEvent) => {\n if (this._isDisposed) {\n return;\n }\n const data = JSON.parse(event.data) as JSONPrimitive[];\n\n // Handle a disconnect message.\n if (data[0] === 'disconnect') {\n this.dispose();\n }\n\n if (this._connectionStatus === 'connecting') {\n // After reconnection, ignore all messages until a 'setup' message\n // before we are truly connected. Setting the connection status to\n // connected only then means that if we do not get a setup message\n // before our retry timeout, we will delete the websocket and try again.\n if (data[0] === 'setup') {\n this._updateConnectionStatus('connected');\n }\n return;\n }\n\n this._messageReceived.emit({\n type: data[0] as Terminal.MessageType,\n content: data.slice(1)\n });\n };\n\n private _onWSClose = (event: CloseEvent) => {\n console.warn(`Terminal websocket closed: ${event.code}`);\n if (!this.isDisposed) {\n this._reconnect();\n }\n };\n\n /**\n * Handle connection status changes.\n */\n private _updateConnectionStatus(\n connectionStatus: Terminal.ConnectionStatus\n ): void {\n if (this._connectionStatus === connectionStatus) {\n return;\n }\n\n this._connectionStatus = connectionStatus;\n\n // If we are not 'connecting', stop any reconnection attempts.\n if (connectionStatus !== 'connecting') {\n this._reconnectAttempt = 0;\n clearTimeout(this._reconnectTimeout);\n }\n\n // Send the pending messages if we just connected.\n if (connectionStatus === 'connected') {\n this._sendPending();\n }\n\n // Notify others that the connection status changed.\n this._connectionStatusChanged.emit(connectionStatus);\n }\n\n /**\n * Utility function to throw an error if this instance is disposed.\n */\n private _errorIfDisposed() {\n if (this.isDisposed) {\n throw new Error('Terminal connection is disposed');\n }\n }\n\n /**\n * A signal emitted when the terminal connection status changes.\n */\n get connectionStatusChanged(): ISignal<this, Terminal.ConnectionStatus> {\n return this._connectionStatusChanged;\n }\n\n /**\n * The current connection status of the terminal connection.\n */\n get connectionStatus(): Terminal.ConnectionStatus {\n return this._connectionStatus;\n }\n\n private _connectionStatus: Terminal.ConnectionStatus = 'connecting';\n private _connectionStatusChanged = new Signal<\n this,\n Terminal.ConnectionStatus\n >(this);\n private _isDisposed = false;\n private _disposed = new Signal<this, void>(this);\n private _messageReceived = new Signal<this, Terminal.IMessage>(this);\n private _name: string;\n private _reconnectTimeout: any = null;\n private _ws: WebSocket | null = null;\n private _noOp = () => {\n /* no-op */\n };\n private _reconnectLimit = 7;\n private _reconnectAttempt = 0;\n private _pendingMessages: Terminal.IMessage[] = [];\n}\n\nnamespace Private {\n /**\n * Get the url for a terminal.\n */\n export function getTermUrl(baseUrl: string, name: string): string {\n return URLExt.join(baseUrl, TERMINAL_SERVICE_URL, encodeURIComponent(name));\n }\n\n /**\n * Get a random integer between min and max, inclusive of both.\n *\n * #### Notes\n * From\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Getting_a_random_integer_between_two_values_inclusive\n *\n * From the MDN page: It might be tempting to use Math.round() to accomplish\n * that, but doing so would cause your random numbers to follow a non-uniform\n * distribution, which may not be acceptable for your needs.\n */\n export function getRandomIntInclusive(min: number, max: number): number {\n min = Math.ceil(min);\n max = Math.floor(max);\n return Math.floor(Math.random() * (max - min + 1)) + min;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { Poll } from '@lumino/polling';\n\nimport { ISignal, Signal } from '@lumino/signaling';\n\nimport { ServerConnection } from '..';\n\nimport * as Terminal from './terminal';\nimport { BaseManager } from '../basemanager';\nimport {\n isAvailable,\n listRunning,\n shutdownTerminal,\n startNew\n} from './restapi';\nimport { TerminalConnection } from './default';\n\n/**\n * A terminal session manager.\n */\nexport class TerminalManager extends BaseManager implements Terminal.IManager {\n /**\n * Construct a new terminal manager.\n */\n constructor(options: TerminalManager.IOptions = {}) {\n super(options);\n\n // Check if terminals are available\n if (!this.isAvailable()) {\n this._ready = Promise.reject('Terminals unavailable');\n this._ready.catch(_ => undefined);\n return;\n }\n\n // Start polling with exponential backoff.\n this._pollModels = new Poll({\n auto: false,\n factory: () => this.requestRunning(),\n frequency: {\n interval: 10 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: `@jupyterlab/services:TerminalManager#models`,\n standby: options.standby ?? 'when-hidden'\n });\n\n // Initialize internal data.\n this._ready = (async () => {\n await this._pollModels.start();\n await this._pollModels.tick;\n this._isReady = true;\n })();\n }\n\n /**\n * The server settings of the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Test whether the manager is ready.\n */\n get isReady(): boolean {\n return this._isReady;\n }\n\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready(): Promise<void> {\n return this._ready;\n }\n\n /**\n * A signal emitted when the running terminals change.\n */\n get runningChanged(): ISignal<this, Terminal.IModel[]> {\n return this._runningChanged;\n }\n\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure(): ISignal<this, Error> {\n return this._connectionFailure;\n }\n\n /**\n * Dispose of the resources used by the manager.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this._names.length = 0;\n this._terminalConnections.forEach(x => x.dispose());\n this._pollModels.dispose();\n super.dispose();\n }\n\n /**\n * Whether the terminal service is available.\n */\n isAvailable(): boolean {\n return isAvailable();\n }\n\n /*\n * Connect to a running terminal.\n *\n * @param options - The options used to connect to the terminal.\n *\n * @returns The new terminal connection instance.\n *\n * #### Notes\n * The manager `serverSettings` will be used.\n */\n connectTo(\n options: Omit<Terminal.ITerminalConnection.IOptions, 'serverSettings'>\n ): Terminal.ITerminalConnection {\n const terminalConnection = new TerminalConnection({\n ...options,\n serverSettings: this.serverSettings\n });\n this._onStarted(terminalConnection);\n if (!this._names.includes(options.model.name)) {\n // We trust the user to connect to an existing session, but we verify\n // asynchronously.\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n return terminalConnection;\n }\n\n /**\n * Create an iterator over the most recent running terminals.\n *\n * @returns A new iterator over the running terminals.\n */\n running(): IterableIterator<Terminal.IModel> {\n return this._models[Symbol.iterator]();\n }\n\n /**\n * Force a refresh of the running terminals.\n *\n * @returns A promise that with the list of running terminals.\n *\n * #### Notes\n * This is intended to be called only in response to a user action,\n * since the manager maintains its internal state.\n */\n async refreshRunning(): Promise<void> {\n await this._pollModels.refresh();\n await this._pollModels.tick;\n }\n\n /**\n * Create a new terminal session.\n *\n * @param options - The options used to create the terminal.\n *\n * @returns A promise that resolves with the terminal connection instance.\n *\n * #### Notes\n * The manager `serverSettings` will be used unless overridden in the\n * options.\n */\n async startNew(\n options?: Terminal.ITerminal.IOptions\n ): Promise<Terminal.ITerminalConnection> {\n const model = await startNew(\n this.serverSettings,\n options?.name,\n options?.cwd\n );\n await this.refreshRunning();\n return this.connectTo({ model });\n }\n\n /**\n * Shut down a terminal session by name.\n */\n async shutdown(name: string): Promise<void> {\n await shutdownTerminal(name, this.serverSettings);\n await this.refreshRunning();\n }\n\n /**\n * Shut down all terminal sessions.\n *\n * @returns A promise that resolves when all of the sessions are shut down.\n */\n async shutdownAll(): Promise<void> {\n // Update the list of models to make sure our list is current.\n await this.refreshRunning();\n\n // Shut down all models.\n await Promise.all(\n this._names.map(name => shutdownTerminal(name, this.serverSettings))\n );\n\n // Update the list of models to clear out our state.\n await this.refreshRunning();\n }\n\n /**\n * Execute a request to the server to poll running terminals and update state.\n */\n protected async requestRunning(): Promise<void> {\n let models: Terminal.IModel[];\n try {\n models = await listRunning(this.serverSettings);\n } catch (err) {\n // Handle network errors, as well as cases where we are on a\n // JupyterHub and the server is not running. JupyterHub returns a\n // 503 (<2.0) or 424 (>2.0) in that case.\n if (\n err instanceof ServerConnection.NetworkError ||\n err.response?.status === 503 ||\n err.response?.status === 424\n ) {\n this._connectionFailure.emit(err);\n }\n throw err;\n }\n\n if (this.isDisposed) {\n return;\n }\n\n const names = models.map(({ name }) => name).sort();\n if (names === this._names) {\n // Identical models list, so just return\n return;\n }\n\n this._names = names;\n this._terminalConnections.forEach(tc => {\n if (!names.includes(tc.name)) {\n tc.dispose();\n }\n });\n this._runningChanged.emit(this._models);\n }\n\n /**\n * Handle a session starting.\n */\n private _onStarted(terminalConnection: Terminal.ITerminalConnection): void {\n this._terminalConnections.add(terminalConnection);\n terminalConnection.disposed.connect(this._onDisposed, this);\n }\n\n /**\n * Handle a session terminating.\n */\n private _onDisposed(terminalConnection: Terminal.ITerminalConnection): void {\n this._terminalConnections.delete(terminalConnection);\n // Update the running models to make sure we reflect the server state\n void this.refreshRunning().catch(() => {\n /* no-op */\n });\n }\n\n private _isReady = false;\n\n // As an optimization, we unwrap the models to just store the names.\n private _names: string[] = [];\n private get _models(): Terminal.IModel[] {\n return this._names.map(name => {\n return { name };\n });\n }\n\n private _pollModels: Poll;\n private _terminalConnections = new Set<Terminal.ITerminalConnection>();\n private _ready: Promise<void>;\n private _runningChanged = new Signal<this, Terminal.IModel[]>(this);\n private _connectionFailure = new Signal<this, Error>(this);\n}\n\n/**\n * The namespace for TerminalManager statics.\n */\nexport namespace TerminalManager {\n /**\n * The options used to initialize a terminal manager.\n */\n export interface IOptions extends BaseManager.IOptions {\n /**\n * When the manager stops polling the API. Defaults to `when-hidden`.\n */\n standby?: Poll.Standby | (() => boolean | Poll.Standby);\n }\n\n /**\n * A no-op terminal manager to be used when starting terminals is not supported.\n */\n export class NoopManager extends TerminalManager {\n /**\n * Whether the manager is active.\n */\n get isActive(): boolean {\n return false;\n }\n\n /**\n * Used for testing.\n */\n get parentReady(): Promise<void> {\n return super.ready;\n }\n\n /**\n * A promise that fulfills when the manager is ready (never).\n */\n get ready(): Promise<void> {\n return this.parentReady.then(() => this._readyPromise);\n }\n\n /**\n * Create a new terminal session - throw an error since it is not supported.\n *\n */\n async startNew(\n options?: Terminal.ITerminal.IOptions\n ): Promise<Terminal.ITerminalConnection> {\n return Promise.reject(\n new Error('Not implemented in no-op Terminal Manager')\n );\n }\n\n /*\n * Connect to a running terminal - throw an error since it is not supported.\n */\n connectTo(\n options: Omit<Terminal.ITerminalConnection.IOptions, 'serverSettings'>\n ): Terminal.ITerminalConnection {\n throw Error('Not implemented in no-op Terminal Manager');\n }\n\n /**\n * Shut down a session by id - throw an error since it is not supported.\n */\n async shutdown(id: string): Promise<void> {\n return Promise.reject(\n new Error('Not implemented in no-op Terminal Manager')\n );\n }\n\n /**\n * Execute a request to the server to poll running sessions and update state.\n */\n protected async requestRunning(): Promise<void> {\n return Promise.resolve();\n }\n\n private _readyPromise = new Promise<void>(() => {\n /* no-op */\n });\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport * as Terminal from './terminal';\nimport * as TerminalAPI from './restapi';\n\nexport * from './manager';\nexport { Terminal, TerminalAPI };\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { URLExt } from '@jupyterlab/coreutils';\n\nimport {\n JSONExt,\n PartialJSONObject,\n ReadonlyJSONObject\n} from '@lumino/coreutils';\n\nimport { Poll } from '@lumino/polling';\n\nimport { ISignal, Signal } from '@lumino/signaling';\n\nimport { ServerConnection } from '../serverconnection';\n\nimport { BaseManager, IManager as IBaseManager } from '../basemanager';\n\n/**\n * The url for the lab workspaces service.\n */\nconst SERVICE_USER_URL = 'api/me';\n\n/**\n * The service's ID.\n * Used to uniquely identify the poll, and\n * the item in local storage.\n */\nconst SERVICE_ID = '@jupyterlab/services:UserManager#user';\n\n/**\n * The user API service manager.\n */\nexport class UserManager extends BaseManager implements User.IManager {\n private _isReady = false;\n private _ready: Promise<void>;\n private _pollSpecs: Poll;\n\n private _identity: User.IIdentity;\n private _permissions: ReadonlyJSONObject;\n\n private _userChanged = new Signal<this, User.IUser>(this);\n private _connectionFailure = new Signal<this, Error>(this);\n\n /**\n * Create a new user manager.\n */\n constructor(options: UserManager.IOptions = {}) {\n super(options);\n\n // Initialize internal data.\n this._ready = this.requestUser()\n .then(() => {\n if (this.isDisposed) {\n return;\n }\n this._isReady = true;\n })\n .catch(\n _ =>\n // Return a promise that will never resolve, so user service is never ready\n // This typically occurs when the backend has no user service\n new Promise(() => {\n // no-op\n })\n );\n\n this._pollSpecs = new Poll({\n auto: false,\n factory: () => this.requestUser(),\n frequency: {\n interval: 61 * 1000,\n backoff: true,\n max: 300 * 1000\n },\n name: SERVICE_ID,\n standby: options.standby ?? 'when-hidden'\n });\n\n void this.ready.then(() => {\n void this._pollSpecs.start();\n });\n }\n\n /**\n * The server settings for the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Test whether the manager is ready.\n */\n get isReady(): boolean {\n return this._isReady;\n }\n\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready(): Promise<void> {\n return this._ready;\n }\n\n /**\n * Get the most recently fetched identity.\n */\n get identity(): User.IIdentity | null {\n return this._identity;\n }\n\n /**\n * Get the most recently fetched permissions.\n */\n get permissions(): ReadonlyJSONObject | null {\n return this._permissions;\n }\n\n /**\n * A signal emitted when the user changes.\n */\n get userChanged(): ISignal<this, User.IUser> {\n return this._userChanged;\n }\n\n /**\n * A signal emitted when there is a connection failure.\n */\n get connectionFailure(): ISignal<this, Error> {\n return this._connectionFailure;\n }\n\n /**\n * Dispose of the resources used by the manager.\n */\n dispose(): void {\n this._pollSpecs.dispose();\n super.dispose();\n }\n\n /**\n * Force a refresh of the specs from the server.\n *\n * @returns A promise that resolves when the specs are fetched.\n *\n * #### Notes\n * This is intended to be called only in response to a user action,\n * since the manager maintains its internal state.\n */\n async refreshUser(): Promise<void> {\n await this._pollSpecs.refresh();\n await this._pollSpecs.tick;\n }\n\n /**\n * Execute a request to the server to poll the user and update state.\n */\n protected async requestUser(): Promise<void> {\n if (this.isDisposed) {\n return;\n }\n\n const { baseUrl } = this.serverSettings;\n const { makeRequest, ResponseError } = ServerConnection;\n const url = URLExt.join(baseUrl, SERVICE_USER_URL);\n const response: Response = await makeRequest(url, {}, this.serverSettings);\n\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n\n const oldUser = {\n identity: this._identity,\n permissions: this._permissions\n };\n const newUser = await response.json();\n const identity = newUser.identity;\n\n // store the color and initials for the user\n // this info is not provided by the server\n const { localStorage } = window;\n const data = localStorage.getItem(SERVICE_ID);\n\n if (data && (!identity.initials || !identity.color)) {\n const localUser = JSON.parse(data);\n identity.initials =\n identity.initials ||\n localUser.initials ||\n identity.name.substring(0, 1);\n identity.color =\n identity.color || localUser.color || Private.getRandomColor();\n }\n\n if (!JSONExt.deepEqual(newUser, oldUser)) {\n this._identity = identity;\n this._permissions = newUser.permissions;\n localStorage.setItem(SERVICE_ID, JSON.stringify(identity));\n this._userChanged.emit(newUser);\n }\n }\n}\n\n/**\n * A namespace for `UserManager` statics.\n */\nexport namespace UserManager {\n /**\n * The instantiation options for a user manager.\n */\n export interface IOptions extends BaseManager.IOptions {\n /**\n * When the manager stops polling the API. Defaults to `when-hidden`.\n */\n standby?: Poll.Standby | (() => boolean | Poll.Standby);\n }\n}\n\n/**\n * A namespace for user API interfaces.\n */\nexport namespace User {\n /**\n * The interface describing a user identity.\n */\n export interface IUser {\n readonly identity: IIdentity;\n\n readonly permissions: PartialJSONObject;\n }\n\n /**\n * The interface describing a user identity.\n */\n export interface IIdentity extends PartialJSONObject {\n /**\n * User's unique identifier.\n */\n readonly username: string;\n\n /**\n * User's full name.\n */\n readonly name: string;\n\n /**\n * Shorter version of the name for displaying it on the UI.\n */\n readonly display_name: string;\n\n /**\n * User's name initials.\n */\n readonly initials: string;\n\n /**\n * User's cursor color and icon color if avatar_url is undefined\n * (there is no image).\n */\n readonly color: string;\n\n /**\n * User's avatar url.\n * The url to the user's image for the icon.\n */\n readonly avatar_url?: string;\n }\n\n /**\n * Object which manages user's identity.\n *\n * #### Notes\n * The manager is responsible for maintaining the state of the user.\n */\n export interface IManager extends IBaseManager {\n /**\n * A signal emitted when the user changes.\n */\n userChanged: ISignal<this, User.IUser>;\n\n /**\n * User's identity.\n *\n * #### Notes\n * The value will be null until the manager is ready.\n */\n readonly identity: User.IIdentity | null;\n\n /**\n * User's permissions.\n *\n * #### Notes\n * The value will be null until the manager is ready.\n */\n readonly permissions: ReadonlyJSONObject | null;\n\n /**\n * Force a refresh of user's identity from the server.\n *\n * @returns A promise that resolves when the identity is fetched.\n *\n * #### Notes\n * This is intended to be called only in response to a user action,\n * since the manager maintains its internal state.\n */\n refreshUser(): Promise<void>;\n }\n}\n\n/**\n * A namespace for module-private functionality.\n *\n * Note: We do not want to export this function\n * to move it to css variables in the Theme.\n */\nnamespace Private {\n /**\n * Predefined colors for users\n */\n const userColors = [\n 'var(--jp-collaborator-color1)',\n 'var(--jp-collaborator-color2)',\n 'var(--jp-collaborator-color3)',\n 'var(--jp-collaborator-color4)',\n 'var(--jp-collaborator-color5)',\n 'var(--jp-collaborator-color6)',\n 'var(--jp-collaborator-color7)'\n ];\n\n /**\n * Get a random color from the list of colors.\n */\n export const getRandomColor = (): string =>\n userColors[Math.floor(Math.random() * userColors.length)];\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { URLExt } from '@jupyterlab/coreutils';\n\nimport { DataConnector } from '@jupyterlab/statedb';\n\nimport { ReadonlyPartialJSONObject } from '@lumino/coreutils';\n\nimport { ServerConnection } from '../serverconnection';\n\n/**\n * The url for the lab workspaces service.\n */\nconst SERVICE_WORKSPACES_URL = 'api/workspaces';\n\n/**\n * The workspaces API service manager.\n */\nexport class WorkspaceManager extends DataConnector<Workspace.IWorkspace> {\n /**\n * Create a new workspace manager.\n */\n constructor(options: WorkspaceManager.IOptions = {}) {\n super();\n this.serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n }\n\n /**\n * The server settings used to make API requests.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Fetch a workspace.\n *\n * @param id - The workspace's ID.\n *\n * @returns A promise that resolves if successful.\n */\n async fetch(id: string): Promise<Workspace.IWorkspace> {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const response = await makeRequest(url, {}, serverSettings);\n\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n\n return response.json();\n }\n\n /**\n * Fetch the list of workspace IDs that exist on the server.\n *\n * @returns A promise that resolves if successful.\n */\n async list(): Promise<{ ids: string[]; values: Workspace.IWorkspace[] }> {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, '');\n const response = await makeRequest(url, {}, serverSettings);\n\n if (response.status !== 200) {\n const err = await ResponseError.create(response);\n throw err;\n }\n\n const result = await response.json();\n\n return result.workspaces;\n }\n\n /**\n * Remove a workspace from the server.\n *\n * @param id - The workspaces's ID.\n *\n * @returns A promise that resolves if successful.\n */\n async remove(id: string): Promise<void> {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const init = { method: 'DELETE' };\n const response = await makeRequest(url, init, serverSettings);\n\n if (response.status !== 204) {\n const err = await ResponseError.create(response);\n throw err;\n }\n }\n\n /**\n * Save a workspace.\n *\n * @param id - The workspace's ID.\n *\n * @param workspace - The workspace being saved.\n *\n * @returns A promise that resolves if successful.\n */\n async save(id: string, workspace: Workspace.IWorkspace): Promise<void> {\n const { serverSettings } = this;\n const { baseUrl, appUrl } = serverSettings;\n const { makeRequest, ResponseError } = ServerConnection;\n const base = baseUrl + appUrl;\n const url = Private.url(base, id);\n const init = { body: JSON.stringify(workspace), method: 'PUT' };\n const response = await makeRequest(url, init, serverSettings);\n\n if (response.status !== 204) {\n const err = await ResponseError.create(response);\n throw err;\n }\n }\n}\n\n/**\n * A namespace for `WorkspaceManager` statics.\n */\nexport namespace WorkspaceManager {\n /**\n * The instantiation options for a workspace manager.\n */\n export interface IOptions {\n /**\n * The server settings used to make API requests.\n */\n serverSettings?: ServerConnection.ISettings;\n }\n}\n\n/**\n * A namespace for workspace API interfaces.\n */\nexport namespace Workspace {\n /**\n * The interface for the workspace API manager.\n */\n export interface IManager extends WorkspaceManager {}\n\n /**\n * The interface describing a workspace API response.\n */\n export interface IWorkspace {\n /**\n * The workspace data.\n */\n data: ReadonlyPartialJSONObject;\n\n /**\n * The metadata for a workspace.\n */\n metadata: {\n /**\n * The workspace ID.\n */\n id: string;\n\n /**\n * The last modification date and time for this workspace (ISO 8601 format).\n */\n last_modified?: string;\n\n /**\n * The creation date and time for this workspace (ISO 8601 format).\n */\n created?: string;\n };\n }\n}\n\n/**\n * A namespace for private data.\n */\nnamespace Private {\n /**\n * Get the url for a workspace.\n */\n export function url(base: string, id: string): string {\n const workspacesBase = URLExt.join(base, SERVICE_WORKSPACES_URL);\n const result = URLExt.join(workspacesBase, id);\n if (!result.startsWith(workspacesBase)) {\n throw new Error('Can only be used for workspaces requests');\n }\n return result;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { IDisposable } from '@lumino/disposable';\n\nimport { Poll } from '@lumino/polling';\n\nimport { ISignal, Signal } from '@lumino/signaling';\n\nimport { Builder, BuildManager } from './builder';\n\nimport { Contents, ContentsManager } from './contents';\n\nimport { Event, EventManager } from './event';\n\nimport { Kernel, KernelManager } from './kernel';\n\nimport { KernelSpec, KernelSpecManager } from './kernelspec';\n\nimport { NbConvert, NbConvertManager } from './nbconvert';\n\nimport { ServerConnection } from './serverconnection';\n\nimport { Session, SessionManager } from './session';\n\nimport { Setting, SettingManager } from './setting';\n\nimport { Terminal, TerminalManager } from './terminal';\n\nimport { User, UserManager } from './user';\n\nimport { Workspace, WorkspaceManager } from './workspace';\n\n/**\n * A Jupyter services manager.\n */\nexport class ServiceManager implements ServiceManager.IManager {\n /**\n * Construct a new services provider.\n */\n constructor(options: Partial<ServiceManager.IOptions> = {}) {\n const defaultDrive = options.defaultDrive;\n const serverSettings =\n options.serverSettings ?? ServerConnection.makeSettings();\n const standby = options.standby ?? 'when-hidden';\n const normalized = { defaultDrive, serverSettings, standby };\n\n this.serverSettings = serverSettings;\n this.contents = options.contents || new ContentsManager(normalized);\n this.events = options.events || new EventManager(normalized);\n this.kernels = options.kernels || new KernelManager(normalized);\n this.sessions =\n options.sessions ||\n new SessionManager({\n ...normalized,\n kernelManager: this.kernels\n });\n this.settings = options.settings || new SettingManager(normalized);\n this.terminals = options.terminals || new TerminalManager(normalized);\n this.builder = options.builder || new BuildManager(normalized);\n this.workspaces = options.workspaces || new WorkspaceManager(normalized);\n this.nbconvert = options.nbconvert || new NbConvertManager(normalized);\n this.kernelspecs = options.kernelspecs || new KernelSpecManager(normalized);\n this.user = options.user || new UserManager(normalized);\n\n // Proxy all connection failures from the individual service managers.\n this.kernelspecs.connectionFailure.connect(this._onConnectionFailure, this);\n this.sessions.connectionFailure.connect(this._onConnectionFailure, this);\n this.terminals.connectionFailure.connect(this._onConnectionFailure, this);\n\n // Define promises that need to be resolved before service manager is ready.\n const readyList = [this.sessions.ready, this.kernelspecs.ready];\n if (this.terminals.isAvailable()) {\n readyList.push(this.terminals.ready);\n }\n this._readyPromise = Promise.all(readyList).then(() => {\n this._isReady = true;\n });\n }\n\n /**\n * A signal emitted when there is a connection failure with the kernel.\n */\n get connectionFailure(): ISignal<this, Error> {\n return this._connectionFailure;\n }\n\n /**\n * Test whether the service manager is disposed.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * Dispose of the resources used by the manager.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n\n this._isDisposed = true;\n Signal.clearData(this);\n\n this.contents.dispose();\n this.events.dispose();\n this.sessions.dispose();\n this.terminals.dispose();\n }\n\n /**\n * The server settings of the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * Get the session manager instance.\n */\n readonly sessions: Session.IManager;\n\n /**\n * Get the kernel manager instance.\n */\n readonly kernels: Kernel.IManager;\n\n /**\n * Get the kernelspec manager instance.\n */\n readonly kernelspecs: KernelSpec.IManager;\n\n /**\n * Get the setting manager instance.\n */\n readonly settings: Setting.IManager;\n\n /**\n * The builder for the manager.\n */\n readonly builder: Builder.IManager;\n\n /**\n * Get the contents manager instance.\n */\n readonly contents: Contents.IManager;\n\n /**\n * The event manager instance.\n */\n readonly events: Event.IManager;\n\n /**\n * Get the terminal manager instance.\n */\n readonly terminals: Terminal.IManager;\n\n /**\n * Get the user manager instance.\n */\n readonly user: User.IManager;\n\n /**\n * Get the workspace manager instance.\n */\n readonly workspaces: Workspace.IManager;\n\n /**\n * Get the nbconvert manager instance.\n */\n readonly nbconvert: NbConvert.IManager;\n\n /**\n * Test whether the manager is ready.\n */\n get isReady(): boolean {\n return this._isReady;\n }\n\n /**\n * A promise that fulfills when the manager is ready.\n */\n get ready(): Promise<void> {\n return this._readyPromise;\n }\n\n private _onConnectionFailure(sender: any, err: Error): void {\n this._connectionFailure.emit(err);\n }\n\n private _isDisposed = false;\n private _readyPromise: Promise<void>;\n private _connectionFailure = new Signal<this, Error>(this);\n private _isReady = false;\n}\n\n/**\n * The namespace for `ServiceManager` statics.\n */\nexport namespace ServiceManager {\n /**\n * A service manager interface.\n */\n export interface IManager extends IDisposable, IManagers {\n /**\n * Test whether the manager is ready.\n */\n readonly isReady: boolean;\n\n /**\n * A promise that fulfills when the manager is initially ready.\n */\n readonly ready: Promise<void>;\n\n /**\n * A signal emitted when there is a connection failure with the server.\n */\n readonly connectionFailure: ISignal<IManager, Error>;\n }\n\n /**\n * The options used to create a service manager.\n */\n export interface IOptions extends IManagers {\n /**\n * The default drive for the contents manager.\n */\n readonly defaultDrive: Contents.IDrive;\n\n /**\n * When the manager stops polling the API. Defaults to `when-hidden`.\n */\n standby: Poll.Standby | (() => boolean | Poll.Standby);\n }\n\n /**\n * The managers provided by the service manager.\n */\n interface IManagers {\n /**\n * The builder for the manager.\n *\n * @deprecated will be removed in JupyterLab v5\n */\n readonly builder: Builder.IManager;\n\n /**\n * The contents manager for the manager.\n */\n readonly contents: Contents.IManager;\n\n /**\n * The events service manager.\n */\n readonly events: Event.IManager;\n\n /**\n * A promise that fulfills when the manager is initially ready.\n */\n readonly ready: Promise<void>;\n\n /**\n * The server settings of the manager.\n */\n readonly serverSettings: ServerConnection.ISettings;\n\n /**\n * The session manager for the manager.\n */\n readonly sessions: Session.IManager;\n\n /**\n * The kernel manager of the manager.\n */\n readonly kernels: Kernel.IManager;\n\n /**\n * The kernelspec manager for the manager.\n */\n readonly kernelspecs: KernelSpec.IManager;\n\n /**\n * The setting manager for the manager.\n */\n readonly settings: Setting.IManager;\n\n /**\n * The terminals manager for the manager.\n */\n readonly terminals: Terminal.IManager;\n\n /**\n * The user manager for the manager.\n */\n readonly user: User.IManager;\n\n /**\n * The workspace manager for the manager.\n */\n readonly workspaces: Workspace.IManager;\n\n /**\n * The nbconvert manager for the manager.\n */\n readonly nbconvert: NbConvert.IManager;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport {\n ConfigSection,\n Contents,\n Event,\n Kernel,\n KernelSpec,\n NbConvert,\n ServerConnection,\n Session,\n Setting,\n Terminal,\n User,\n Workspace\n} from '.';\nimport { ServiceManager } from './manager';\n\nimport { type IPlugin, Token } from '@lumino/coreutils';\n\n/**\n * The type for a service manager plugin.\n *\n * @typeparam T - The type that the plugin `provides` upon being activated.\n *\n * #### Notes\n * This type of plugin is different than a JupyterFrontEndPlugin,\n * as the app will still be `null` when its `activate` method is called.\n */\nexport type ServiceManagerPlugin<T> = IPlugin<null, T>;\n\n/**\n * Application connection status interface\n */\nexport interface IConnectionStatus {\n /**\n * Whether the application is connected to the server or not.\n *\n * #### Notes\n *\n * Every periodic network polling should be paused while this is set\n * to `false`. Extensions should use this value to decide whether to proceed\n * with the polling.\n * The extensions may also set this value to `false` if there is no need to\n * fetch anything from the server backend basing on some conditions\n * (e.g. when an error message dialog is displayed).\n * At the same time, the extensions are responsible for setting this value\n * back to `true`.\n */\n isConnected: boolean;\n}\n\n/**\n * Token providing the application connection status.\n */\nexport const IConnectionStatus = new Token<IConnectionStatus>(\n '@jupyterlab/application:IConnectionStatus',\n 'A service providing the application connection status.'\n);\n\n/**\n * Token providing the config section manager.\n */\nexport const IConfigSectionManager = new Token<ConfigSection.IManager>(\n '@jupyterlab/services:IConfigSectionManager',\n 'A service providing the config section manager.'\n);\n\n/**\n * The contents manager token.\n */\nexport const IContentsManager = new Token<Contents.IManager>(\n '@jupyterlab/services:IContentsManager',\n 'The contents manager token.'\n);\n\n/**\n * The default drive token.\n */\nexport const IDefaultDrive = new Token<Contents.IDrive>(\n '@jupyterlab/services:IDefaultDrive',\n 'The default drive for the contents manager.'\n);\n\n/**\n * The event manager token.\n */\nexport const IEventManager = new Token<Event.IManager>(\n '@jupyterlab/services:IEventManager',\n 'The event manager token.'\n);\n\n/**\n * The kernel manager token.\n */\nexport const IKernelManager = new Token<Kernel.IManager>(\n '@jupyterlab/services:IKernelManager',\n 'The kernel manager token.'\n);\n\n/**\n * The kernel spec manager token.\n */\nexport const IKernelSpecManager = new Token<KernelSpec.IManager>(\n '@jupyterlab/services:IKernelSpecManager',\n 'The kernel spec manager token.'\n);\n\n/**\n * The nbconvert manager token.\n */\nexport const INbConvertManager = new Token<NbConvert.IManager>(\n '@jupyterlab/services:INbConvertManager',\n 'The nbconvert manager token.'\n);\n\n/**\n * The server settings token.\n */\nexport const IServerSettings = new Token<ServerConnection.ISettings>(\n '@jupyterlab/services:IServerSettings',\n 'The server settings for the application.'\n);\n\n/**\n * The session manager token.\n */\nexport const ISessionManager = new Token<Session.IManager>(\n '@jupyterlab/services:ISessionManager',\n 'The session manager token.'\n);\n\n/**\n * The setting manager token.\n */\nexport const ISettingManager = new Token<Setting.IManager>(\n '@jupyterlab/services:ISettingManager',\n 'The setting manager token.'\n);\n\n/**\n * The default service manager token.\n */\nexport const IServiceManager = new Token<ServiceManager.IManager>(\n '@jupyterlab/services:IServiceManager',\n 'The service manager for the application.'\n);\n\n/**\n * The terminal manager token.\n */\nexport const ITerminalManager = new Token<Terminal.IManager>(\n '@jupyterlab/services:ITerminalManager',\n 'The terminal manager token.'\n);\n\n/**\n * The user manager token.\n */\nexport const IUserManager = new Token<User.IManager>(\n '@jupyterlab/services:IUserManager',\n 'The user manager token.'\n);\n\n/**\n * The workspace manager token.\n */\nexport const IWorkspaceManager = new Token<Workspace.IManager>(\n '@jupyterlab/services:IWorkspaceManager',\n 'The workspace manager token.'\n);\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n/**\n * @packageDocumentation\n * @module services\n */\n\nexport * from './basemanager';\nexport * from './config';\nexport * from './connectionstatus';\nexport * from './contents';\nexport * from './event';\nexport * from './kernel';\nexport * from './kernelspec';\nexport * from './manager';\nexport * from './serverconnection';\nexport * from './session';\nexport * from './setting';\nexport * from './terminal';\nexport * from './tokens';\nexport * from './user';\nexport * from './workspace';\nexport * from './nbconvert';\n\nexport { Builder } from './builder';\n", "'use strict';\n\n/**\n * @param typeMap [Object] Map of MIME type -> Array[extensions]\n * @param ...\n */\nfunction Mime() {\n this._types = Object.create(null);\n this._extensions = Object.create(null);\n\n for (let i = 0; i < arguments.length; i++) {\n this.define(arguments[i]);\n }\n\n this.define = this.define.bind(this);\n this.getType = this.getType.bind(this);\n this.getExtension = this.getExtension.bind(this);\n}\n\n/**\n * Define mimetype -> extension mappings. Each key is a mime-type that maps\n * to an array of extensions associated with the type. The first extension is\n * used as the default extension for the type.\n *\n * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});\n *\n * If a type declares an extension that has already been defined, an error will\n * be thrown. To suppress this error and force the extension to be associated\n * with the new type, pass `force`=true. Alternatively, you may prefix the\n * extension with \"*\" to map the type to extension, without mapping the\n * extension to the type.\n *\n * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});\n *\n *\n * @param map (Object) type definitions\n * @param force (Boolean) if true, force overriding of existing definitions\n */\nMime.prototype.define = function(typeMap, force) {\n for (let type in typeMap) {\n let extensions = typeMap[type].map(function(t) {\n return t.toLowerCase();\n });\n type = type.toLowerCase();\n\n for (let i = 0; i < extensions.length; i++) {\n const ext = extensions[i];\n\n // '*' prefix = not the preferred type for this extension. So fixup the\n // extension, and skip it.\n if (ext[0] === '*') {\n continue;\n }\n\n if (!force && (ext in this._types)) {\n throw new Error(\n 'Attempt to change mapping for \"' + ext +\n '\" extension from \"' + this._types[ext] + '\" to \"' + type +\n '\". Pass `force=true` to allow this, otherwise remove \"' + ext +\n '\" from the list of extensions for \"' + type + '\".'\n );\n }\n\n this._types[ext] = type;\n }\n\n // Use first extension as default\n if (force || !this._extensions[type]) {\n const ext = extensions[0];\n this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);\n }\n }\n};\n\n/**\n * Lookup a mime type based on extension\n */\nMime.prototype.getType = function(path) {\n path = String(path);\n let last = path.replace(/^.*[/\\\\]/, '').toLowerCase();\n let ext = last.replace(/^.*\\./, '').toLowerCase();\n\n let hasPath = last.length < path.length;\n let hasDot = ext.length < last.length - 1;\n\n return (hasDot || !hasPath) && this._types[ext] || null;\n};\n\n/**\n * Return file extension associated with a mime type\n */\nMime.prototype.getExtension = function(type) {\n type = /^\\s*([^;\\s]*)/.test(type) && RegExp.$1;\n return type && this._extensions[type.toLowerCase()] || null;\n};\n\nmodule.exports = Mime;\n", "module.exports = {\"application/andrew-inset\":[\"ez\"],\"application/applixware\":[\"aw\"],\"application/atom+xml\":[\"atom\"],\"application/atomcat+xml\":[\"atomcat\"],\"application/atomdeleted+xml\":[\"atomdeleted\"],\"application/atomsvc+xml\":[\"atomsvc\"],\"application/atsc-dwd+xml\":[\"dwd\"],\"application/atsc-held+xml\":[\"held\"],\"application/atsc-rsat+xml\":[\"rsat\"],\"application/bdoc\":[\"bdoc\"],\"application/calendar+xml\":[\"xcs\"],\"application/ccxml+xml\":[\"ccxml\"],\"application/cdfx+xml\":[\"cdfx\"],\"application/cdmi-capability\":[\"cdmia\"],\"application/cdmi-container\":[\"cdmic\"],\"application/cdmi-domain\":[\"cdmid\"],\"application/cdmi-object\":[\"cdmio\"],\"application/cdmi-queue\":[\"cdmiq\"],\"application/cu-seeme\":[\"cu\"],\"application/dash+xml\":[\"mpd\"],\"application/davmount+xml\":[\"davmount\"],\"application/docbook+xml\":[\"dbk\"],\"application/dssc+der\":[\"dssc\"],\"application/dssc+xml\":[\"xdssc\"],\"application/ecmascript\":[\"es\",\"ecma\"],\"application/emma+xml\":[\"emma\"],\"application/emotionml+xml\":[\"emotionml\"],\"application/epub+zip\":[\"epub\"],\"application/exi\":[\"exi\"],\"application/express\":[\"exp\"],\"application/fdt+xml\":[\"fdt\"],\"application/font-tdpfr\":[\"pfr\"],\"application/geo+json\":[\"geojson\"],\"application/gml+xml\":[\"gml\"],\"application/gpx+xml\":[\"gpx\"],\"application/gxf\":[\"gxf\"],\"application/gzip\":[\"gz\"],\"application/hjson\":[\"hjson\"],\"application/hyperstudio\":[\"stk\"],\"application/inkml+xml\":[\"ink\",\"inkml\"],\"application/ipfix\":[\"ipfix\"],\"application/its+xml\":[\"its\"],\"application/java-archive\":[\"jar\",\"war\",\"ear\"],\"application/java-serialized-object\":[\"ser\"],\"application/java-vm\":[\"class\"],\"application/javascript\":[\"js\",\"mjs\"],\"application/json\":[\"json\",\"map\"],\"application/json5\":[\"json5\"],\"application/jsonml+json\":[\"jsonml\"],\"application/ld+json\":[\"jsonld\"],\"application/lgr+xml\":[\"lgr\"],\"application/lost+xml\":[\"lostxml\"],\"application/mac-binhex40\":[\"hqx\"],\"application/mac-compactpro\":[\"cpt\"],\"application/mads+xml\":[\"mads\"],\"application/manifest+json\":[\"webmanifest\"],\"application/marc\":[\"mrc\"],\"application/marcxml+xml\":[\"mrcx\"],\"application/mathematica\":[\"ma\",\"nb\",\"mb\"],\"application/mathml+xml\":[\"mathml\"],\"application/mbox\":[\"mbox\"],\"application/mediaservercontrol+xml\":[\"mscml\"],\"application/metalink+xml\":[\"metalink\"],\"application/metalink4+xml\":[\"meta4\"],\"application/mets+xml\":[\"mets\"],\"application/mmt-aei+xml\":[\"maei\"],\"application/mmt-usd+xml\":[\"musd\"],\"application/mods+xml\":[\"mods\"],\"application/mp21\":[\"m21\",\"mp21\"],\"application/mp4\":[\"mp4s\",\"m4p\"],\"application/msword\":[\"doc\",\"dot\"],\"application/mxf\":[\"mxf\"],\"application/n-quads\":[\"nq\"],\"application/n-triples\":[\"nt\"],\"application/node\":[\"cjs\"],\"application/octet-stream\":[\"bin\",\"dms\",\"lrf\",\"mar\",\"so\",\"dist\",\"distz\",\"pkg\",\"bpk\",\"dump\",\"elc\",\"deploy\",\"exe\",\"dll\",\"deb\",\"dmg\",\"iso\",\"img\",\"msi\",\"msp\",\"msm\",\"buffer\"],\"application/oda\":[\"oda\"],\"application/oebps-package+xml\":[\"opf\"],\"application/ogg\":[\"ogx\"],\"application/omdoc+xml\":[\"omdoc\"],\"application/onenote\":[\"onetoc\",\"onetoc2\",\"onetmp\",\"onepkg\"],\"application/oxps\":[\"oxps\"],\"application/p2p-overlay+xml\":[\"relo\"],\"application/patch-ops-error+xml\":[\"xer\"],\"application/pdf\":[\"pdf\"],\"application/pgp-encrypted\":[\"pgp\"],\"application/pgp-signature\":[\"asc\",\"sig\"],\"application/pics-rules\":[\"prf\"],\"application/pkcs10\":[\"p10\"],\"application/pkcs7-mime\":[\"p7m\",\"p7c\"],\"application/pkcs7-signature\":[\"p7s\"],\"application/pkcs8\":[\"p8\"],\"application/pkix-attr-cert\":[\"ac\"],\"application/pkix-cert\":[\"cer\"],\"application/pkix-crl\":[\"crl\"],\"application/pkix-pkipath\":[\"pkipath\"],\"application/pkixcmp\":[\"pki\"],\"application/pls+xml\":[\"pls\"],\"application/postscript\":[\"ai\",\"eps\",\"ps\"],\"application/provenance+xml\":[\"provx\"],\"application/pskc+xml\":[\"pskcxml\"],\"application/raml+yaml\":[\"raml\"],\"application/rdf+xml\":[\"rdf\",\"owl\"],\"application/reginfo+xml\":[\"rif\"],\"application/relax-ng-compact-syntax\":[\"rnc\"],\"application/resource-lists+xml\":[\"rl\"],\"application/resource-lists-diff+xml\":[\"rld\"],\"application/rls-services+xml\":[\"rs\"],\"application/route-apd+xml\":[\"rapd\"],\"application/route-s-tsid+xml\":[\"sls\"],\"application/route-usd+xml\":[\"rusd\"],\"application/rpki-ghostbusters\":[\"gbr\"],\"application/rpki-manifest\":[\"mft\"],\"application/rpki-roa\":[\"roa\"],\"application/rsd+xml\":[\"rsd\"],\"application/rss+xml\":[\"rss\"],\"application/rtf\":[\"rtf\"],\"application/sbml+xml\":[\"sbml\"],\"application/scvp-cv-request\":[\"scq\"],\"application/scvp-cv-response\":[\"scs\"],\"application/scvp-vp-request\":[\"spq\"],\"application/scvp-vp-response\":[\"spp\"],\"application/sdp\":[\"sdp\"],\"application/senml+xml\":[\"senmlx\"],\"application/sensml+xml\":[\"sensmlx\"],\"application/set-payment-initiation\":[\"setpay\"],\"application/set-registration-initiation\":[\"setreg\"],\"application/shf+xml\":[\"shf\"],\"application/sieve\":[\"siv\",\"sieve\"],\"application/smil+xml\":[\"smi\",\"smil\"],\"application/sparql-query\":[\"rq\"],\"application/sparql-results+xml\":[\"srx\"],\"application/srgs\":[\"gram\"],\"application/srgs+xml\":[\"grxml\"],\"application/sru+xml\":[\"sru\"],\"application/ssdl+xml\":[\"ssdl\"],\"application/ssml+xml\":[\"ssml\"],\"application/swid+xml\":[\"swidtag\"],\"application/tei+xml\":[\"tei\",\"teicorpus\"],\"application/thraud+xml\":[\"tfi\"],\"application/timestamped-data\":[\"tsd\"],\"application/toml\":[\"toml\"],\"application/trig\":[\"trig\"],\"application/ttml+xml\":[\"ttml\"],\"application/ubjson\":[\"ubj\"],\"application/urc-ressheet+xml\":[\"rsheet\"],\"application/urc-targetdesc+xml\":[\"td\"],\"application/voicexml+xml\":[\"vxml\"],\"application/wasm\":[\"wasm\"],\"application/widget\":[\"wgt\"],\"application/winhlp\":[\"hlp\"],\"application/wsdl+xml\":[\"wsdl\"],\"application/wspolicy+xml\":[\"wspolicy\"],\"application/xaml+xml\":[\"xaml\"],\"application/xcap-att+xml\":[\"xav\"],\"application/xcap-caps+xml\":[\"xca\"],\"application/xcap-diff+xml\":[\"xdf\"],\"application/xcap-el+xml\":[\"xel\"],\"application/xcap-ns+xml\":[\"xns\"],\"application/xenc+xml\":[\"xenc\"],\"application/xhtml+xml\":[\"xhtml\",\"xht\"],\"application/xliff+xml\":[\"xlf\"],\"application/xml\":[\"xml\",\"xsl\",\"xsd\",\"rng\"],\"application/xml-dtd\":[\"dtd\"],\"application/xop+xml\":[\"xop\"],\"application/xproc+xml\":[\"xpl\"],\"application/xslt+xml\":[\"*xsl\",\"xslt\"],\"application/xspf+xml\":[\"xspf\"],\"application/xv+xml\":[\"mxml\",\"xhvml\",\"xvml\",\"xvm\"],\"application/yang\":[\"yang\"],\"application/yin+xml\":[\"yin\"],\"application/zip\":[\"zip\"],\"audio/3gpp\":[\"*3gpp\"],\"audio/adpcm\":[\"adp\"],\"audio/amr\":[\"amr\"],\"audio/basic\":[\"au\",\"snd\"],\"audio/midi\":[\"mid\",\"midi\",\"kar\",\"rmi\"],\"audio/mobile-xmf\":[\"mxmf\"],\"audio/mp3\":[\"*mp3\"],\"audio/mp4\":[\"m4a\",\"mp4a\"],\"audio/mpeg\":[\"mpga\",\"mp2\",\"mp2a\",\"mp3\",\"m2a\",\"m3a\"],\"audio/ogg\":[\"oga\",\"ogg\",\"spx\",\"opus\"],\"audio/s3m\":[\"s3m\"],\"audio/silk\":[\"sil\"],\"audio/wav\":[\"wav\"],\"audio/wave\":[\"*wav\"],\"audio/webm\":[\"weba\"],\"audio/xm\":[\"xm\"],\"font/collection\":[\"ttc\"],\"font/otf\":[\"otf\"],\"font/ttf\":[\"ttf\"],\"font/woff\":[\"woff\"],\"font/woff2\":[\"woff2\"],\"image/aces\":[\"exr\"],\"image/apng\":[\"apng\"],\"image/avif\":[\"avif\"],\"image/bmp\":[\"bmp\"],\"image/cgm\":[\"cgm\"],\"image/dicom-rle\":[\"drle\"],\"image/emf\":[\"emf\"],\"image/fits\":[\"fits\"],\"image/g3fax\":[\"g3\"],\"image/gif\":[\"gif\"],\"image/heic\":[\"heic\"],\"image/heic-sequence\":[\"heics\"],\"image/heif\":[\"heif\"],\"image/heif-sequence\":[\"heifs\"],\"image/hej2k\":[\"hej2\"],\"image/hsj2\":[\"hsj2\"],\"image/ief\":[\"ief\"],\"image/jls\":[\"jls\"],\"image/jp2\":[\"jp2\",\"jpg2\"],\"image/jpeg\":[\"jpeg\",\"jpg\",\"jpe\"],\"image/jph\":[\"jph\"],\"image/jphc\":[\"jhc\"],\"image/jpm\":[\"jpm\"],\"image/jpx\":[\"jpx\",\"jpf\"],\"image/jxr\":[\"jxr\"],\"image/jxra\":[\"jxra\"],\"image/jxrs\":[\"jxrs\"],\"image/jxs\":[\"jxs\"],\"image/jxsc\":[\"jxsc\"],\"image/jxsi\":[\"jxsi\"],\"image/jxss\":[\"jxss\"],\"image/ktx\":[\"ktx\"],\"image/ktx2\":[\"ktx2\"],\"image/png\":[\"png\"],\"image/sgi\":[\"sgi\"],\"image/svg+xml\":[\"svg\",\"svgz\"],\"image/t38\":[\"t38\"],\"image/tiff\":[\"tif\",\"tiff\"],\"image/tiff-fx\":[\"tfx\"],\"image/webp\":[\"webp\"],\"image/wmf\":[\"wmf\"],\"message/disposition-notification\":[\"disposition-notification\"],\"message/global\":[\"u8msg\"],\"message/global-delivery-status\":[\"u8dsn\"],\"message/global-disposition-notification\":[\"u8mdn\"],\"message/global-headers\":[\"u8hdr\"],\"message/rfc822\":[\"eml\",\"mime\"],\"model/3mf\":[\"3mf\"],\"model/gltf+json\":[\"gltf\"],\"model/gltf-binary\":[\"glb\"],\"model/iges\":[\"igs\",\"iges\"],\"model/mesh\":[\"msh\",\"mesh\",\"silo\"],\"model/mtl\":[\"mtl\"],\"model/obj\":[\"obj\"],\"model/step+xml\":[\"stpx\"],\"model/step+zip\":[\"stpz\"],\"model/step-xml+zip\":[\"stpxz\"],\"model/stl\":[\"stl\"],\"model/vrml\":[\"wrl\",\"vrml\"],\"model/x3d+binary\":[\"*x3db\",\"x3dbz\"],\"model/x3d+fastinfoset\":[\"x3db\"],\"model/x3d+vrml\":[\"*x3dv\",\"x3dvz\"],\"model/x3d+xml\":[\"x3d\",\"x3dz\"],\"model/x3d-vrml\":[\"x3dv\"],\"text/cache-manifest\":[\"appcache\",\"manifest\"],\"text/calendar\":[\"ics\",\"ifb\"],\"text/coffeescript\":[\"coffee\",\"litcoffee\"],\"text/css\":[\"css\"],\"text/csv\":[\"csv\"],\"text/html\":[\"html\",\"htm\",\"shtml\"],\"text/jade\":[\"jade\"],\"text/jsx\":[\"jsx\"],\"text/less\":[\"less\"],\"text/markdown\":[\"markdown\",\"md\"],\"text/mathml\":[\"mml\"],\"text/mdx\":[\"mdx\"],\"text/n3\":[\"n3\"],\"text/plain\":[\"txt\",\"text\",\"conf\",\"def\",\"list\",\"log\",\"in\",\"ini\"],\"text/richtext\":[\"rtx\"],\"text/rtf\":[\"*rtf\"],\"text/sgml\":[\"sgml\",\"sgm\"],\"text/shex\":[\"shex\"],\"text/slim\":[\"slim\",\"slm\"],\"text/spdx\":[\"spdx\"],\"text/stylus\":[\"stylus\",\"styl\"],\"text/tab-separated-values\":[\"tsv\"],\"text/troff\":[\"t\",\"tr\",\"roff\",\"man\",\"me\",\"ms\"],\"text/turtle\":[\"ttl\"],\"text/uri-list\":[\"uri\",\"uris\",\"urls\"],\"text/vcard\":[\"vcard\"],\"text/vtt\":[\"vtt\"],\"text/xml\":[\"*xml\"],\"text/yaml\":[\"yaml\",\"yml\"],\"video/3gpp\":[\"3gp\",\"3gpp\"],\"video/3gpp2\":[\"3g2\"],\"video/h261\":[\"h261\"],\"video/h263\":[\"h263\"],\"video/h264\":[\"h264\"],\"video/iso.segment\":[\"m4s\"],\"video/jpeg\":[\"jpgv\"],\"video/jpm\":[\"*jpm\",\"jpgm\"],\"video/mj2\":[\"mj2\",\"mjp2\"],\"video/mp2t\":[\"ts\"],\"video/mp4\":[\"mp4\",\"mp4v\",\"mpg4\"],\"video/mpeg\":[\"mpeg\",\"mpg\",\"mpe\",\"m1v\",\"m2v\"],\"video/ogg\":[\"ogv\"],\"video/quicktime\":[\"qt\",\"mov\"],\"video/webm\":[\"webm\"]};", "module.exports = {\"application/prs.cww\":[\"cww\"],\"application/vnd.1000minds.decision-model+xml\":[\"1km\"],\"application/vnd.3gpp.pic-bw-large\":[\"plb\"],\"application/vnd.3gpp.pic-bw-small\":[\"psb\"],\"application/vnd.3gpp.pic-bw-var\":[\"pvb\"],\"application/vnd.3gpp2.tcap\":[\"tcap\"],\"application/vnd.3m.post-it-notes\":[\"pwn\"],\"application/vnd.accpac.simply.aso\":[\"aso\"],\"application/vnd.accpac.simply.imp\":[\"imp\"],\"application/vnd.acucobol\":[\"acu\"],\"application/vnd.acucorp\":[\"atc\",\"acutc\"],\"application/vnd.adobe.air-application-installer-package+zip\":[\"air\"],\"application/vnd.adobe.formscentral.fcdt\":[\"fcdt\"],\"application/vnd.adobe.fxp\":[\"fxp\",\"fxpl\"],\"application/vnd.adobe.xdp+xml\":[\"xdp\"],\"application/vnd.adobe.xfdf\":[\"xfdf\"],\"application/vnd.ahead.space\":[\"ahead\"],\"application/vnd.airzip.filesecure.azf\":[\"azf\"],\"application/vnd.airzip.filesecure.azs\":[\"azs\"],\"application/vnd.amazon.ebook\":[\"azw\"],\"application/vnd.americandynamics.acc\":[\"acc\"],\"application/vnd.amiga.ami\":[\"ami\"],\"application/vnd.android.package-archive\":[\"apk\"],\"application/vnd.anser-web-certificate-issue-initiation\":[\"cii\"],\"application/vnd.anser-web-funds-transfer-initiation\":[\"fti\"],\"application/vnd.antix.game-component\":[\"atx\"],\"application/vnd.apple.installer+xml\":[\"mpkg\"],\"application/vnd.apple.keynote\":[\"key\"],\"application/vnd.apple.mpegurl\":[\"m3u8\"],\"application/vnd.apple.numbers\":[\"numbers\"],\"application/vnd.apple.pages\":[\"pages\"],\"application/vnd.apple.pkpass\":[\"pkpass\"],\"application/vnd.aristanetworks.swi\":[\"swi\"],\"application/vnd.astraea-software.iota\":[\"iota\"],\"application/vnd.audiograph\":[\"aep\"],\"application/vnd.balsamiq.bmml+xml\":[\"bmml\"],\"application/vnd.blueice.multipass\":[\"mpm\"],\"application/vnd.bmi\":[\"bmi\"],\"application/vnd.businessobjects\":[\"rep\"],\"application/vnd.chemdraw+xml\":[\"cdxml\"],\"application/vnd.chipnuts.karaoke-mmd\":[\"mmd\"],\"application/vnd.cinderella\":[\"cdy\"],\"application/vnd.citationstyles.style+xml\":[\"csl\"],\"application/vnd.claymore\":[\"cla\"],\"application/vnd.cloanto.rp9\":[\"rp9\"],\"application/vnd.clonk.c4group\":[\"c4g\",\"c4d\",\"c4f\",\"c4p\",\"c4u\"],\"application/vnd.cluetrust.cartomobile-config\":[\"c11amc\"],\"application/vnd.cluetrust.cartomobile-config-pkg\":[\"c11amz\"],\"application/vnd.commonspace\":[\"csp\"],\"application/vnd.contact.cmsg\":[\"cdbcmsg\"],\"application/vnd.cosmocaller\":[\"cmc\"],\"application/vnd.crick.clicker\":[\"clkx\"],\"application/vnd.crick.clicker.keyboard\":[\"clkk\"],\"application/vnd.crick.clicker.palette\":[\"clkp\"],\"application/vnd.crick.clicker.template\":[\"clkt\"],\"application/vnd.crick.clicker.wordbank\":[\"clkw\"],\"application/vnd.criticaltools.wbs+xml\":[\"wbs\"],\"application/vnd.ctc-posml\":[\"pml\"],\"application/vnd.cups-ppd\":[\"ppd\"],\"application/vnd.curl.car\":[\"car\"],\"application/vnd.curl.pcurl\":[\"pcurl\"],\"application/vnd.dart\":[\"dart\"],\"application/vnd.data-vision.rdz\":[\"rdz\"],\"application/vnd.dbf\":[\"dbf\"],\"application/vnd.dece.data\":[\"uvf\",\"uvvf\",\"uvd\",\"uvvd\"],\"application/vnd.dece.ttml+xml\":[\"uvt\",\"uvvt\"],\"application/vnd.dece.unspecified\":[\"uvx\",\"uvvx\"],\"application/vnd.dece.zip\":[\"uvz\",\"uvvz\"],\"application/vnd.denovo.fcselayout-link\":[\"fe_launch\"],\"application/vnd.dna\":[\"dna\"],\"application/vnd.dolby.mlp\":[\"mlp\"],\"application/vnd.dpgraph\":[\"dpg\"],\"application/vnd.dreamfactory\":[\"dfac\"],\"application/vnd.ds-keypoint\":[\"kpxx\"],\"application/vnd.dvb.ait\":[\"ait\"],\"application/vnd.dvb.service\":[\"svc\"],\"application/vnd.dynageo\":[\"geo\"],\"application/vnd.ecowin.chart\":[\"mag\"],\"application/vnd.enliven\":[\"nml\"],\"application/vnd.epson.esf\":[\"esf\"],\"application/vnd.epson.msf\":[\"msf\"],\"application/vnd.epson.quickanime\":[\"qam\"],\"application/vnd.epson.salt\":[\"slt\"],\"application/vnd.epson.ssf\":[\"ssf\"],\"application/vnd.eszigno3+xml\":[\"es3\",\"et3\"],\"application/vnd.ezpix-album\":[\"ez2\"],\"application/vnd.ezpix-package\":[\"ez3\"],\"application/vnd.fdf\":[\"fdf\"],\"application/vnd.fdsn.mseed\":[\"mseed\"],\"application/vnd.fdsn.seed\":[\"seed\",\"dataless\"],\"application/vnd.flographit\":[\"gph\"],\"application/vnd.fluxtime.clip\":[\"ftc\"],\"application/vnd.framemaker\":[\"fm\",\"frame\",\"maker\",\"book\"],\"application/vnd.frogans.fnc\":[\"fnc\"],\"application/vnd.frogans.ltf\":[\"ltf\"],\"application/vnd.fsc.weblaunch\":[\"fsc\"],\"application/vnd.fujitsu.oasys\":[\"oas\"],\"application/vnd.fujitsu.oasys2\":[\"oa2\"],\"application/vnd.fujitsu.oasys3\":[\"oa3\"],\"application/vnd.fujitsu.oasysgp\":[\"fg5\"],\"application/vnd.fujitsu.oasysprs\":[\"bh2\"],\"application/vnd.fujixerox.ddd\":[\"ddd\"],\"application/vnd.fujixerox.docuworks\":[\"xdw\"],\"application/vnd.fujixerox.docuworks.binder\":[\"xbd\"],\"application/vnd.fuzzysheet\":[\"fzs\"],\"application/vnd.genomatix.tuxedo\":[\"txd\"],\"application/vnd.geogebra.file\":[\"ggb\"],\"application/vnd.geogebra.tool\":[\"ggt\"],\"application/vnd.geometry-explorer\":[\"gex\",\"gre\"],\"application/vnd.geonext\":[\"gxt\"],\"application/vnd.geoplan\":[\"g2w\"],\"application/vnd.geospace\":[\"g3w\"],\"application/vnd.gmx\":[\"gmx\"],\"application/vnd.google-apps.document\":[\"gdoc\"],\"application/vnd.google-apps.presentation\":[\"gslides\"],\"application/vnd.google-apps.spreadsheet\":[\"gsheet\"],\"application/vnd.google-earth.kml+xml\":[\"kml\"],\"application/vnd.google-earth.kmz\":[\"kmz\"],\"application/vnd.grafeq\":[\"gqf\",\"gqs\"],\"application/vnd.groove-account\":[\"gac\"],\"application/vnd.groove-help\":[\"ghf\"],\"application/vnd.groove-identity-message\":[\"gim\"],\"application/vnd.groove-injector\":[\"grv\"],\"application/vnd.groove-tool-message\":[\"gtm\"],\"application/vnd.groove-tool-template\":[\"tpl\"],\"application/vnd.groove-vcard\":[\"vcg\"],\"application/vnd.hal+xml\":[\"hal\"],\"application/vnd.handheld-entertainment+xml\":[\"zmm\"],\"application/vnd.hbci\":[\"hbci\"],\"application/vnd.hhe.lesson-player\":[\"les\"],\"application/vnd.hp-hpgl\":[\"hpgl\"],\"application/vnd.hp-hpid\":[\"hpid\"],\"application/vnd.hp-hps\":[\"hps\"],\"application/vnd.hp-jlyt\":[\"jlt\"],\"application/vnd.hp-pcl\":[\"pcl\"],\"application/vnd.hp-pclxl\":[\"pclxl\"],\"application/vnd.hydrostatix.sof-data\":[\"sfd-hdstx\"],\"application/vnd.ibm.minipay\":[\"mpy\"],\"application/vnd.ibm.modcap\":[\"afp\",\"listafp\",\"list3820\"],\"application/vnd.ibm.rights-management\":[\"irm\"],\"application/vnd.ibm.secure-container\":[\"sc\"],\"application/vnd.iccprofile\":[\"icc\",\"icm\"],\"application/vnd.igloader\":[\"igl\"],\"application/vnd.immervision-ivp\":[\"ivp\"],\"application/vnd.immervision-ivu\":[\"ivu\"],\"application/vnd.insors.igm\":[\"igm\"],\"application/vnd.intercon.formnet\":[\"xpw\",\"xpx\"],\"application/vnd.intergeo\":[\"i2g\"],\"application/vnd.intu.qbo\":[\"qbo\"],\"application/vnd.intu.qfx\":[\"qfx\"],\"application/vnd.ipunplugged.rcprofile\":[\"rcprofile\"],\"application/vnd.irepository.package+xml\":[\"irp\"],\"application/vnd.is-xpr\":[\"xpr\"],\"application/vnd.isac.fcs\":[\"fcs\"],\"application/vnd.jam\":[\"jam\"],\"application/vnd.jcp.javame.midlet-rms\":[\"rms\"],\"application/vnd.jisp\":[\"jisp\"],\"application/vnd.joost.joda-archive\":[\"joda\"],\"application/vnd.kahootz\":[\"ktz\",\"ktr\"],\"application/vnd.kde.karbon\":[\"karbon\"],\"application/vnd.kde.kchart\":[\"chrt\"],\"application/vnd.kde.kformula\":[\"kfo\"],\"application/vnd.kde.kivio\":[\"flw\"],\"application/vnd.kde.kontour\":[\"kon\"],\"application/vnd.kde.kpresenter\":[\"kpr\",\"kpt\"],\"application/vnd.kde.kspread\":[\"ksp\"],\"application/vnd.kde.kword\":[\"kwd\",\"kwt\"],\"application/vnd.kenameaapp\":[\"htke\"],\"application/vnd.kidspiration\":[\"kia\"],\"application/vnd.kinar\":[\"kne\",\"knp\"],\"application/vnd.koan\":[\"skp\",\"skd\",\"skt\",\"skm\"],\"application/vnd.kodak-descriptor\":[\"sse\"],\"application/vnd.las.las+xml\":[\"lasxml\"],\"application/vnd.llamagraphics.life-balance.desktop\":[\"lbd\"],\"application/vnd.llamagraphics.life-balance.exchange+xml\":[\"lbe\"],\"application/vnd.lotus-1-2-3\":[\"123\"],\"application/vnd.lotus-approach\":[\"apr\"],\"application/vnd.lotus-freelance\":[\"pre\"],\"application/vnd.lotus-notes\":[\"nsf\"],\"application/vnd.lotus-organizer\":[\"org\"],\"application/vnd.lotus-screencam\":[\"scm\"],\"application/vnd.lotus-wordpro\":[\"lwp\"],\"application/vnd.macports.portpkg\":[\"portpkg\"],\"application/vnd.mapbox-vector-tile\":[\"mvt\"],\"application/vnd.mcd\":[\"mcd\"],\"application/vnd.medcalcdata\":[\"mc1\"],\"application/vnd.mediastation.cdkey\":[\"cdkey\"],\"application/vnd.mfer\":[\"mwf\"],\"application/vnd.mfmp\":[\"mfm\"],\"application/vnd.micrografx.flo\":[\"flo\"],\"application/vnd.micrografx.igx\":[\"igx\"],\"application/vnd.mif\":[\"mif\"],\"application/vnd.mobius.daf\":[\"daf\"],\"application/vnd.mobius.dis\":[\"dis\"],\"application/vnd.mobius.mbk\":[\"mbk\"],\"application/vnd.mobius.mqy\":[\"mqy\"],\"application/vnd.mobius.msl\":[\"msl\"],\"application/vnd.mobius.plc\":[\"plc\"],\"application/vnd.mobius.txf\":[\"txf\"],\"application/vnd.mophun.application\":[\"mpn\"],\"application/vnd.mophun.certificate\":[\"mpc\"],\"application/vnd.mozilla.xul+xml\":[\"xul\"],\"application/vnd.ms-artgalry\":[\"cil\"],\"application/vnd.ms-cab-compressed\":[\"cab\"],\"application/vnd.ms-excel\":[\"xls\",\"xlm\",\"xla\",\"xlc\",\"xlt\",\"xlw\"],\"application/vnd.ms-excel.addin.macroenabled.12\":[\"xlam\"],\"application/vnd.ms-excel.sheet.binary.macroenabled.12\":[\"xlsb\"],\"application/vnd.ms-excel.sheet.macroenabled.12\":[\"xlsm\"],\"application/vnd.ms-excel.template.macroenabled.12\":[\"xltm\"],\"application/vnd.ms-fontobject\":[\"eot\"],\"application/vnd.ms-htmlhelp\":[\"chm\"],\"application/vnd.ms-ims\":[\"ims\"],\"application/vnd.ms-lrm\":[\"lrm\"],\"application/vnd.ms-officetheme\":[\"thmx\"],\"application/vnd.ms-outlook\":[\"msg\"],\"application/vnd.ms-pki.seccat\":[\"cat\"],\"application/vnd.ms-pki.stl\":[\"*stl\"],\"application/vnd.ms-powerpoint\":[\"ppt\",\"pps\",\"pot\"],\"application/vnd.ms-powerpoint.addin.macroenabled.12\":[\"ppam\"],\"application/vnd.ms-powerpoint.presentation.macroenabled.12\":[\"pptm\"],\"application/vnd.ms-powerpoint.slide.macroenabled.12\":[\"sldm\"],\"application/vnd.ms-powerpoint.slideshow.macroenabled.12\":[\"ppsm\"],\"application/vnd.ms-powerpoint.template.macroenabled.12\":[\"potm\"],\"application/vnd.ms-project\":[\"mpp\",\"mpt\"],\"application/vnd.ms-word.document.macroenabled.12\":[\"docm\"],\"application/vnd.ms-word.template.macroenabled.12\":[\"dotm\"],\"application/vnd.ms-works\":[\"wps\",\"wks\",\"wcm\",\"wdb\"],\"application/vnd.ms-wpl\":[\"wpl\"],\"application/vnd.ms-xpsdocument\":[\"xps\"],\"application/vnd.mseq\":[\"mseq\"],\"application/vnd.musician\":[\"mus\"],\"application/vnd.muvee.style\":[\"msty\"],\"application/vnd.mynfc\":[\"taglet\"],\"application/vnd.neurolanguage.nlu\":[\"nlu\"],\"application/vnd.nitf\":[\"ntf\",\"nitf\"],\"application/vnd.noblenet-directory\":[\"nnd\"],\"application/vnd.noblenet-sealer\":[\"nns\"],\"application/vnd.noblenet-web\":[\"nnw\"],\"application/vnd.nokia.n-gage.ac+xml\":[\"*ac\"],\"application/vnd.nokia.n-gage.data\":[\"ngdat\"],\"application/vnd.nokia.n-gage.symbian.install\":[\"n-gage\"],\"application/vnd.nokia.radio-preset\":[\"rpst\"],\"application/vnd.nokia.radio-presets\":[\"rpss\"],\"application/vnd.novadigm.edm\":[\"edm\"],\"application/vnd.novadigm.edx\":[\"edx\"],\"application/vnd.novadigm.ext\":[\"ext\"],\"application/vnd.oasis.opendocument.chart\":[\"odc\"],\"application/vnd.oasis.opendocument.chart-template\":[\"otc\"],\"application/vnd.oasis.opendocument.database\":[\"odb\"],\"application/vnd.oasis.opendocument.formula\":[\"odf\"],\"application/vnd.oasis.opendocument.formula-template\":[\"odft\"],\"application/vnd.oasis.opendocument.graphics\":[\"odg\"],\"application/vnd.oasis.opendocument.graphics-template\":[\"otg\"],\"application/vnd.oasis.opendocument.image\":[\"odi\"],\"application/vnd.oasis.opendocument.image-template\":[\"oti\"],\"application/vnd.oasis.opendocument.presentation\":[\"odp\"],\"application/vnd.oasis.opendocument.presentation-template\":[\"otp\"],\"application/vnd.oasis.opendocument.spreadsheet\":[\"ods\"],\"application/vnd.oasis.opendocument.spreadsheet-template\":[\"ots\"],\"application/vnd.oasis.opendocument.text\":[\"odt\"],\"application/vnd.oasis.opendocument.text-master\":[\"odm\"],\"application/vnd.oasis.opendocument.text-template\":[\"ott\"],\"application/vnd.oasis.opendocument.text-web\":[\"oth\"],\"application/vnd.olpc-sugar\":[\"xo\"],\"application/vnd.oma.dd2+xml\":[\"dd2\"],\"application/vnd.openblox.game+xml\":[\"obgx\"],\"application/vnd.openofficeorg.extension\":[\"oxt\"],\"application/vnd.openstreetmap.data+xml\":[\"osm\"],\"application/vnd.openxmlformats-officedocument.presentationml.presentation\":[\"pptx\"],\"application/vnd.openxmlformats-officedocument.presentationml.slide\":[\"sldx\"],\"application/vnd.openxmlformats-officedocument.presentationml.slideshow\":[\"ppsx\"],\"application/vnd.openxmlformats-officedocument.presentationml.template\":[\"potx\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\":[\"xlsx\"],\"application/vnd.openxmlformats-officedocument.spreadsheetml.template\":[\"xltx\"],\"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":[\"docx\"],\"application/vnd.openxmlformats-officedocument.wordprocessingml.template\":[\"dotx\"],\"application/vnd.osgeo.mapguide.package\":[\"mgp\"],\"application/vnd.osgi.dp\":[\"dp\"],\"application/vnd.osgi.subsystem\":[\"esa\"],\"application/vnd.palm\":[\"pdb\",\"pqa\",\"oprc\"],\"application/vnd.pawaafile\":[\"paw\"],\"application/vnd.pg.format\":[\"str\"],\"application/vnd.pg.osasli\":[\"ei6\"],\"application/vnd.picsel\":[\"efif\"],\"application/vnd.pmi.widget\":[\"wg\"],\"application/vnd.pocketlearn\":[\"plf\"],\"application/vnd.powerbuilder6\":[\"pbd\"],\"application/vnd.previewsystems.box\":[\"box\"],\"application/vnd.proteus.magazine\":[\"mgz\"],\"application/vnd.publishare-delta-tree\":[\"qps\"],\"application/vnd.pvi.ptid1\":[\"ptid\"],\"application/vnd.quark.quarkxpress\":[\"qxd\",\"qxt\",\"qwd\",\"qwt\",\"qxl\",\"qxb\"],\"application/vnd.rar\":[\"rar\"],\"application/vnd.realvnc.bed\":[\"bed\"],\"application/vnd.recordare.musicxml\":[\"mxl\"],\"application/vnd.recordare.musicxml+xml\":[\"musicxml\"],\"application/vnd.rig.cryptonote\":[\"cryptonote\"],\"application/vnd.rim.cod\":[\"cod\"],\"application/vnd.rn-realmedia\":[\"rm\"],\"application/vnd.rn-realmedia-vbr\":[\"rmvb\"],\"application/vnd.route66.link66+xml\":[\"link66\"],\"application/vnd.sailingtracker.track\":[\"st\"],\"application/vnd.seemail\":[\"see\"],\"application/vnd.sema\":[\"sema\"],\"application/vnd.semd\":[\"semd\"],\"application/vnd.semf\":[\"semf\"],\"application/vnd.shana.informed.formdata\":[\"ifm\"],\"application/vnd.shana.informed.formtemplate\":[\"itp\"],\"application/vnd.shana.informed.interchange\":[\"iif\"],\"application/vnd.shana.informed.package\":[\"ipk\"],\"application/vnd.simtech-mindmapper\":[\"twd\",\"twds\"],\"application/vnd.smaf\":[\"mmf\"],\"application/vnd.smart.teacher\":[\"teacher\"],\"application/vnd.software602.filler.form+xml\":[\"fo\"],\"application/vnd.solent.sdkm+xml\":[\"sdkm\",\"sdkd\"],\"application/vnd.spotfire.dxp\":[\"dxp\"],\"application/vnd.spotfire.sfs\":[\"sfs\"],\"application/vnd.stardivision.calc\":[\"sdc\"],\"application/vnd.stardivision.draw\":[\"sda\"],\"application/vnd.stardivision.impress\":[\"sdd\"],\"application/vnd.stardivision.math\":[\"smf\"],\"application/vnd.stardivision.writer\":[\"sdw\",\"vor\"],\"application/vnd.stardivision.writer-global\":[\"sgl\"],\"application/vnd.stepmania.package\":[\"smzip\"],\"application/vnd.stepmania.stepchart\":[\"sm\"],\"application/vnd.sun.wadl+xml\":[\"wadl\"],\"application/vnd.sun.xml.calc\":[\"sxc\"],\"application/vnd.sun.xml.calc.template\":[\"stc\"],\"application/vnd.sun.xml.draw\":[\"sxd\"],\"application/vnd.sun.xml.draw.template\":[\"std\"],\"application/vnd.sun.xml.impress\":[\"sxi\"],\"application/vnd.sun.xml.impress.template\":[\"sti\"],\"application/vnd.sun.xml.math\":[\"sxm\"],\"application/vnd.sun.xml.writer\":[\"sxw\"],\"application/vnd.sun.xml.writer.global\":[\"sxg\"],\"application/vnd.sun.xml.writer.template\":[\"stw\"],\"application/vnd.sus-calendar\":[\"sus\",\"susp\"],\"application/vnd.svd\":[\"svd\"],\"application/vnd.symbian.install\":[\"sis\",\"sisx\"],\"application/vnd.syncml+xml\":[\"xsm\"],\"application/vnd.syncml.dm+wbxml\":[\"bdm\"],\"application/vnd.syncml.dm+xml\":[\"xdm\"],\"application/vnd.syncml.dmddf+xml\":[\"ddf\"],\"application/vnd.tao.intent-module-archive\":[\"tao\"],\"application/vnd.tcpdump.pcap\":[\"pcap\",\"cap\",\"dmp\"],\"application/vnd.tmobile-livetv\":[\"tmo\"],\"application/vnd.trid.tpt\":[\"tpt\"],\"application/vnd.triscape.mxs\":[\"mxs\"],\"application/vnd.trueapp\":[\"tra\"],\"application/vnd.ufdl\":[\"ufd\",\"ufdl\"],\"application/vnd.uiq.theme\":[\"utz\"],\"application/vnd.umajin\":[\"umj\"],\"application/vnd.unity\":[\"unityweb\"],\"application/vnd.uoml+xml\":[\"uoml\"],\"application/vnd.vcx\":[\"vcx\"],\"application/vnd.visio\":[\"vsd\",\"vst\",\"vss\",\"vsw\"],\"application/vnd.visionary\":[\"vis\"],\"application/vnd.vsf\":[\"vsf\"],\"application/vnd.wap.wbxml\":[\"wbxml\"],\"application/vnd.wap.wmlc\":[\"wmlc\"],\"application/vnd.wap.wmlscriptc\":[\"wmlsc\"],\"application/vnd.webturbo\":[\"wtb\"],\"application/vnd.wolfram.player\":[\"nbp\"],\"application/vnd.wordperfect\":[\"wpd\"],\"application/vnd.wqd\":[\"wqd\"],\"application/vnd.wt.stf\":[\"stf\"],\"application/vnd.xara\":[\"xar\"],\"application/vnd.xfdl\":[\"xfdl\"],\"application/vnd.yamaha.hv-dic\":[\"hvd\"],\"application/vnd.yamaha.hv-script\":[\"hvs\"],\"application/vnd.yamaha.hv-voice\":[\"hvp\"],\"application/vnd.yamaha.openscoreformat\":[\"osf\"],\"application/vnd.yamaha.openscoreformat.osfpvg+xml\":[\"osfpvg\"],\"application/vnd.yamaha.smaf-audio\":[\"saf\"],\"application/vnd.yamaha.smaf-phrase\":[\"spf\"],\"application/vnd.yellowriver-custom-menu\":[\"cmp\"],\"application/vnd.zul\":[\"zir\",\"zirz\"],\"application/vnd.zzazz.deck+xml\":[\"zaz\"],\"application/x-7z-compressed\":[\"7z\"],\"application/x-abiword\":[\"abw\"],\"application/x-ace-compressed\":[\"ace\"],\"application/x-apple-diskimage\":[\"*dmg\"],\"application/x-arj\":[\"arj\"],\"application/x-authorware-bin\":[\"aab\",\"x32\",\"u32\",\"vox\"],\"application/x-authorware-map\":[\"aam\"],\"application/x-authorware-seg\":[\"aas\"],\"application/x-bcpio\":[\"bcpio\"],\"application/x-bdoc\":[\"*bdoc\"],\"application/x-bittorrent\":[\"torrent\"],\"application/x-blorb\":[\"blb\",\"blorb\"],\"application/x-bzip\":[\"bz\"],\"application/x-bzip2\":[\"bz2\",\"boz\"],\"application/x-cbr\":[\"cbr\",\"cba\",\"cbt\",\"cbz\",\"cb7\"],\"application/x-cdlink\":[\"vcd\"],\"application/x-cfs-compressed\":[\"cfs\"],\"application/x-chat\":[\"chat\"],\"application/x-chess-pgn\":[\"pgn\"],\"application/x-chrome-extension\":[\"crx\"],\"application/x-cocoa\":[\"cco\"],\"application/x-conference\":[\"nsc\"],\"application/x-cpio\":[\"cpio\"],\"application/x-csh\":[\"csh\"],\"application/x-debian-package\":[\"*deb\",\"udeb\"],\"application/x-dgc-compressed\":[\"dgc\"],\"application/x-director\":[\"dir\",\"dcr\",\"dxr\",\"cst\",\"cct\",\"cxt\",\"w3d\",\"fgd\",\"swa\"],\"application/x-doom\":[\"wad\"],\"application/x-dtbncx+xml\":[\"ncx\"],\"application/x-dtbook+xml\":[\"dtb\"],\"application/x-dtbresource+xml\":[\"res\"],\"application/x-dvi\":[\"dvi\"],\"application/x-envoy\":[\"evy\"],\"application/x-eva\":[\"eva\"],\"application/x-font-bdf\":[\"bdf\"],\"application/x-font-ghostscript\":[\"gsf\"],\"application/x-font-linux-psf\":[\"psf\"],\"application/x-font-pcf\":[\"pcf\"],\"application/x-font-snf\":[\"snf\"],\"application/x-font-type1\":[\"pfa\",\"pfb\",\"pfm\",\"afm\"],\"application/x-freearc\":[\"arc\"],\"application/x-futuresplash\":[\"spl\"],\"application/x-gca-compressed\":[\"gca\"],\"application/x-glulx\":[\"ulx\"],\"application/x-gnumeric\":[\"gnumeric\"],\"application/x-gramps-xml\":[\"gramps\"],\"application/x-gtar\":[\"gtar\"],\"application/x-hdf\":[\"hdf\"],\"application/x-httpd-php\":[\"php\"],\"application/x-install-instructions\":[\"install\"],\"application/x-iso9660-image\":[\"*iso\"],\"application/x-iwork-keynote-sffkey\":[\"*key\"],\"application/x-iwork-numbers-sffnumbers\":[\"*numbers\"],\"application/x-iwork-pages-sffpages\":[\"*pages\"],\"application/x-java-archive-diff\":[\"jardiff\"],\"application/x-java-jnlp-file\":[\"jnlp\"],\"application/x-keepass2\":[\"kdbx\"],\"application/x-latex\":[\"latex\"],\"application/x-lua-bytecode\":[\"luac\"],\"application/x-lzh-compressed\":[\"lzh\",\"lha\"],\"application/x-makeself\":[\"run\"],\"application/x-mie\":[\"mie\"],\"application/x-mobipocket-ebook\":[\"prc\",\"mobi\"],\"application/x-ms-application\":[\"application\"],\"application/x-ms-shortcut\":[\"lnk\"],\"application/x-ms-wmd\":[\"wmd\"],\"application/x-ms-wmz\":[\"wmz\"],\"application/x-ms-xbap\":[\"xbap\"],\"application/x-msaccess\":[\"mdb\"],\"application/x-msbinder\":[\"obd\"],\"application/x-mscardfile\":[\"crd\"],\"application/x-msclip\":[\"clp\"],\"application/x-msdos-program\":[\"*exe\"],\"application/x-msdownload\":[\"*exe\",\"*dll\",\"com\",\"bat\",\"*msi\"],\"application/x-msmediaview\":[\"mvb\",\"m13\",\"m14\"],\"application/x-msmetafile\":[\"*wmf\",\"*wmz\",\"*emf\",\"emz\"],\"application/x-msmoney\":[\"mny\"],\"application/x-mspublisher\":[\"pub\"],\"application/x-msschedule\":[\"scd\"],\"application/x-msterminal\":[\"trm\"],\"application/x-mswrite\":[\"wri\"],\"application/x-netcdf\":[\"nc\",\"cdf\"],\"application/x-ns-proxy-autoconfig\":[\"pac\"],\"application/x-nzb\":[\"nzb\"],\"application/x-perl\":[\"pl\",\"pm\"],\"application/x-pilot\":[\"*prc\",\"*pdb\"],\"application/x-pkcs12\":[\"p12\",\"pfx\"],\"application/x-pkcs7-certificates\":[\"p7b\",\"spc\"],\"application/x-pkcs7-certreqresp\":[\"p7r\"],\"application/x-rar-compressed\":[\"*rar\"],\"application/x-redhat-package-manager\":[\"rpm\"],\"application/x-research-info-systems\":[\"ris\"],\"application/x-sea\":[\"sea\"],\"application/x-sh\":[\"sh\"],\"application/x-shar\":[\"shar\"],\"application/x-shockwave-flash\":[\"swf\"],\"application/x-silverlight-app\":[\"xap\"],\"application/x-sql\":[\"sql\"],\"application/x-stuffit\":[\"sit\"],\"application/x-stuffitx\":[\"sitx\"],\"application/x-subrip\":[\"srt\"],\"application/x-sv4cpio\":[\"sv4cpio\"],\"application/x-sv4crc\":[\"sv4crc\"],\"application/x-t3vm-image\":[\"t3\"],\"application/x-tads\":[\"gam\"],\"application/x-tar\":[\"tar\"],\"application/x-tcl\":[\"tcl\",\"tk\"],\"application/x-tex\":[\"tex\"],\"application/x-tex-tfm\":[\"tfm\"],\"application/x-texinfo\":[\"texinfo\",\"texi\"],\"application/x-tgif\":[\"*obj\"],\"application/x-ustar\":[\"ustar\"],\"application/x-virtualbox-hdd\":[\"hdd\"],\"application/x-virtualbox-ova\":[\"ova\"],\"application/x-virtualbox-ovf\":[\"ovf\"],\"application/x-virtualbox-vbox\":[\"vbox\"],\"application/x-virtualbox-vbox-extpack\":[\"vbox-extpack\"],\"application/x-virtualbox-vdi\":[\"vdi\"],\"application/x-virtualbox-vhd\":[\"vhd\"],\"application/x-virtualbox-vmdk\":[\"vmdk\"],\"application/x-wais-source\":[\"src\"],\"application/x-web-app-manifest+json\":[\"webapp\"],\"application/x-x509-ca-cert\":[\"der\",\"crt\",\"pem\"],\"application/x-xfig\":[\"fig\"],\"application/x-xliff+xml\":[\"*xlf\"],\"application/x-xpinstall\":[\"xpi\"],\"application/x-xz\":[\"xz\"],\"application/x-zmachine\":[\"z1\",\"z2\",\"z3\",\"z4\",\"z5\",\"z6\",\"z7\",\"z8\"],\"audio/vnd.dece.audio\":[\"uva\",\"uvva\"],\"audio/vnd.digital-winds\":[\"eol\"],\"audio/vnd.dra\":[\"dra\"],\"audio/vnd.dts\":[\"dts\"],\"audio/vnd.dts.hd\":[\"dtshd\"],\"audio/vnd.lucent.voice\":[\"lvp\"],\"audio/vnd.ms-playready.media.pya\":[\"pya\"],\"audio/vnd.nuera.ecelp4800\":[\"ecelp4800\"],\"audio/vnd.nuera.ecelp7470\":[\"ecelp7470\"],\"audio/vnd.nuera.ecelp9600\":[\"ecelp9600\"],\"audio/vnd.rip\":[\"rip\"],\"audio/x-aac\":[\"aac\"],\"audio/x-aiff\":[\"aif\",\"aiff\",\"aifc\"],\"audio/x-caf\":[\"caf\"],\"audio/x-flac\":[\"flac\"],\"audio/x-m4a\":[\"*m4a\"],\"audio/x-matroska\":[\"mka\"],\"audio/x-mpegurl\":[\"m3u\"],\"audio/x-ms-wax\":[\"wax\"],\"audio/x-ms-wma\":[\"wma\"],\"audio/x-pn-realaudio\":[\"ram\",\"ra\"],\"audio/x-pn-realaudio-plugin\":[\"rmp\"],\"audio/x-realaudio\":[\"*ra\"],\"audio/x-wav\":[\"*wav\"],\"chemical/x-cdx\":[\"cdx\"],\"chemical/x-cif\":[\"cif\"],\"chemical/x-cmdf\":[\"cmdf\"],\"chemical/x-cml\":[\"cml\"],\"chemical/x-csml\":[\"csml\"],\"chemical/x-xyz\":[\"xyz\"],\"image/prs.btif\":[\"btif\"],\"image/prs.pti\":[\"pti\"],\"image/vnd.adobe.photoshop\":[\"psd\"],\"image/vnd.airzip.accelerator.azv\":[\"azv\"],\"image/vnd.dece.graphic\":[\"uvi\",\"uvvi\",\"uvg\",\"uvvg\"],\"image/vnd.djvu\":[\"djvu\",\"djv\"],\"image/vnd.dvb.subtitle\":[\"*sub\"],\"image/vnd.dwg\":[\"dwg\"],\"image/vnd.dxf\":[\"dxf\"],\"image/vnd.fastbidsheet\":[\"fbs\"],\"image/vnd.fpx\":[\"fpx\"],\"image/vnd.fst\":[\"fst\"],\"image/vnd.fujixerox.edmics-mmr\":[\"mmr\"],\"image/vnd.fujixerox.edmics-rlc\":[\"rlc\"],\"image/vnd.microsoft.icon\":[\"ico\"],\"image/vnd.ms-dds\":[\"dds\"],\"image/vnd.ms-modi\":[\"mdi\"],\"image/vnd.ms-photo\":[\"wdp\"],\"image/vnd.net-fpx\":[\"npx\"],\"image/vnd.pco.b16\":[\"b16\"],\"image/vnd.tencent.tap\":[\"tap\"],\"image/vnd.valve.source.texture\":[\"vtf\"],\"image/vnd.wap.wbmp\":[\"wbmp\"],\"image/vnd.xiff\":[\"xif\"],\"image/vnd.zbrush.pcx\":[\"pcx\"],\"image/x-3ds\":[\"3ds\"],\"image/x-cmu-raster\":[\"ras\"],\"image/x-cmx\":[\"cmx\"],\"image/x-freehand\":[\"fh\",\"fhc\",\"fh4\",\"fh5\",\"fh7\"],\"image/x-icon\":[\"*ico\"],\"image/x-jng\":[\"jng\"],\"image/x-mrsid-image\":[\"sid\"],\"image/x-ms-bmp\":[\"*bmp\"],\"image/x-pcx\":[\"*pcx\"],\"image/x-pict\":[\"pic\",\"pct\"],\"image/x-portable-anymap\":[\"pnm\"],\"image/x-portable-bitmap\":[\"pbm\"],\"image/x-portable-graymap\":[\"pgm\"],\"image/x-portable-pixmap\":[\"ppm\"],\"image/x-rgb\":[\"rgb\"],\"image/x-tga\":[\"tga\"],\"image/x-xbitmap\":[\"xbm\"],\"image/x-xpixmap\":[\"xpm\"],\"image/x-xwindowdump\":[\"xwd\"],\"message/vnd.wfa.wsc\":[\"wsc\"],\"model/vnd.collada+xml\":[\"dae\"],\"model/vnd.dwf\":[\"dwf\"],\"model/vnd.gdl\":[\"gdl\"],\"model/vnd.gtw\":[\"gtw\"],\"model/vnd.mts\":[\"mts\"],\"model/vnd.opengex\":[\"ogex\"],\"model/vnd.parasolid.transmit.binary\":[\"x_b\"],\"model/vnd.parasolid.transmit.text\":[\"x_t\"],\"model/vnd.sap.vds\":[\"vds\"],\"model/vnd.usdz+zip\":[\"usdz\"],\"model/vnd.valve.source.compiled-map\":[\"bsp\"],\"model/vnd.vtu\":[\"vtu\"],\"text/prs.lines.tag\":[\"dsc\"],\"text/vnd.curl\":[\"curl\"],\"text/vnd.curl.dcurl\":[\"dcurl\"],\"text/vnd.curl.mcurl\":[\"mcurl\"],\"text/vnd.curl.scurl\":[\"scurl\"],\"text/vnd.dvb.subtitle\":[\"sub\"],\"text/vnd.fly\":[\"fly\"],\"text/vnd.fmi.flexstor\":[\"flx\"],\"text/vnd.graphviz\":[\"gv\"],\"text/vnd.in3d.3dml\":[\"3dml\"],\"text/vnd.in3d.spot\":[\"spot\"],\"text/vnd.sun.j2me.app-descriptor\":[\"jad\"],\"text/vnd.wap.wml\":[\"wml\"],\"text/vnd.wap.wmlscript\":[\"wmls\"],\"text/x-asm\":[\"s\",\"asm\"],\"text/x-c\":[\"c\",\"cc\",\"cxx\",\"cpp\",\"h\",\"hh\",\"dic\"],\"text/x-component\":[\"htc\"],\"text/x-fortran\":[\"f\",\"for\",\"f77\",\"f90\"],\"text/x-handlebars-template\":[\"hbs\"],\"text/x-java-source\":[\"java\"],\"text/x-lua\":[\"lua\"],\"text/x-markdown\":[\"mkd\"],\"text/x-nfo\":[\"nfo\"],\"text/x-opml\":[\"opml\"],\"text/x-org\":[\"*org\"],\"text/x-pascal\":[\"p\",\"pas\"],\"text/x-processing\":[\"pde\"],\"text/x-sass\":[\"sass\"],\"text/x-scss\":[\"scss\"],\"text/x-setext\":[\"etx\"],\"text/x-sfv\":[\"sfv\"],\"text/x-suse-ymp\":[\"ymp\"],\"text/x-uuencode\":[\"uu\"],\"text/x-vcalendar\":[\"vcs\"],\"text/x-vcard\":[\"vcf\"],\"video/vnd.dece.hd\":[\"uvh\",\"uvvh\"],\"video/vnd.dece.mobile\":[\"uvm\",\"uvvm\"],\"video/vnd.dece.pd\":[\"uvp\",\"uvvp\"],\"video/vnd.dece.sd\":[\"uvs\",\"uvvs\"],\"video/vnd.dece.video\":[\"uvv\",\"uvvv\"],\"video/vnd.dvb.file\":[\"dvb\"],\"video/vnd.fvt\":[\"fvt\"],\"video/vnd.mpegurl\":[\"mxu\",\"m4u\"],\"video/vnd.ms-playready.media.pyv\":[\"pyv\"],\"video/vnd.uvvu.mp4\":[\"uvu\",\"uvvu\"],\"video/vnd.vivo\":[\"viv\"],\"video/x-f4v\":[\"f4v\"],\"video/x-fli\":[\"fli\"],\"video/x-flv\":[\"flv\"],\"video/x-m4v\":[\"m4v\"],\"video/x-matroska\":[\"mkv\",\"mk3d\",\"mks\"],\"video/x-mng\":[\"mng\"],\"video/x-ms-asf\":[\"asf\",\"asx\"],\"video/x-ms-vob\":[\"vob\"],\"video/x-ms-wm\":[\"wm\"],\"video/x-ms-wmv\":[\"wmv\"],\"video/x-ms-wmx\":[\"wmx\"],\"video/x-ms-wvx\":[\"wvx\"],\"video/x-msvideo\":[\"avi\"],\"video/x-sgi-movie\":[\"movie\"],\"video/x-smv\":[\"smv\"],\"x-conference/x-cooltalk\":[\"ice\"]};", "'use strict';\n\nlet Mime = require('./Mime');\nmodule.exports = new Mime(require('./types/standard'), require('./types/other'));\n", "import { IDisposable } from '@lumino/disposable';\nimport { IRenderMime } from '@jupyterlab/rendermime-interfaces';\nimport { PageConfig } from '@jupyterlab/coreutils';\nimport { Token } from '@lumino/coreutils';\nimport mime from 'mime';\n\n/**\n * Commonly-used mimetypes\n */\nexport namespace MIME {\n export const JSON = 'application/json';\n export const PLAIN_TEXT = 'text/plain';\n export const OCTET_STREAM = 'octet/stream';\n}\n\n/**\n * A namespace for file constructs.\n */\nexport namespace FILE {\n /**\n * Build-time configured file types.\n */\n const TYPES: Record<string, Partial<IRenderMime.IFileType>> = JSON.parse(\n PageConfig.getOption('fileTypes') || '{}',\n );\n\n /**\n * Get a mimetype (or fallback).\n */\n export function getType(ext: string, defaultType: string | null = null): string {\n ext = ext.toLowerCase();\n for (const fileType of Object.values(TYPES)) {\n for (const fileExt of fileType.extensions || []) {\n if (fileExt === ext && fileType.mimeTypes && fileType.mimeTypes.length) {\n return fileType.mimeTypes[0];\n }\n }\n }\n\n return mime.getType(ext) || defaultType || MIME.OCTET_STREAM;\n }\n\n /**\n * Determine whether the given extension matches a given fileFormat.\n */\n export function hasFormat(\n ext: string,\n fileFormat: 'base64' | 'text' | 'json',\n ): boolean {\n ext = ext.toLowerCase();\n for (const fileType of Object.values(TYPES)) {\n if (fileType.fileFormat !== fileFormat) {\n continue;\n }\n for (const fileExt of fileType.extensions || []) {\n if (fileExt === ext) {\n return true;\n }\n }\n }\n return false;\n }\n}\n\n/**\n * The token for the BroadcastChannel broadcaster.\n */\nexport const IBroadcastChannelWrapper = new Token<IBroadcastChannelWrapper>(\n '@jupyterlite/contents:IBroadcastChannelWrapper',\n);\n\nexport interface IBroadcastChannelWrapper extends IDisposable {\n enable(): void;\n disable(): void;\n enabled: boolean;\n}\n", "import { PageConfig, URLExt } from '@jupyterlab/coreutils';\n\nimport { Contents, Drive, ServerConnection } from '@jupyterlab/services';\n\nimport { INotebookContent } from '@jupyterlab/nbformat';\n\nimport { PathExt } from '@jupyterlab/coreutils';\n\nimport { PromiseDelegate } from '@lumino/coreutils';\n\nimport { ISignal, Signal } from '@lumino/signaling';\n\nimport { FILE, MIME } from './tokens';\n\nimport type localforage from 'localforage';\n\ntype IModel = Contents.IModel;\n\n/**\n * The name of the local storage.\n */\nconst DEFAULT_STORAGE_NAME = 'JupyterLite Storage';\n\n/**\n * The name of the drive.\n */\nexport const DRIVE_NAME = 'BrowserStorage';\n\n/**\n * The number of checkpoints to save.\n */\nconst N_CHECKPOINTS = 5;\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8');\n\n/**\n * A custom drive to store files in the browser storage.\n */\nexport class BrowserStorageDrive implements Contents.IDrive {\n /**\n * Construct a new localForage-powered contents provider\n */\n constructor(options: BrowserStorageDrive.IOptions) {\n this._localforage = options.localforage;\n this._storageName = options.storageName || DEFAULT_STORAGE_NAME;\n this._storageDrivers = options.storageDrivers || null;\n this._serverSettings = options.serverSettings ?? ServerConnection.makeSettings();\n this._ready = new PromiseDelegate();\n this.initialize().catch(console.warn);\n }\n\n /**\n * Dispose the drive.\n */\n dispose(): void {\n if (this.isDisposed) {\n return;\n }\n this._isDisposed = true;\n Signal.clearData(this);\n }\n\n /**\n * Whether the drive is disposed.\n */\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n /**\n * The name of the drive.\n */\n get name(): string {\n return DRIVE_NAME;\n }\n\n /**\n * The server settings of the drive.\n */\n get serverSettings(): ServerConnection.ISettings {\n return this._serverSettings;\n }\n\n /**\n * Signal emitted when a file operation takes place.\n */\n get fileChanged(): ISignal<Contents.IDrive, Contents.IChangedArgs> {\n return this._fileChanged;\n }\n\n /**\n * Get the download URL\n */\n async getDownloadUrl(path: string): Promise<string> {\n throw new Error('Method not implemented.');\n }\n\n /**\n * Finish any initialization after server has started and all extensions are applied.\n *\n * TODO: keep private?\n */\n async initialize() {\n await this.initStorage();\n this._ready.resolve(void 0);\n }\n\n /**\n * Initialize all storage instances\n */\n protected async initStorage(): Promise<void> {\n this._storage = this.createDefaultStorage();\n this._counters = this.createDefaultCounters();\n this._checkpoints = this.createDefaultCheckpoints();\n }\n\n /**\n * A promise that resolves once all storage is fully initialized.\n */\n get ready(): Promise<void> {\n return this._ready.promise;\n }\n\n /**\n * A lazy reference to the underlying storage.\n */\n protected get storage(): Promise<LocalForage> {\n return this.ready.then(() => this._storage as LocalForage);\n }\n\n /**\n * A lazy reference to the underlying counters.\n */\n protected get counters(): Promise<LocalForage> {\n return this.ready.then(() => this._counters as LocalForage);\n }\n\n /**\n * A lazy reference to the underlying checkpoints.\n */\n protected get checkpoints(): Promise<LocalForage> {\n return this.ready.then(() => this._checkpoints as LocalForage);\n }\n\n /**\n * Get default options for localForage instances\n */\n protected get defaultStorageOptions(): LocalForageOptions {\n const driver =\n this._storageDrivers && this._storageDrivers.length ? this._storageDrivers : null;\n return {\n version: 1,\n name: this._storageName,\n ...(driver ? { driver } : {}),\n };\n }\n\n /**\n * Initialize the default storage for contents.\n */\n protected createDefaultStorage(): LocalForage {\n return this._localforage.createInstance({\n description: 'Offline Storage for Notebooks and Files',\n storeName: 'files',\n ...this.defaultStorageOptions,\n });\n }\n\n /**\n * Initialize the default storage for counting file suffixes.\n */\n protected createDefaultCounters(): LocalForage {\n return this._localforage.createInstance({\n description: 'Store the current file suffix counters',\n storeName: 'counters',\n ...this.defaultStorageOptions,\n });\n }\n\n /**\n * Create the default checkpoint storage.\n */\n protected createDefaultCheckpoints(): LocalForage {\n return this._localforage.createInstance({\n description: 'Offline Storage for Checkpoints',\n storeName: 'checkpoints',\n ...this.defaultStorageOptions,\n });\n }\n\n /**\n * Create a new untitled file or directory in the specified directory path.\n *\n * @param options: The options used to create the file.\n *\n * @returns A promise which resolves with the created file content when the file is created.\n */\n async newUntitled(options?: Contents.ICreateOptions): Promise<IModel> {\n const path = options?.path ?? '';\n const type = options?.type ?? 'notebook';\n const created = new Date().toISOString();\n\n let dirname = PathExt.dirname(path);\n const basename = PathExt.basename(path);\n const extname = PathExt.extname(path);\n const item = await this.get(dirname);\n\n // handle the case of \"Save As\", where the path points to the new file\n // to create, e.g. subfolder/example-copy.ipynb\n let name = '';\n if (path && !extname && item) {\n // directory\n dirname = `${path}/`;\n name = '';\n } else if (dirname && basename) {\n // file in a subfolder\n dirname = `${dirname}/`;\n name = basename;\n } else {\n // file at the top level\n dirname = '';\n name = path;\n }\n\n let file: IModel;\n switch (type) {\n case 'directory': {\n const counter = await this._incrementCounter('directory');\n name = `Untitled Folder${counter || ''}`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format: 'json',\n mimetype: '',\n content: null,\n size: 0,\n writable: true,\n type: 'directory',\n };\n break;\n }\n case 'notebook': {\n const counter = await this._incrementCounter('notebook');\n name = name || `Untitled${counter || ''}.ipynb`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format: 'json',\n mimetype: MIME.JSON,\n content: Private.EMPTY_NB,\n size: encoder.encode(JSON.stringify(Private.EMPTY_NB)).length,\n writable: true,\n type: 'notebook',\n };\n break;\n }\n default: {\n let ext = options?.ext ?? '.txt';\n if (!ext.startsWith('.')) {\n ext = `.${ext}`;\n }\n const counter = await this._incrementCounter('file');\n const mimetype = FILE.getType(ext) || MIME.OCTET_STREAM;\n\n let format: Contents.FileFormat;\n if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {\n format = 'text';\n } else if (ext.indexOf('json') !== -1 || ext.indexOf('ipynb') !== -1) {\n format = 'json';\n } else {\n format = 'base64';\n }\n\n name = name || `untitled${counter || ''}${ext}`;\n file = {\n name,\n path: `${dirname}${name}`,\n last_modified: created,\n created,\n format,\n mimetype,\n content: '',\n size: 0,\n writable: true,\n type: 'file',\n };\n break;\n }\n }\n\n const key = file.path;\n await (await this.storage).setItem(key, file);\n this._fileChanged.emit({\n type: 'new',\n oldValue: null,\n newValue: file,\n });\n return file;\n }\n\n /**\n * Copy a file into a given directory.\n *\n * @param path - The original file path.\n * @param toDir - The destination directory path.\n *\n * @returns A promise which resolves with the new contents model when the\n * file is copied.\n *\n * #### Notes\n * The server will select the name of the copied file.\n */\n async copy(path: string, toDir: string): Promise<IModel> {\n let name = PathExt.basename(path);\n toDir = toDir === '' ? '' : `${PathExt.removeSlash(toDir)}/`;\n // TODO: better handle naming collisions with existing files\n while (await this.get(`${toDir}${name}`, { content: true })) {\n const ext = PathExt.extname(name);\n const base = name.replace(ext, '');\n name = `${base} (copy)${ext}`;\n }\n const toPath = `${toDir}${name}`;\n let item = await this.get(path, { content: true });\n if (!item) {\n throw Error(`Could not find file with path ${path}`);\n }\n item = {\n ...item,\n name,\n path: toPath,\n };\n await (await this.storage).setItem(toPath, item);\n\n this._fileChanged.emit({\n type: 'new',\n oldValue: null,\n newValue: item,\n });\n\n return item;\n }\n\n /**\n * Get a file or directory.\n *\n * @param path: The path to the file.\n * @param options: The options used to fetch the file.\n *\n * @returns A promise which resolves with the file content.\n */\n async get(path: string, options?: Contents.IFetchOptions): Promise<IModel> {\n // remove leading slash\n path = decodeURIComponent(path.replace(/^\\//, ''));\n\n if (path === '') {\n const folder = await this._getFolder(path);\n if (folder === null) {\n throw Error(`Could not find file with path ${path}`);\n }\n return folder;\n }\n\n const storage = await this.storage;\n const item = await storage.getItem(path);\n const serverItem = await this._getServerContents(path, options);\n\n const model = (item || serverItem) as IModel | null;\n\n if (!model) {\n throw Error(`Could not find content with path ${path}`);\n }\n\n if (!options?.content) {\n return {\n size: 0,\n ...model,\n content: null,\n };\n }\n\n // for directories, find all files with the path as the prefix\n if (model.type === 'directory') {\n const contentMap = new Map<string, IModel>();\n await storage.iterate<IModel, void>((file, key) => {\n // use an additional slash to not include the directory itself\n if (key === `${path}/${file.name}`) {\n contentMap.set(file.name, file);\n }\n });\n\n const serverContents: IModel[] = serverItem\n ? serverItem.content\n : Array.from((await this._getServerDirectory(path)).values());\n for (const file of serverContents) {\n if (!contentMap.has(file.name)) {\n contentMap.set(file.name, file);\n }\n }\n\n const content = [...contentMap.values()];\n\n return {\n name: PathExt.basename(path),\n path,\n last_modified: model.last_modified,\n created: model.created,\n format: 'json',\n mimetype: MIME.JSON,\n content,\n size: 0,\n writable: true,\n type: 'directory',\n };\n }\n return model;\n }\n\n /**\n * Rename a file or directory.\n *\n * @param oldLocalPath - The original file path.\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with the new file content model when the file is renamed.\n */\n async rename(oldLocalPath: string, newLocalPath: string): Promise<IModel> {\n const path = decodeURIComponent(oldLocalPath);\n const file = await this.get(path, { content: true });\n if (!file) {\n throw Error(`Could not find file with path ${path}`);\n }\n const modified = new Date().toISOString();\n const name = PathExt.basename(newLocalPath);\n const newFile = {\n ...file,\n name,\n path: newLocalPath,\n last_modified: modified,\n };\n const storage = await this.storage;\n await storage.setItem(newLocalPath, newFile);\n // remove the old file\n await storage.removeItem(path);\n // remove the corresponding checkpoint\n await (await this.checkpoints).removeItem(path);\n // if a directory, recurse through all children\n if (file.type === 'directory') {\n let child: IModel;\n for (child of file.content) {\n await this.rename(\n URLExt.join(oldLocalPath, child.name),\n URLExt.join(newLocalPath, child.name),\n );\n }\n }\n\n this._fileChanged.emit({\n type: 'rename',\n oldValue: { path: oldLocalPath },\n newValue: newFile,\n });\n\n return newFile;\n }\n\n /**\n * Save a file.\n *\n * @param path - The desired file path.\n * @param options - Optional overrides to the model.\n *\n * @returns A promise which resolves with the file content model when the file is saved.\n */\n async save(path: string, options: Partial<IModel> = {}): Promise<IModel> {\n path = decodeURIComponent(path);\n\n // process the file if coming from an upload\n const ext = PathExt.extname(options.name ?? '');\n const chunk = options.chunk;\n\n // retrieve the content if it is a later chunk or the last one\n // the new content will then be appended to the existing one\n const appendChunk = chunk ? chunk > 1 || chunk === -1 : false;\n let item: IModel | null = await this.get(path, { content: appendChunk });\n\n if (!item) {\n item = await this.newUntitled({ path, ext, type: 'file' });\n }\n\n if (!item) {\n throw Error(`Could not find file with path ${path}`);\n }\n\n // keep a reference to the original content\n const originalContent = item.content;\n\n const modified = new Date().toISOString();\n // override with the new values\n item = {\n ...item,\n ...options,\n last_modified: modified,\n };\n\n if (options.content && options.format === 'base64') {\n const lastChunk = chunk ? chunk === -1 : true;\n\n const contentBinaryString = this._handleUploadChunk(\n options.content,\n originalContent,\n appendChunk,\n );\n\n if (ext === '.ipynb') {\n const content = lastChunk\n ? JSON.parse(decoder.decode(this._binaryStringToBytes(contentBinaryString)))\n : contentBinaryString;\n item = {\n ...item,\n content,\n format: 'json',\n type: 'notebook',\n size: contentBinaryString.length,\n };\n } else if (FILE.hasFormat(ext, 'json')) {\n const content = lastChunk\n ? JSON.parse(decoder.decode(this._binaryStringToBytes(contentBinaryString)))\n : contentBinaryString;\n item = {\n ...item,\n content,\n format: 'json',\n type: 'file',\n size: contentBinaryString.length,\n };\n } else if (FILE.hasFormat(ext, 'text')) {\n const content = lastChunk\n ? decoder.decode(this._binaryStringToBytes(contentBinaryString))\n : contentBinaryString;\n item = {\n ...item,\n content,\n format: 'text',\n type: 'file',\n size: contentBinaryString.length,\n };\n } else {\n const content = lastChunk ? btoa(contentBinaryString) : contentBinaryString;\n item = {\n ...item,\n content,\n format: 'base64',\n type: 'file',\n size: contentBinaryString.length,\n };\n }\n }\n\n // fixup content sizes if necessary\n if (item.content) {\n switch (options.format) {\n case 'json': {\n item = { ...item, size: encoder.encode(JSON.stringify(item.content)).length };\n break;\n }\n case 'text': {\n item = { ...item, size: encoder.encode(item.content).length };\n break;\n }\n // base64 save was already handled above\n case 'base64': {\n break;\n }\n default: {\n item = { ...item, size: 0 };\n break;\n }\n }\n } else {\n item = { ...item, size: 0 };\n }\n\n await (await this.storage).setItem(path, item);\n\n this._fileChanged.emit({\n type: 'save',\n oldValue: null,\n newValue: item,\n });\n\n return item;\n }\n\n /**\n * Delete a file from browser storage.\n *\n * Has no effect on server-backed files, which will re-appear with their\n * original timestamp.\n *\n * @param path - The path to the file.\n */\n async delete(path: string): Promise<void> {\n path = decodeURIComponent(path);\n const slashed = `${path}/`;\n const toDelete = (await (await this.storage).keys()).filter(\n (key) => key === path || key.startsWith(slashed),\n );\n await Promise.all(toDelete.map(this.forgetPath, this));\n this._fileChanged.emit({\n type: 'delete',\n oldValue: { path },\n newValue: null,\n });\n }\n\n /**\n * Remove the localForage and checkpoints for a path.\n *\n * @param path - The path to the file\n */\n protected async forgetPath(path: string): Promise<void> {\n await Promise.all([\n (await this.storage).removeItem(path),\n (await this.checkpoints).removeItem(path),\n ]);\n }\n\n /**\n * Create a checkpoint for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with the new checkpoint model when the\n * checkpoint is created.\n */\n async createCheckpoint(path: string): Promise<Contents.ICheckpointModel> {\n const checkpoints = await this.checkpoints;\n path = decodeURIComponent(path);\n const item = await this.get(path, { content: true });\n if (!item) {\n throw Error(`Could not find file with path ${path}`);\n }\n const copies = (((await checkpoints.getItem(path)) as IModel[]) ?? []).filter(\n Boolean,\n );\n copies.push(item);\n // keep only a certain amount of checkpoints per file\n if (copies.length > N_CHECKPOINTS) {\n copies.splice(0, copies.length - N_CHECKPOINTS);\n }\n await checkpoints.setItem(path, copies);\n const id = `${copies.length - 1}`;\n return { id, last_modified: (item as IModel).last_modified };\n }\n\n /**\n * List available checkpoints for a file.\n *\n * @param path - The path of the file.\n *\n * @returns A promise which resolves with a list of checkpoint models for\n * the file.\n */\n async listCheckpoints(path: string): Promise<Contents.ICheckpointModel[]> {\n const copies: IModel[] = (await (await this.checkpoints).getItem(path)) || [];\n return copies.filter(Boolean).map(this.normalizeCheckpoint, this);\n }\n\n protected normalizeCheckpoint(model: IModel, id: number): Contents.ICheckpointModel {\n return { id: id.toString(), last_modified: model.last_modified };\n }\n\n /**\n * Restore a file to a known checkpoint state.\n *\n * @param path - The path of the file.\n * @param checkpointID - The id of the checkpoint to restore.\n *\n * @returns A promise which resolves when the checkpoint is restored.\n */\n async restoreCheckpoint(path: string, checkpointID: string): Promise<void> {\n path = decodeURIComponent(path);\n const copies = ((await (await this.checkpoints).getItem(path)) || []) as IModel[];\n const id = parseInt(checkpointID);\n const item = copies[id];\n await (await this.storage).setItem(path, item);\n }\n\n /**\n * Delete a checkpoint for a file.\n *\n * @param path - The path of the file.\n * @param checkpointID - The id of the checkpoint to delete.\n *\n * @returns A promise which resolves when the checkpoint is deleted.\n */\n async deleteCheckpoint(path: string, checkpointID: string): Promise<void> {\n path = decodeURIComponent(path);\n const copies = ((await (await this.checkpoints).getItem(path)) || []) as IModel[];\n const id = parseInt(checkpointID);\n copies.splice(id, 1);\n await (await this.checkpoints).setItem(path, copies);\n }\n\n /**\n * Handle an upload chunk for a file.\n * each chunk is base64 encoded, so we need to decode it and append it to the\n * original content.\n * @param newContent the new content to process, base64 encoded\n * @param originalContent the original content, must be null or a binary string if chunked is true\n * @param appendChunk whether the chunk should be appended to the originalContent\n *\n *\n * @returns the decoded binary string, appended to the original content if requested\n * /\n */\n private _handleUploadChunk(\n newContent: string,\n originalContent: any,\n appendChunk: boolean,\n ): string {\n const newContentBinaryString = atob(newContent);\n const contentBinaryString = appendChunk\n ? originalContent + newContentBinaryString\n : newContentBinaryString;\n return contentBinaryString;\n }\n\n /**\n * Convert a binary string to an Uint8Array\n * @param binaryString the binary string\n * @returns the bytes of the binary string\n */\n private _binaryStringToBytes(binaryString: string): Uint8Array {\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n }\n\n /**\n * retrieve the contents for this path from the union of local storage and\n * `api/contents/{path}/all.json`.\n *\n * @param path - The contents path to retrieve\n *\n * @returns A promise which resolves with a Map of contents, keyed by local file name\n */\n private async _getFolder(path: string): Promise<IModel | null> {\n const content = new Map<string, IModel>();\n const storage = await this.storage;\n await storage.iterate<IModel, void>((file, key) => {\n if (key.includes('/')) {\n return;\n }\n content.set(file.path, file);\n });\n\n // layer in contents that don't have local overwrites\n for (const file of (await this._getServerDirectory(path)).values()) {\n if (!content.has(file.path)) {\n content.set(file.path, file);\n }\n }\n\n if (path && content.size === 0) {\n return null;\n }\n\n return {\n name: '',\n path,\n last_modified: new Date(0).toISOString(),\n created: new Date(0).toISOString(),\n format: 'json',\n mimetype: MIME.JSON,\n content: Array.from(content.values()),\n size: 0,\n writable: true,\n type: 'directory',\n };\n }\n\n /**\n * Attempt to recover the model from `{:path}/__all__.json` file, fall back to\n * deriving the model (including content) off the file in `/files/`. Otherwise\n * return `null`.\n */\n private async _getServerContents(\n path: string,\n options?: Contents.IFetchOptions,\n ): Promise<IModel | null> {\n const name = PathExt.basename(path);\n const parentContents = await this._getServerDirectory(URLExt.join(path, '..'));\n let model = parentContents.get(name);\n if (!model) {\n return null;\n }\n model = model || {\n name,\n path,\n last_modified: new Date(0).toISOString(),\n created: new Date(0).toISOString(),\n format: 'text',\n mimetype: MIME.PLAIN_TEXT,\n type: 'file',\n writable: true,\n size: 0,\n content: '',\n };\n\n if (options?.content) {\n if (model.type === 'directory') {\n const serverContents = await this._getServerDirectory(path);\n model = { ...model, content: Array.from(serverContents.values()) };\n } else {\n const fileUrl = URLExt.join(PageConfig.getBaseUrl(), 'files', path);\n const response = await fetch(fileUrl);\n if (!response.ok) {\n return null;\n }\n const mimetype = model.mimetype || response.headers.get('Content-Type');\n const ext = PathExt.extname(name);\n\n if (\n model.type === 'notebook' ||\n FILE.hasFormat(ext, 'json') ||\n mimetype?.indexOf('json') !== -1 ||\n path.match(/\\.(ipynb|[^/]*json[^/]*)$/)\n ) {\n const contentText = await response.text();\n model = {\n ...model,\n content: JSON.parse(contentText),\n format: 'json',\n mimetype: model.mimetype || MIME.JSON,\n size: encoder.encode(contentText).length,\n };\n } else if (FILE.hasFormat(ext, 'text') || mimetype.indexOf('text') !== -1) {\n const contentText = await response.text();\n model = {\n ...model,\n content: contentText,\n format: 'text',\n mimetype: mimetype || MIME.PLAIN_TEXT,\n size: encoder.encode(contentText).length,\n };\n } else {\n const contentBuffer = await response.arrayBuffer();\n const contentBytes = new Uint8Array(contentBuffer);\n model = {\n ...model,\n content: btoa(contentBytes.reduce(this.reduceBytesToString, '')),\n format: 'base64',\n mimetype: mimetype || MIME.OCTET_STREAM,\n size: contentBytes.length,\n };\n }\n }\n }\n\n return model;\n }\n\n /**\n * A reducer for turning arbitrary binary into a string\n */\n protected reduceBytesToString = (data: string, byte: number): string => {\n return data + String.fromCharCode(byte);\n };\n\n /**\n * retrieve the contents for this path from `__index__.json` in the appropriate\n * folder.\n *\n * @param newLocalPath - The new file path.\n *\n * @returns A promise which resolves with a Map of contents, keyed by local file name\n */\n private async _getServerDirectory(path: string): Promise<Map<string, IModel>> {\n const content = this._serverContents.get(path) || new Map();\n\n if (!this._serverContents.has(path)) {\n const apiURL = URLExt.join(\n PageConfig.getBaseUrl(),\n 'api/contents',\n path,\n 'all.json',\n );\n\n try {\n const response = await fetch(apiURL);\n const json = JSON.parse(await response.text());\n for (const file of json['content'] as IModel[]) {\n content.set(file.name, file);\n }\n } catch (err) {\n console.warn(\n `don't worry, about ${err}... nothing's broken. If there had been a\n file at ${apiURL}, you might see some more files.`,\n );\n }\n this._serverContents.set(path, content);\n }\n\n return content;\n }\n\n /**\n * Increment the counter for a given file type.\n * Used to avoid collisions when creating new untitled files.\n *\n * @param type The file type to increment the counter for.\n */\n private async _incrementCounter(type: Contents.ContentType): Promise<number> {\n const counters = await this.counters;\n const current = ((await counters.getItem(type)) as number) ?? -1;\n const counter = current + 1;\n await counters.setItem(type, counter);\n return counter;\n }\n\n private _serverContents = new Map<string, Map<string, IModel>>();\n private _isDisposed = false;\n private _fileChanged = new Signal<Contents.IDrive, Contents.IChangedArgs>(this);\n private _storageName: string = DEFAULT_STORAGE_NAME;\n private _storageDrivers: string[] | null = null;\n private _ready: PromiseDelegate<void>;\n private _storage: LocalForage | undefined;\n private _counters: LocalForage | undefined;\n private _checkpoints: LocalForage | undefined;\n private _localforage: typeof localforage;\n private _serverSettings: ServerConnection.ISettings;\n}\n\n/**\n * A namespace for contents information.\n */\nexport namespace BrowserStorageDrive {\n /**\n * The options used to create a BrowserStorageDrive.\n */\n export interface IOptions extends Drive.IOptions {\n /**\n * The name of the storage instance on e.g. IndexedDB, localStorage\n */\n storageName?: string | null;\n\n /**\n * The drivers to use for storage.\n */\n storageDrivers?: string[] | null;\n\n /**\n * The localForage instance to use.\n */\n localforage: typeof localforage;\n }\n}\n\n/**\n * A namespace for private data.\n */\nnamespace Private {\n /**\n * The content for an empty notebook.\n */\n export const EMPTY_NB: INotebookContent = {\n metadata: {\n orig_nbformat: 4,\n },\n nbformat_minor: 5,\n nbformat: 4,\n cells: [],\n };\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n// Types and implementation inspired from https://github.com/jvilk/BrowserFS\n// LICENSE: https://github.com/jvilk/BrowserFS/blob/8977a704ea469d05daf857e4818bef1f4f498326/LICENSE\n// And from https://github.com/gzuidhof/starboard-notebook\n\n// LICENSE: https://github.com/gzuidhof/starboard-notebook/blob/cd8d3fc30af4bd29cdd8f6b8c207df8138f5d5dd/LICENSE\n\n/**\n * Types for Emscripten primitives.\n *\n * Ideally, much more of these would be taken from `@types/emscripten`.\n */\n\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"../../../node_modules/@types/emscripten/index.d.ts\" />\ntype EmscriptenFS = typeof FS;\n\nexport const DIR_MODE = 16895; // 040777\nexport const FILE_MODE = 33206; // 100666\nexport const SEEK_CUR = 1;\nexport const SEEK_END = 2;\n\nexport interface IStats {\n dev: number;\n ino?: number;\n mode?: number;\n nlink: number;\n uid: number;\n gid: number;\n rdev: number;\n size: number;\n blksize: number;\n blocks: number;\n atime: Date | string;\n mtime: Date | string;\n ctime: Date | string;\n timestamp?: number;\n}\n\nexport interface IEmscriptenFSNode {\n id: number;\n name: string;\n mode: number;\n parent: IEmscriptenFSNode;\n mount: { opts: { root: string } };\n stream_ops: IEmscriptenStreamOps;\n node_ops: IEmscriptenNodeOps;\n timestamp: number;\n}\n\nexport interface IEmscriptenStream {\n node: IEmscriptenFSNode;\n nfd: any;\n flags: string;\n position: number;\n}\n\nexport function instanceOfStream(\n nodeOrStream: IEmscriptenFSNode | IEmscriptenStream,\n): nodeOrStream is IEmscriptenStream {\n return 'node' in nodeOrStream;\n}\n\nexport interface IEmscriptenNodeOps {\n getattr(node: IEmscriptenFSNode | IEmscriptenStream): IStats;\n setattr(node: IEmscriptenFSNode | IEmscriptenStream, attr: IStats): void;\n lookup(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n name: string,\n ): IEmscriptenFSNode;\n mknod(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n name: string,\n mode: number,\n dev: number,\n ): IEmscriptenFSNode;\n rename(\n oldNode: IEmscriptenFSNode | IEmscriptenStream,\n newDir: IEmscriptenFSNode | IEmscriptenStream,\n newName: string,\n ): void;\n unlink(parent: IEmscriptenFSNode | IEmscriptenStream, name: string): void;\n rmdir(parent: IEmscriptenFSNode | IEmscriptenStream, name: string): void;\n readdir(node: IEmscriptenFSNode | IEmscriptenStream): string[];\n symlink(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n newName: string,\n oldPath: string,\n ): void;\n readlink(node: IEmscriptenFSNode | IEmscriptenStream): string;\n}\n\nexport interface IEmscriptenStreamOps {\n open(stream: IEmscriptenStream): void;\n close(stream: IEmscriptenStream): void;\n read(\n stream: IEmscriptenStream,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): number;\n write(\n stream: IEmscriptenStream,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): number;\n llseek(stream: IEmscriptenStream, offset: number, whence: number): number;\n}\n\n/**\n * The emscripten filesystem module API.\n */\nexport type FS = EmscriptenFS & {\n ErrnoError: any;\n createNode: (\n parent: IEmscriptenFSNode | null,\n name: string,\n mode: number,\n dev: number,\n ) => IEmscriptenFSNode;\n};\n\n/**\n * The emscripten filesystem error codes.\n */\nexport type ERRNO_CODES = any;\n\n/**\n * The emscripten FS Path API.\n */\nexport type PATH = {\n basename: (path: string) => string;\n dirname: (path: string) => string;\n join: (...parts: string[]) => string;\n join2: (l: string, r: string) => string;\n normalize: (path: string) => string;\n splitPath: (filename: string) => string;\n};\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n// Types and implementation inspired from https://github.com/jvilk/BrowserFS\n// LICENSE: https://github.com/jvilk/BrowserFS/blob/8977a704ea469d05daf857e4818bef1f4f498326/LICENSE\n// And from https://github.com/gzuidhof/starboard-notebook\n\n// LICENSE: https://github.com/gzuidhof/starboard-notebook/blob/cd8d3fc30af4bd29cdd8f6b8c207df8138f5d5dd/LICENSE\nimport { Contents } from '@jupyterlab/services';\n\nimport {\n FS,\n ERRNO_CODES,\n PATH,\n DIR_MODE,\n SEEK_CUR,\n SEEK_END,\n IEmscriptenStream,\n instanceOfStream,\n IEmscriptenStreamOps,\n IEmscriptenNodeOps,\n IEmscriptenFSNode,\n IStats,\n} from './emscripten';\n\nexport const DRIVE_SEPARATOR = ':';\nexport const DRIVE_API_PATH = '/api/drive.v1';\n\nexport const BLOCK_SIZE = 4096;\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8');\n\nexport type TDriveMethod =\n | 'readdir'\n | 'rmdir'\n | 'rename'\n | 'getmode'\n | 'lookup'\n | 'mknod'\n | 'getattr'\n | 'get'\n | 'put';\n\n/**\n * Type of the data argument for the drive request, based on the request name\n */\nexport type TDriveData = {\n rename: {\n /**\n * The new path for the file\n */\n newPath: string;\n };\n mknod: {\n /**\n * The mode of the file to create\n */\n mode: number;\n };\n put: {\n /**\n * The file content to write\n */\n data: any;\n\n /**\n * The file content format\n */\n format: Contents.FileFormat;\n };\n};\n\n/**\n * Drive request\n */\nexport type TDriveRequest<T extends TDriveMethod> = {\n /**\n * The method of the request (rmdir, readdir etc)\n */\n method: T;\n\n /**\n * The expected receiver of the request\n */\n receiver?: 'broadcast.ts';\n\n /**\n * The path to the file/directory for which the request was sent\n */\n path: string;\n} & (T extends keyof TDriveData ? { data: TDriveData[T] } : object);\n\ntype TDriveResponses = {\n readdir: string[];\n rmdir: null;\n rename: null;\n getmode: number;\n lookup: DriveFS.ILookup;\n mknod: null;\n getattr: IStats;\n get:\n | {\n /**\n * The returned file content\n */\n content: any;\n\n /**\n * The content format\n */\n format: Contents.FileFormat;\n }\n | undefined;\n put: null;\n};\n\n/**\n * Drive response\n */\nexport type TDriveResponse<T extends TDriveMethod> = TDriveResponses[T];\n\n// Mapping flag -> do we need to overwrite the file upon closing it\nconst flagNeedsWrite: { [flag: number]: boolean } = {\n 0 /*O_RDONLY*/: false,\n 1 /*O_WRONLY*/: true,\n 2 /*O_RDWR*/: true,\n 64 /*O_CREAT*/: true,\n 65 /*O_WRONLY|O_CREAT*/: true,\n 66 /*O_RDWR|O_CREAT*/: true,\n 129 /*O_WRONLY|O_EXCL*/: true,\n 193 /*O_WRONLY|O_CREAT|O_EXCL*/: true,\n 514 /*O_RDWR|O_TRUNC*/: true,\n 577 /*O_WRONLY|O_CREAT|O_TRUNC*/: true,\n 578 /*O_CREAT|O_RDWR|O_TRUNC*/: true,\n 705 /*O_WRONLY|O_CREAT|O_EXCL|O_TRUNC*/: true,\n 706 /*O_RDWR|O_CREAT|O_EXCL|O_TRUNC*/: true,\n 1024 /*O_APPEND*/: true,\n 1025 /*O_WRONLY|O_APPEND*/: true,\n 1026 /*O_RDWR|O_APPEND*/: true,\n 1089 /*O_WRONLY|O_CREAT|O_APPEND*/: true,\n 1090 /*O_RDWR|O_CREAT|O_APPEND*/: true,\n 1153 /*O_WRONLY|O_EXCL|O_APPEND*/: true,\n 1154 /*O_RDWR|O_EXCL|O_APPEND*/: true,\n 1217 /*O_WRONLY|O_CREAT|O_EXCL|O_APPEND*/: true,\n 1218 /*O_RDWR|O_CREAT|O_EXCL|O_APPEND*/: true,\n 4096 /*O_RDONLY|O_DSYNC*/: true,\n 4098 /*O_RDWR|O_DSYNC*/: true,\n};\n\n/** Implementation-specifc extension of an open stream, adding the file. */\nexport interface IDriveStream extends IEmscriptenStream {\n file?: DriveFS.IFile;\n}\n\nexport class DriveFSEmscriptenStreamOps implements IEmscriptenStreamOps {\n private fs: DriveFS;\n\n constructor(fs: DriveFS) {\n this.fs = fs;\n }\n\n open(stream: IDriveStream): void {\n const path = this.fs.realPath(stream.node);\n if (this.fs.FS.isFile(stream.node.mode)) {\n stream.file = this.fs.API.get(path);\n }\n }\n\n close(stream: IDriveStream): void {\n if (!this.fs.FS.isFile(stream.node.mode) || !stream.file) {\n return;\n }\n\n const path = this.fs.realPath(stream.node);\n\n const flags = stream.flags;\n let parsedFlags = typeof flags === 'string' ? parseInt(flags, 10) : flags;\n parsedFlags &= 0x1fff;\n\n let needsWrite = true;\n if (parsedFlags in flagNeedsWrite) {\n needsWrite = flagNeedsWrite[parsedFlags];\n }\n\n if (needsWrite) {\n this.fs.API.put(path, stream.file);\n }\n\n stream.file = undefined;\n }\n\n read(\n stream: IDriveStream,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): number {\n if (\n length <= 0 ||\n stream.file === undefined ||\n position >= (stream.file.data.length || 0)\n ) {\n return 0;\n }\n\n const size = Math.min(stream.file.data.length - position, length);\n buffer.set(stream.file.data.subarray(position, position + size), offset);\n return size;\n }\n\n write(\n stream: IDriveStream,\n buffer: Uint8Array,\n offset: number,\n length: number,\n position: number,\n ): number {\n if (length <= 0 || stream.file === undefined) {\n return 0;\n }\n\n stream.node.timestamp = Date.now();\n\n if (position + length > (stream.file?.data.length || 0)) {\n const oldData = stream.file.data ? stream.file.data : new Uint8Array();\n stream.file.data = new Uint8Array(position + length);\n stream.file.data.set(oldData);\n }\n\n stream.file.data.set(buffer.subarray(offset, offset + length), position);\n\n return length;\n }\n\n llseek(stream: IDriveStream, offset: number, whence: number): number {\n let position = offset;\n if (whence === SEEK_CUR) {\n position += stream.position;\n } else if (whence === SEEK_END) {\n if (this.fs.FS.isFile(stream.node.mode)) {\n if (stream.file !== undefined) {\n position += stream.file.data.length;\n } else {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EPERM);\n }\n }\n }\n\n if (position < 0) {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES.EINVAL);\n }\n\n return position;\n }\n}\n\nexport class DriveFSEmscriptenNodeOps implements IEmscriptenNodeOps {\n private fs: DriveFS;\n\n constructor(fs: DriveFS) {\n this.fs = fs;\n }\n\n protected node(\n nodeOrStream: IEmscriptenFSNode | IEmscriptenStream,\n ): IEmscriptenFSNode {\n if (instanceOfStream(nodeOrStream)) {\n return nodeOrStream.node;\n }\n return nodeOrStream;\n }\n\n getattr(value: IEmscriptenFSNode | IEmscriptenStream): IStats {\n const node = this.node(value);\n return {\n ...this.fs.API.getattr(this.fs.realPath(node)),\n mode: node.mode,\n ino: node.id,\n };\n }\n\n setattr(value: IEmscriptenFSNode | IEmscriptenStream, attr: IStats): void {\n const node = this.node(value);\n for (const [key, value] of Object.entries(attr)) {\n switch (key) {\n case 'mode':\n node.mode = value;\n break;\n case 'timestamp':\n node.timestamp = value;\n break;\n case 'size': {\n const size = value;\n const path = this.fs.realPath(node);\n if (this.fs.FS.isFile(node.mode) && size >= 0) {\n const file = this.fs.API.get(path);\n const oldData = file.data ? file.data : new Uint8Array();\n if (size !== oldData.length) {\n if (size < oldData.length) {\n file.data = file.data.slice(0, size);\n } else {\n file.data = new Uint8Array(size);\n file.data.set(oldData);\n }\n this.fs.API.put(path, file);\n }\n } else {\n console.warn('setattr size of', size, 'on', node, 'not yet implemented');\n }\n break;\n }\n default:\n console.warn('setattr', key, 'of', value, 'on', node, 'not yet implemented');\n break;\n }\n }\n }\n\n lookup(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n name: string,\n ): IEmscriptenFSNode {\n const node = this.node(parent);\n const path = this.fs.PATH.join2(this.fs.realPath(node), name);\n const result = this.fs.API.lookup(path);\n if (!result.ok) {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['ENOENT']);\n }\n return this.fs.createNode(node, name, result.mode!, 0);\n }\n\n mknod(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n name: string,\n mode: number,\n dev: number,\n ): IEmscriptenFSNode {\n const node = this.node(parent);\n const path = this.fs.PATH.join2(this.fs.realPath(node), name);\n this.fs.API.mknod(path, mode);\n return this.fs.createNode(node, name, mode, dev);\n }\n\n rename(\n value: IEmscriptenFSNode | IEmscriptenStream,\n newDir: IEmscriptenFSNode | IEmscriptenStream,\n newName: string,\n ): void {\n const oldNode = this.node(value);\n const newDirNode = this.node(newDir);\n this.fs.API.rename(\n oldNode.parent\n ? this.fs.PATH.join2(this.fs.realPath(oldNode.parent), oldNode.name)\n : oldNode.name,\n this.fs.PATH.join2(this.fs.realPath(newDirNode), newName),\n );\n\n // Updating the in-memory node\n oldNode.name = newName;\n oldNode.parent = newDirNode;\n }\n\n unlink(parent: IEmscriptenFSNode | IEmscriptenStream, name: string): void {\n this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(this.node(parent)), name));\n }\n\n rmdir(parent: IEmscriptenFSNode | IEmscriptenStream, name: string) {\n this.fs.API.rmdir(this.fs.PATH.join2(this.fs.realPath(this.node(parent)), name));\n }\n\n readdir(value: IEmscriptenFSNode | IEmscriptenStream): string[] {\n return this.fs.API.readdir(this.fs.realPath(this.node(value)));\n }\n\n symlink(\n parent: IEmscriptenFSNode | IEmscriptenStream,\n newName: string,\n oldPath: string,\n ): void {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);\n }\n\n readlink(node: IEmscriptenFSNode | IEmscriptenStream): string {\n throw new this.fs.FS.ErrnoError(this.fs.ERRNO_CODES['EPERM']);\n }\n}\n\n/**\n * ContentsAPI base class\n */\nexport abstract class ContentsAPI {\n constructor(driveName: string, mountpoint: string, FS: FS, ERRNO_CODES: ERRNO_CODES) {\n this._driveName = driveName;\n this._mountpoint = mountpoint;\n\n this.FS = FS;\n this.ERRNO_CODES = ERRNO_CODES;\n }\n\n lookup(path: string): DriveFS.ILookup {\n return this.request({ method: 'lookup', path: this.normalizePath(path) });\n }\n\n getmode(path: string): number {\n return this.request({ method: 'getmode', path: this.normalizePath(path) });\n }\n\n mknod(path: string, mode: number): null {\n return this.request({\n method: 'mknod',\n path: this.normalizePath(path),\n data: { mode },\n });\n }\n\n rename(oldPath: string, newPath: string): null {\n return this.request({\n method: 'rename',\n path: this.normalizePath(oldPath),\n data: { newPath: this.normalizePath(newPath) },\n });\n }\n\n readdir(path: string): string[] {\n const dirlist = this.request({\n method: 'readdir',\n path: this.normalizePath(path),\n });\n dirlist.push('.');\n dirlist.push('..');\n return dirlist;\n }\n\n rmdir(path: string): null {\n return this.request({ method: 'rmdir', path: this.normalizePath(path) });\n }\n\n get(path: string): DriveFS.IFile {\n const response = this.request({\n method: 'get',\n path: this.normalizePath(path),\n });\n\n if (!response) {\n throw new this.FS.ErrnoError(this.ERRNO_CODES['ENOENT']);\n }\n\n const serializedContent = response.content;\n const format: 'json' | 'text' | 'base64' | null = response.format;\n\n switch (format) {\n case 'json':\n case 'text':\n return {\n data: encoder.encode(serializedContent),\n format,\n };\n case 'base64': {\n const binString = atob(serializedContent);\n const len = binString.length;\n const data = new Uint8Array(len);\n for (let i = 0; i < len; i++) {\n data[i] = binString.charCodeAt(i);\n }\n return {\n data,\n format,\n };\n }\n default:\n throw new this.FS.ErrnoError(this.ERRNO_CODES['ENOENT']);\n }\n }\n\n put(path: string, value: DriveFS.IFile): null {\n switch (value.format) {\n case 'json':\n case 'text':\n return this.request({\n method: 'put',\n path: this.normalizePath(path),\n data: {\n format: value.format,\n data: decoder.decode(value.data),\n },\n });\n case 'base64': {\n let binary = '';\n for (let i = 0; i < value.data.byteLength; i++) {\n binary += String.fromCharCode(value.data[i]);\n }\n return this.request({\n method: 'put',\n path: this.normalizePath(path),\n data: {\n format: value.format,\n data: btoa(binary),\n },\n });\n }\n }\n }\n\n getattr(path: string): IStats {\n const stats = this.request({\n method: 'getattr',\n path: this.normalizePath(path),\n });\n // Turn datetimes into proper objects\n if (stats.atime) {\n stats.atime = new Date(stats.atime);\n }\n if (stats.mtime) {\n stats.mtime = new Date(stats.mtime);\n }\n if (stats.ctime) {\n stats.ctime = new Date(stats.ctime);\n }\n // ensure a non-undefined size (0 isn't great, though)\n stats.size = stats.size || 0;\n return stats;\n }\n\n /**\n * Normalize a Path by making it compliant for the content manager\n *\n * @param path: the path relatively to the Emscripten drive\n */\n normalizePath(path: string): string {\n // Remove mountpoint prefix\n if (path.startsWith(this._mountpoint)) {\n path = path.slice(this._mountpoint.length);\n }\n\n // Add JupyterLab drive name\n if (this._driveName) {\n path = `${this._driveName}${DRIVE_SEPARATOR}${path}`;\n }\n\n return path;\n }\n\n abstract request<T extends TDriveMethod>(data: TDriveRequest<T>): TDriveResponse<T>;\n\n private _driveName: string;\n private _mountpoint: string;\n\n protected FS: FS;\n protected ERRNO_CODES: ERRNO_CODES;\n}\n\n/**\n * An Emscripten-compatible synchronous Contents API using the service worker.\n */\nexport class ServiceWorkerContentsAPI extends ContentsAPI {\n constructor(\n baseUrl: string,\n driveName: string,\n mountpoint: string,\n FS: FS,\n ERRNO_CODES: ERRNO_CODES,\n ) {\n super(driveName, mountpoint, FS, ERRNO_CODES);\n\n this._baseUrl = baseUrl;\n }\n\n request<T extends TDriveMethod>(data: TDriveRequest<T>): TDriveResponse<T> {\n const xhr = new XMLHttpRequest();\n xhr.open('POST', encodeURI(this.endpoint), false);\n\n try {\n xhr.send(JSON.stringify(data));\n } catch (e) {\n console.error(e);\n }\n\n if (xhr.status >= 400) {\n throw new this.FS.ErrnoError(this.ERRNO_CODES['EINVAL']);\n }\n\n return JSON.parse(xhr.responseText);\n }\n\n /**\n * Get the api/drive endpoint\n */\n get endpoint(): string {\n return `${this._baseUrl}api/drive`;\n }\n\n private _baseUrl: string;\n}\n\nexport class DriveFS {\n FS: FS;\n API: ContentsAPI;\n PATH: PATH;\n ERRNO_CODES: ERRNO_CODES;\n driveName: string;\n\n constructor(options: DriveFS.IOptions) {\n this.FS = options.FS;\n this.PATH = options.PATH;\n this.ERRNO_CODES = options.ERRNO_CODES;\n this.API = this.createAPI(options);\n\n this.driveName = options.driveName;\n\n this.node_ops = new DriveFSEmscriptenNodeOps(this);\n this.stream_ops = new DriveFSEmscriptenStreamOps(this);\n }\n\n node_ops: IEmscriptenNodeOps;\n stream_ops: IEmscriptenStreamOps;\n\n /**\n * Create the ContentsAPI.\n *\n * This is supposed to be overwritten if needed.\n */\n createAPI(options: DriveFS.IOptions): ContentsAPI {\n return new ServiceWorkerContentsAPI(\n options.baseUrl,\n options.driveName,\n options.mountpoint,\n options.FS,\n options.ERRNO_CODES,\n );\n }\n\n mount(mount: any): IEmscriptenFSNode {\n return this.createNode(null, mount.mountpoint, DIR_MODE | 511, 0);\n }\n\n createNode(\n parent: IEmscriptenFSNode | null,\n name: string,\n mode: number,\n dev: number,\n ): IEmscriptenFSNode {\n const FS = this.FS;\n if (!FS.isDir(mode) && !FS.isFile(mode)) {\n throw new FS.ErrnoError(this.ERRNO_CODES['EINVAL']);\n }\n const node = FS.createNode(parent, name, mode, dev);\n node.node_ops = this.node_ops;\n node.stream_ops = this.stream_ops;\n return node;\n }\n\n getMode(path: string): number {\n return this.API.getmode(path);\n }\n\n realPath(node: IEmscriptenFSNode): string {\n const parts: string[] = [];\n let currentNode: IEmscriptenFSNode = node;\n\n parts.push(currentNode.name);\n while (currentNode.parent !== currentNode) {\n currentNode = currentNode.parent;\n parts.push(currentNode.name);\n }\n parts.reverse();\n\n return this.PATH.join.apply(null, parts);\n }\n}\n\n/**\n * A namespace for DriveFS configurations, etc.\n */\nexport namespace DriveFS {\n /**\n * A file representation;\n */\n export interface IFile {\n data: Uint8Array;\n format: 'json' | 'text' | 'base64';\n }\n\n /**\n * The response to a lookup request;\n */\n export interface ILookup {\n ok: boolean;\n mode?: number;\n }\n\n /**\n * Initialization options for a drive;\n */\n export interface IOptions {\n FS: FS;\n PATH: PATH;\n ERRNO_CODES: ERRNO_CODES;\n baseUrl: string;\n driveName: string;\n mountpoint: string;\n }\n}\n", "import { PathExt } from '@jupyterlab/coreutils';\nimport { Contents } from '@jupyterlab/services';\nimport { BLOCK_SIZE, TDriveMethod, TDriveRequest, TDriveResponse } from './drivefs';\nimport { DIR_MODE, FILE_MODE } from './emscripten';\n\nexport interface IDriveContentsProcessor {\n /**\n * Process a content request\n *\n * @param request the request\n */\n processDriveRequest<T extends TDriveMethod>(\n request: TDriveRequest<T>,\n ): Promise<TDriveResponse<T>>;\n\n /**\n * Process the request to read a directory content\n *\n * @param request the request\n */\n readdir(request: TDriveRequest<'readdir'>): Promise<TDriveResponse<'readdir'>>;\n\n /**\n * Process the request to remove a directory\n *\n * @param request the request\n */\n rmdir(request: TDriveRequest<'rmdir'>): Promise<TDriveResponse<'rmdir'>>;\n\n /**\n * Process the request to rename a file or directory\n *\n * @param request the request\n */\n rename(request: TDriveRequest<'rename'>): Promise<TDriveResponse<'rename'>>;\n\n /**\n * Process the request to get the node mode (file or directory)\n *\n * @param request the request\n */\n getmode(request: TDriveRequest<'getmode'>): Promise<TDriveResponse<'getmode'>>;\n\n /**\n * Process the request to check if a node exist\n *\n * @param request the request\n */\n lookup(request: TDriveRequest<'lookup'>): Promise<TDriveResponse<'lookup'>>;\n\n /**\n * Process the request to create a directory/file\n *\n * @param request the request\n */\n mknod(request: TDriveRequest<'mknod'>): Promise<TDriveResponse<'mknod'>>;\n\n /**\n * Process the request to get a node stats\n *\n * @param request the request\n */\n getattr(request: TDriveRequest<'getattr'>): Promise<TDriveResponse<'getattr'>>;\n\n /**\n * Process the request to get the content of a file\n *\n * @param request the request\n */\n get(request: TDriveRequest<'get'>): Promise<TDriveResponse<'get'>>;\n\n /**\n * Process the request to write the content of a file\n *\n * @param request the request\n */\n put(request: TDriveRequest<'put'>): Promise<TDriveResponse<'put'>>;\n}\n\n/**\n * Class for processing a drive request from the DriveFS.\n */\nexport class DriveContentsProcessor implements IDriveContentsProcessor {\n private contentsManager: Contents.IManager;\n\n constructor(options: DriveContentsProcessor.IOptions) {\n this.contentsManager = options.contentsManager;\n }\n\n async processDriveRequest<T extends TDriveMethod>(\n request: TDriveRequest<T>,\n ): Promise<TDriveResponse<T>> {\n switch (request.method) {\n case 'readdir':\n return this.readdir(request as TDriveRequest<'readdir'>) as Promise<\n TDriveResponse<T>\n >;\n case 'rmdir':\n return this.rmdir(request as TDriveRequest<'rmdir'>) as Promise<\n TDriveResponse<T>\n >;\n case 'rename':\n return this.rename(request as TDriveRequest<'rename'>) as Promise<\n TDriveResponse<T>\n >;\n case 'getmode':\n return this.getmode(request as TDriveRequest<'getmode'>) as Promise<\n TDriveResponse<T>\n >;\n case 'lookup':\n return this.lookup(request as TDriveRequest<'lookup'>) as Promise<\n TDriveResponse<T>\n >;\n case 'mknod':\n return this.mknod(request as TDriveRequest<'mknod'>) as Promise<\n TDriveResponse<T>\n >;\n case 'getattr':\n return this.getattr(request as TDriveRequest<'getattr'>) as Promise<\n TDriveResponse<T>\n >;\n case 'get':\n return this.get(request as TDriveRequest<'get'>) as Promise<TDriveResponse<T>>;\n case 'put':\n return this.put(request as TDriveRequest<'put'>) as Promise<TDriveResponse<T>>;\n }\n\n throw `Drive request ${request.method} does not exist.`;\n }\n\n async readdir(request: TDriveRequest<'readdir'>): Promise<TDriveResponse<'readdir'>> {\n const model = await this.contentsManager.get(request.path, { content: true });\n let response: string[] = [];\n if (model.type === 'directory' && model.content) {\n response = model.content.map((subcontent: Contents.IModel) => subcontent.name);\n }\n return response;\n }\n\n async rmdir(request: TDriveRequest<'rmdir'>): Promise<TDriveResponse<'rmdir'>> {\n await this.contentsManager.delete(request.path);\n return null;\n }\n\n async rename(request: TDriveRequest<'rename'>): Promise<TDriveResponse<'rename'>> {\n await this.contentsManager.rename(request.path, request.data.newPath);\n return null;\n }\n\n async getmode(request: TDriveRequest<'getmode'>): Promise<TDriveResponse<'getmode'>> {\n const model = await this.contentsManager.get(request.path);\n let response: number;\n if (model.type === 'directory') {\n response = DIR_MODE;\n } else {\n response = FILE_MODE;\n }\n return response;\n }\n\n async lookup(request: TDriveRequest<'lookup'>): Promise<TDriveResponse<'lookup'>> {\n let response: TDriveResponse<'lookup'>;\n\n try {\n const model = await this.contentsManager.get(request.path);\n response = {\n ok: true,\n mode: model.type === 'directory' ? DIR_MODE : FILE_MODE,\n };\n } catch (e) {\n response = { ok: false };\n }\n\n return response;\n }\n\n async mknod(request: TDriveRequest<'mknod'>): Promise<TDriveResponse<'mknod'>> {\n const model = await this.contentsManager.newUntitled({\n path: PathExt.dirname(request.path),\n type: request.data.mode === DIR_MODE ? 'directory' : 'file',\n ext: PathExt.extname(request.path),\n });\n await this.contentsManager.rename(model.path, request.path);\n return null;\n }\n\n async getattr(request: TDriveRequest<'getattr'>): Promise<TDriveResponse<'getattr'>> {\n const model = await this.contentsManager.get(request.path);\n // create a default date for drives that send incomplete information\n // for nested foldes and files\n const defaultDate = new Date(0).toISOString();\n\n return {\n dev: 1,\n nlink: 1,\n uid: 0,\n gid: 0,\n rdev: 0,\n size: model.size || 0,\n blksize: BLOCK_SIZE,\n blocks: Math.ceil(model.size || 0 / BLOCK_SIZE),\n atime: model.last_modified || defaultDate, // TODO Get the proper atime?\n mtime: model.last_modified || defaultDate,\n ctime: model.created || defaultDate,\n timestamp: 0,\n };\n }\n\n async get(request: TDriveRequest<'get'>): Promise<TDriveResponse<'get'>> {\n const model = await this.contentsManager.get(request.path, { content: true });\n\n let response;\n\n if (model.type !== 'directory') {\n response = {\n content:\n model.format === 'json' ? JSON.stringify(model.content) : model.content,\n format: model.format,\n };\n }\n\n return response;\n }\n\n async put(request: TDriveRequest<'put'>): Promise<TDriveResponse<'put'>> {\n await this.contentsManager.save(request.path, {\n content:\n request.data.format === 'json'\n ? JSON.parse(request.data.data)\n : request.data.data,\n type: 'file',\n format: request.data.format as Contents.FileFormat,\n });\n return null;\n }\n}\n\n/**\n * A namespace for DriveContentsProcessor configurations, etc.\n */\nexport namespace DriveContentsProcessor {\n /**\n * Initialization options for a drive;\n */\n export interface IOptions {\n contentsManager: Contents.IManager;\n }\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport { Contents as ServerContents } from '@jupyterlab/services';\n\nimport { TDriveRequest, DRIVE_API_PATH, TDriveMethod } from './drivefs';\n\nimport { IBroadcastChannelWrapper } from './tokens';\nimport { IDriveContentsProcessor, DriveContentsProcessor } from './drivecontents';\n\n/** A broadcaster for the ServiceWorker */\nexport class BroadcastChannelWrapper implements IBroadcastChannelWrapper {\n public isDisposed = false;\n\n constructor(options: BroadcastChannelWrapper.IOptions) {\n this._contents = options.contents;\n this._driveContentsProcessor = new DriveContentsProcessor({\n contentsManager: this._contents,\n });\n }\n\n get enabled() {\n return this._enabled;\n }\n\n enable() {\n if (this._channel) {\n console.warn('BroadcastChannel already created and enabled');\n return;\n }\n this._channel = new BroadcastChannel(DRIVE_API_PATH);\n this._channel.addEventListener('message', this._onMessage);\n this._enabled = true;\n }\n\n disable() {\n if (this._channel) {\n this._channel.removeEventListener('message', this._onMessage);\n this._channel = null;\n }\n this._enabled = false;\n }\n\n /** Clean up the broadcaster. */\n dispose() {\n if (this.isDisposed) {\n return;\n }\n this.disable();\n this.isDisposed = true;\n }\n\n /** Handle a message received on the BroadcastChannel */\n protected _onMessage = async <T extends TDriveMethod>(\n event: MessageEvent<TDriveRequest<T>>,\n ): Promise<void> => {\n if (!this._channel) {\n return;\n }\n\n const request = event.data;\n const receiver = request?.receiver;\n if (receiver !== 'broadcast.ts') {\n // Message is not meant for us\n return;\n }\n\n const response = await this._driveContentsProcessor.processDriveRequest(request);\n\n this._channel.postMessage(response);\n };\n\n protected _channel: BroadcastChannel | null = null;\n protected _contents: ServerContents.IManager;\n protected _driveContentsProcessor: IDriveContentsProcessor;\n protected _enabled = false;\n}\n\n/** A namespace for */\nexport namespace BroadcastChannelWrapper {\n export interface IOptions {\n contents: ServerContents.IManager;\n }\n export type TBroadcastResponse = any;\n}\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nexport * from './drive';\nexport * from './drivefs';\nexport * from './tokens';\nexport * from './broadcast';\nexport * from './emscripten';\nexport * from './drivecontents';\n", "export const ARRAY = 'array';\nexport const BIGINT = 'bigint';\nexport const BOOLEAN = 'boolean';\nexport const FUNCTION = 'function';\nexport const NULL = 'null';\nexport const NUMBER = 'number';\nexport const OBJECT = 'object';\nexport const STRING = 'string';\nexport const SYMBOL = 'symbol';\nexport const UNDEFINED = 'undefined';\n", "// \u26A0\uFE0F AUTOMATICALLY GENERATED - DO NOT CHANGE\nexport const CHANNEL = '64e10b34-2bf7-4616-9668-f99de5aa046e';\n\nexport const MAIN = 'M' + CHANNEL;\nexport const THREAD = 'T' + CHANNEL;\n", "export const APPLY = 'apply';\nexport const CONSTRUCT = 'construct';\nexport const DEFINE_PROPERTY = 'defineProperty';\nexport const DELETE_PROPERTY = 'deleteProperty';\nexport const GET = 'get';\nexport const GET_OWN_PROPERTY_DESCRIPTOR = 'getOwnPropertyDescriptor';\nexport const GET_PROTOTYPE_OF = 'getPrototypeOf';\nexport const HAS = 'has';\nexport const IS_EXTENSIBLE = 'isExtensible';\nexport const OWN_KEYS = 'ownKeys';\nexport const PREVENT_EXTENSION = 'preventExtensions';\nexport const SET = 'set';\nexport const SET_PROTOTYPE_OF = 'setPrototypeOf';\n", "// The goal of this file is to normalize SAB\n// at least in main -> worker() use cases.\n// This still cannot possibly solve the sync\n// worker -> main() use case if SharedArrayBuffer\n// is not available or usable.\n\nimport {CHANNEL} from './channel.js';\n\nconst {isArray} = Array;\n\nlet {SharedArrayBuffer, window} = globalThis;\nlet {notify, wait, waitAsync} = Atomics;\nlet postPatched = null;\n\n// This is needed for some version of Firefox\nif (!waitAsync) {\n waitAsync = buffer => ({\n value: new Promise(onmessage => {\n // encodeURIComponent('onmessage=({data:b})=>(Atomics.wait(b,0),postMessage(0))')\n let w = new Worker('data:application/javascript,onmessage%3D(%7Bdata%3Ab%7D)%3D%3E(Atomics.wait(b%2C0)%2CpostMessage(0))');\n w.onmessage = onmessage;\n w.postMessage(buffer);\n })\n });\n}\n\n// Monkey-patch SharedArrayBuffer if needed\ntry {\n new SharedArrayBuffer(4);\n}\ncatch (_) {\n SharedArrayBuffer = ArrayBuffer;\n\n const ids = new WeakMap;\n // patch only main -> worker():async use case\n if (window) {\n const resolvers = new Map;\n const {prototype: {postMessage}} = Worker;\n\n const listener = event => {\n const details = event.data?.[CHANNEL];\n if (!isArray(details)) {\n event.stopImmediatePropagation();\n const { id, sb } = details;\n resolvers.get(id)(sb);\n }\n };\n\n postPatched = function (data, ...rest) {\n const details = data?.[CHANNEL];\n if (isArray(details)) {\n const [id, sb] = details;\n ids.set(sb, id);\n this.addEventListener('message', listener);\n }\n return postMessage.call(this, data, ...rest);\n };\n\n waitAsync = sb => ({\n value: new Promise(resolve => {\n resolvers.set(ids.get(sb), resolve);\n }).then(buff => {\n resolvers.delete(ids.get(sb));\n ids.delete(sb);\n for (let i = 0; i < buff.length; i++) sb[i] = buff[i];\n return 'ok';\n })\n });\n }\n else {\n const as = (id, sb) => ({[CHANNEL]: { id, sb }});\n\n notify = sb => {\n postMessage(as(ids.get(sb), sb));\n };\n\n addEventListener('message', event => {\n const details = event.data?.[CHANNEL];\n if (isArray(details)) {\n const [id, sb] = details;\n ids.set(sb, id);\n }\n });\n }\n}\n\nexport {SharedArrayBuffer, isArray, notify, postPatched, wait, waitAsync};\n", "/*! (c) Andrea Giammarchi - ISC */\n\nimport {FUNCTION} from 'proxy-target/types';\n\nimport {CHANNEL} from './channel.js';\nimport {GET, HAS, SET} from './shared/traps.js';\n\nimport {SharedArrayBuffer, isArray, notify, postPatched, wait, waitAsync} from './bridge.js';\n\n// just minifier friendly for Blob Workers' cases\nconst {Int32Array, Map, Uint16Array} = globalThis;\n\n// common constants / utilities for repeated operations\nconst {BYTES_PER_ELEMENT: I32_BYTES} = Int32Array;\nconst {BYTES_PER_ELEMENT: UI16_BYTES} = Uint16Array;\n\nconst waitInterrupt = (sb, delay, handler) => {\n while (wait(sb, 0, 0, delay) === 'timed-out')\n handler();\n};\n\n// retain buffers to transfer\nconst buffers = new WeakSet;\n\n// retain either main threads or workers global context\nconst context = new WeakMap;\n\nconst syncResult = {value: {then: fn => fn()}};\n\n// used to generate a unique `id` per each worker `postMessage` \"transaction\"\nlet uid = 0;\n\n/**\n * @typedef {Object} Interrupt used to sanity-check interrupts while waiting synchronously.\n * @prop {function} [handler] a callback invoked every `delay` milliseconds.\n * @prop {number} [delay=42] define `handler` invokes in terms of milliseconds.\n */\n\n/**\n * Create once a `Proxy` able to orchestrate synchronous `postMessage` out of the box.\n * @param {globalThis | Worker} self the context in which code should run\n * @param {{parse: (serialized: string) => any, stringify: (serializable: any) => string, transform?: (value:any) => any, interrupt?: () => void | Interrupt}} [JSON] an optional `JSON` like interface to `parse` or `stringify` content with extra `transform` ability.\n * @returns {ProxyHandler<globalThis> | ProxyHandler<Worker>}\n */\nconst coincident = (self, {parse = JSON.parse, stringify = JSON.stringify, transform, interrupt} = JSON) => {\n // create a Proxy once for the given context (globalThis or Worker instance)\n if (!context.has(self)) {\n // ensure no SAB gets a chance to pass through this call\n const sendMessage = postPatched || self.postMessage;\n // ensure the CHANNEL and data are posted correctly\n const post = (transfer, ...args) => sendMessage.call(self, {[CHANNEL]: args}, {transfer});\n\n const handler = typeof interrupt === FUNCTION ? interrupt : interrupt?.handler;\n const delay = interrupt?.delay || 42;\n const decoder = new TextDecoder('utf-16');\n\n // automatically uses sync wait (worker -> main)\n // or fallback to async wait (main -> worker)\n const waitFor = (isAsync, sb) => isAsync ?\n waitAsync(sb, 0) :\n ((handler ? waitInterrupt(sb, delay, handler) : wait(sb, 0)), syncResult);\n\n // prevent Harakiri https://github.com/WebReflection/coincident/issues/18\n let seppuku = false;\n\n context.set(self, new Proxy(new Map, {\n // there is very little point in checking prop in proxy for this very specific case\n // and I don't want to orchestrate a whole roundtrip neither, as stuff would fail\n // regardless if from Worker we access non existent Main callback, and vice-versa.\n // This is here mostly to guarantee that if such check is performed, at least the\n // get trap goes through and then it's up to developers guarantee they are accessing\n // stuff that actually exists elsewhere.\n [HAS]: (_, action) => typeof action === 'string' && !action.startsWith('_'),\n\n // worker related: get any utility that should be available on the main thread\n [GET]: (_, action) => action === 'then' ? null : ((...args) => {\n // transaction id\n const id = uid++;\n\n // first contact: just ask for how big the buffer should be\n // the value would be stored at index [1] while [0] is just control\n let sb = new Int32Array(new SharedArrayBuffer(I32_BYTES * 2));\n\n // if a transfer list has been passed, drop it from args\n let transfer = [];\n if (buffers.has(args.at(-1) || transfer))\n buffers.delete(transfer = args.pop());\n\n // ask for invoke with arguments and wait for it\n post(transfer, id, sb, action, transform ? args.map(transform) : args);\n\n // helps deciding how to wait for results\n const isAsync = self !== globalThis;\n\n // warn users about possible deadlock still allowing them\n // to explicitly `proxy.invoke().then(...)` without blocking\n let deadlock = 0;\n if (seppuku && isAsync)\n deadlock = setTimeout(console.warn, 1000, `\uD83D\uDC80\uD83D\uDD12 - Possible deadlock if proxy.${action}(...args) is awaited`);\n\n return waitFor(isAsync, sb).value.then(() => {\n clearTimeout(deadlock);\n\n // commit transaction using the returned / needed buffer length\n const length = sb[1];\n\n // filter undefined results\n if (!length) return;\n\n // calculate the needed ui16 bytes length to store the result string\n const bytes = UI16_BYTES * length;\n\n // round up to the next amount of bytes divided by 4 to allow i32 operations\n sb = new Int32Array(new SharedArrayBuffer(bytes + (bytes % I32_BYTES)));\n\n // ask for results and wait for it\n post([], id, sb);\n return waitFor(isAsync, sb).value.then(() => parse(\n decoder.decode(new Uint16Array(sb.buffer).slice(0, length)))\n );\n });\n }),\n\n // main thread related: react to any utility a worker is asking for\n [SET](actions, action, callback) {\n const type = typeof callback;\n if (type !== FUNCTION)\n throw new Error(`Unable to assign ${action} as ${type}`);\n // lazy event listener and logic handling, triggered once by setters actions\n if (!actions.size) {\n // maps results by `id` as they are asked for\n const results = new Map;\n // add the event listener once (first defined setter, all others work the same)\n self.addEventListener('message', async (event) => {\n // grub the very same library CHANNEL; ignore otherwise\n const details = event.data?.[CHANNEL];\n if (isArray(details)) {\n // if early enough, avoid leaking data to other listeners\n event.stopImmediatePropagation();\n const [id, sb, ...rest] = details;\n let error;\n // action available: it must be defined/known on the main thread\n if (rest.length) {\n const [action, args] = rest;\n if (actions.has(action)) {\n seppuku = true;\n try {\n // await for result either sync or async and serialize it\n const result = await actions.get(action)(...args);\n if (result !== void 0) {\n const serialized = stringify(transform ? transform(result) : result);\n // store the result for \"the very next\" event listener call\n results.set(id, serialized);\n // communicate the required SharedArrayBuffer length out of the\n // resulting serialized string\n sb[1] = serialized.length;\n }\n }\n catch (_) {\n error = _;\n }\n finally {\n seppuku = false;\n }\n }\n // unknown action should be notified as missing on the main thread\n else {\n error = new Error(`Unsupported action: ${action}`);\n }\n // unlock the wait lock later on\n sb[0] = 1;\n }\n // no action means: get results out of the well known `id`\n // wait lock automatically unlocked here as no `0` value would\n // possibly ever land at index `0`\n else {\n const result = results.get(id);\n results.delete(id);\n // populate the SharedArrayBuffer with utf-16 chars code\n for (let ui16a = new Uint16Array(sb.buffer), i = 0; i < result.length; i++)\n ui16a[i] = result.charCodeAt(i);\n }\n // release te worker waiting either the length or the result\n notify(sb, 0);\n if (error) throw error;\n }\n });\n }\n // store this action callback allowing the setter in the process\n return !!actions.set(action, callback);\n }\n }));\n }\n return context.get(self);\n};\n\ncoincident.transfer = (...args) => (buffers.add(args), args);\n\nexport default coincident;\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\n/**\n * A WebWorker entrypoint that uses coincident to handle postMessage details\n */\nimport coincident from 'coincident';\n\nimport {\n ContentsAPI,\n DriveFS,\n TDriveMethod,\n TDriveRequest,\n TDriveResponse,\n} from '@jupyterlite/contents';\n\nimport { IPyodideWorkerKernel } from './tokens';\n\nimport { PyodideRemoteKernel } from './worker';\n\nconst workerAPI = coincident(self) as IPyodideWorkerKernel;\n\n/**\n * An Emscripten-compatible synchronous Contents API using shared array buffers.\n */\nexport class SharedBufferContentsAPI extends ContentsAPI {\n request<T extends TDriveMethod>(data: TDriveRequest<T>): TDriveResponse<T> {\n return workerAPI.processDriveRequest(data);\n }\n}\n\n/**\n * A custom drive implementation which uses shared array buffers (via coincident) if available\n */\nclass PyodideDriveFS extends DriveFS {\n createAPI(options: DriveFS.IOptions): ContentsAPI {\n return new SharedBufferContentsAPI(\n options.driveName,\n options.mountpoint,\n options.FS,\n options.ERRNO_CODES,\n );\n }\n}\n\nexport class PyodideCoincidentKernel extends PyodideRemoteKernel {\n /**\n * Setup custom Emscripten FileSystem\n */\n protected async initFilesystem(\n options: IPyodideWorkerKernel.IOptions,\n ): Promise<void> {\n if (options.mountDrive) {\n const mountpoint = '/drive';\n const { FS, PATH, ERRNO_CODES } = this._pyodide;\n const { baseUrl } = options;\n\n const driveFS = new PyodideDriveFS({\n FS: FS as any,\n PATH,\n ERRNO_CODES,\n baseUrl,\n driveName: this._driveName,\n mountpoint,\n });\n FS.mkdirTree(mountpoint);\n FS.mount(driveFS, {}, mountpoint);\n FS.chdir(mountpoint);\n this._driveFS = driveFS;\n }\n }\n}\n\nconst worker = new PyodideCoincidentKernel();\n\nconst sendWorkerMessage = workerAPI.processWorkerMessage.bind(workerAPI);\nworker.registerCallback(sendWorkerMessage);\n\nworkerAPI.initialize = worker.initialize.bind(worker);\nworkerAPI.execute = worker.execute.bind(worker);\nworkerAPI.complete = worker.complete.bind(worker);\nworkerAPI.inspect = worker.inspect.bind(worker);\nworkerAPI.isComplete = worker.isComplete.bind(worker);\nworkerAPI.commInfo = worker.commInfo.bind(worker);\nworkerAPI.commOpen = worker.commOpen.bind(worker);\nworkerAPI.commMsg = worker.commMsg.bind(worker);\nworkerAPI.commClose = worker.commClose.bind(worker);\nworkerAPI.inputReply = worker.inputReply.bind(worker);\n", "// Copyright (c) Jupyter Development Team.\n// Distributed under the terms of the Modified BSD License.\n\nimport type Pyodide from 'pyodide';\n\nimport type { DriveFS } from '@jupyterlite/contents';\n\nimport { KernelMessage } from '@jupyterlab/services';\n\nimport type { IPyodideWorkerKernel } from './tokens';\n\nexport class PyodideRemoteKernel {\n constructor() {\n this._initialized = new Promise((resolve, reject) => {\n this._initializer = { resolve, reject };\n });\n }\n\n /**\n * Accept the URLs from the host\n **/\n async initialize(options: IPyodideWorkerKernel.IOptions): Promise<void> {\n this._options = options;\n\n if (options.location.includes(':')) {\n const parts = options.location.split(':');\n this._driveName = parts[0];\n this._localPath = parts[1];\n } else {\n this._driveName = '';\n this._localPath = options.location;\n }\n\n await this.initRuntime(options);\n await this.initFilesystem(options);\n await this.initPackageManager(options);\n await this.initKernel(options);\n await this.initGlobals(options);\n this._initializer?.resolve();\n }\n\n protected async initRuntime(options: IPyodideWorkerKernel.IOptions): Promise<void> {\n const { pyodideUrl, indexUrl } = options;\n let loadPyodide: typeof Pyodide.loadPyodide;\n if (pyodideUrl.endsWith('.mjs')) {\n // note: this does not work at all in firefox\n const pyodideModule: typeof Pyodide = await import(\n /* webpackIgnore: true */ pyodideUrl\n );\n loadPyodide = pyodideModule.loadPyodide;\n } else {\n importScripts(pyodideUrl);\n loadPyodide = (self as any).loadPyodide;\n }\n this._pyodide = await loadPyodide({\n indexURL: indexUrl,\n ...options.loadPyodideOptions,\n });\n }\n\n protected async initPackageManager(\n options: IPyodideWorkerKernel.IOptions,\n ): Promise<void> {\n if (!this._options) {\n throw new Error('Uninitialized');\n }\n\n const { pipliteWheelUrl, disablePyPIFallback, pipliteUrls, loadPyodideOptions } =\n this._options;\n\n const preloaded = (loadPyodideOptions || {}).packages || [];\n\n if (!preloaded.includes('micropip')) {\n await this._pyodide.loadPackage(['micropip']);\n }\n\n if (!preloaded.includes('piplite')) {\n await this._pyodide.runPythonAsync(`\n import micropip\n await micropip.install('${pipliteWheelUrl}', keep_going=True)\n `);\n }\n\n // get piplite early enough to impact pyodide-kernel dependencies\n await this._pyodide.runPythonAsync(`\n import piplite.piplite\n piplite.piplite._PIPLITE_DISABLE_PYPI = ${disablePyPIFallback ? 'True' : 'False'}\n piplite.piplite._PIPLITE_URLS = ${JSON.stringify(pipliteUrls)}\n `);\n }\n\n protected async initKernel(options: IPyodideWorkerKernel.IOptions): Promise<void> {\n const preloaded = (options.loadPyodideOptions || {}).packages || [];\n\n const toLoad = [\n 'ssl',\n 'sqlite3',\n 'ipykernel',\n 'comm',\n 'pyodide_kernel',\n 'jedi',\n 'ipython',\n ];\n\n const scriptLines: string[] = [];\n\n // use piplite for packages that weren't pre-loaded\n for (const pkgName of toLoad) {\n if (!preloaded.includes(pkgName)) {\n scriptLines.push(`await piplite.install('${pkgName}', keep_going=True)`);\n }\n }\n\n // import the kernel\n scriptLines.push('import pyodide_kernel');\n\n // cd to the kernel location\n if (options.mountDrive && this._localPath) {\n scriptLines.push('import os', `os.chdir(\"${this._localPath}\")`);\n }\n\n // from this point forward, only use piplite (but not %pip)\n await this._pyodide.runPythonAsync(scriptLines.join('\\n'));\n }\n\n protected async initGlobals(options: IPyodideWorkerKernel.IOptions): Promise<void> {\n const { globals } = this._pyodide;\n this._kernel = globals.get('pyodide_kernel').kernel_instance.copy();\n this._stdout_stream = globals.get('pyodide_kernel').stdout_stream.copy();\n this._stderr_stream = globals.get('pyodide_kernel').stderr_stream.copy();\n this._interpreter = this._kernel.interpreter.copy();\n this._interpreter.send_comm = this.sendComm.bind(this);\n }\n\n /**\n * Setup custom Emscripten FileSystem\n */\n protected async initFilesystem(\n options: IPyodideWorkerKernel.IOptions,\n ): Promise<void> {\n if (options.mountDrive) {\n const mountpoint = '/drive';\n const { FS, PATH, ERRNO_CODES } = this._pyodide;\n const { baseUrl } = options;\n const { DriveFS } = await import('@jupyterlite/contents');\n\n const driveFS = new DriveFS({\n FS: FS as any,\n PATH,\n ERRNO_CODES,\n baseUrl,\n driveName: this._driveName,\n mountpoint,\n });\n FS.mkdirTree(mountpoint);\n FS.mount(driveFS, {}, mountpoint);\n FS.chdir(mountpoint);\n this._driveFS = driveFS;\n }\n }\n\n /**\n * Recursively convert a Map to a JavaScript object\n * @param obj A Map, Array, or other object to convert\n */\n mapToObject(obj: any) {\n const out: any = obj instanceof Array ? [] : {};\n obj.forEach((value: any, key: string) => {\n out[key] =\n value instanceof Map || value instanceof Array\n ? this.mapToObject(value)\n : value;\n });\n return out;\n }\n\n /**\n * Format the response from the Pyodide evaluation.\n *\n * @param res The result object from the Pyodide evaluation\n */\n formatResult(res: any): any {\n if (!(res instanceof this._pyodide.ffi.PyProxy)) {\n return res;\n }\n // TODO: this is a bit brittle\n const m = res.toJs();\n const results = this.mapToObject(m);\n return results;\n }\n\n /**\n * Register the callback function to send messages from the worker back to the main thread.\n * @param callback the callback to register\n */\n registerCallback(callback: (msg: any) => void): void {\n this._sendWorkerMessage = callback;\n }\n\n /**\n * Makes sure pyodide is ready before continuing, and cache the parent message.\n */\n async setup(parent: any): Promise<void> {\n await this._initialized;\n this._kernel._parent_header = this._pyodide.toPy(parent);\n }\n\n /**\n * Execute code with the interpreter.\n *\n * @param content The incoming message with the code to execute.\n */\n async execute(content: any, parent: any) {\n await this.setup(parent);\n\n const publishExecutionResult = (\n prompt_count: any,\n data: any,\n metadata: any,\n ): void => {\n const bundle = {\n execution_count: prompt_count,\n data: this.formatResult(data),\n metadata: this.formatResult(metadata),\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'execute_result',\n });\n };\n\n const publishExecutionError = (ename: any, evalue: any, traceback: any): void => {\n const bundle = {\n ename: ename,\n evalue: evalue,\n traceback: traceback,\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'execute_error',\n });\n };\n\n const clearOutputCallback = (wait: boolean): void => {\n const bundle = {\n wait: this.formatResult(wait),\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'clear_output',\n });\n };\n\n const displayDataCallback = (data: any, metadata: any, transient: any): void => {\n const bundle = {\n data: this.formatResult(data),\n metadata: this.formatResult(metadata),\n transient: this.formatResult(transient),\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'display_data',\n });\n };\n\n const updateDisplayDataCallback = (\n data: any,\n metadata: any,\n transient: any,\n ): void => {\n const bundle = {\n data: this.formatResult(data),\n metadata: this.formatResult(metadata),\n transient: this.formatResult(transient),\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'update_display_data',\n });\n };\n\n const publishStreamCallback = (name: any, text: any): void => {\n const bundle = {\n name: this.formatResult(name),\n text: this.formatResult(text),\n };\n\n this._sendWorkerMessage({\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n bundle,\n type: 'stream',\n });\n };\n\n this._stdout_stream.publish_stream_callback = publishStreamCallback;\n this._stderr_stream.publish_stream_callback = publishStreamCallback;\n this._interpreter.display_pub.clear_output_callback = clearOutputCallback;\n this._interpreter.display_pub.display_data_callback = displayDataCallback;\n this._interpreter.display_pub.update_display_data_callback =\n updateDisplayDataCallback;\n this._interpreter.displayhook.publish_execution_result = publishExecutionResult;\n this._interpreter.input = this.input.bind(this);\n this._interpreter.getpass = this.getpass.bind(this);\n\n const res = await this._kernel.run(content.code);\n const results = this.formatResult(res);\n\n if (results['status'] === 'error') {\n publishExecutionError(results['ename'], results['evalue'], results['traceback']);\n }\n\n return results;\n }\n\n /**\n * Complete the code submitted by a user.\n *\n * @param content The incoming message with the code to complete.\n */\n async complete(content: any, parent: any) {\n await this.setup(parent);\n\n const res = this._kernel.complete(content.code, content.cursor_pos);\n const results = this.formatResult(res);\n return results;\n }\n\n /**\n * Inspect the code submitted by a user.\n *\n * @param content The incoming message with the code to inspect.\n */\n async inspect(\n content: { code: string; cursor_pos: number; detail_level: 0 | 1 },\n parent: any,\n ) {\n await this.setup(parent);\n\n const res = this._kernel.inspect(\n content.code,\n content.cursor_pos,\n content.detail_level,\n );\n const results = this.formatResult(res);\n return results;\n }\n\n /**\n * Check code for completeness submitted by a user.\n *\n * @param content The incoming message with the code to check.\n */\n async isComplete(content: { code: string }, parent: any) {\n await this.setup(parent);\n\n const res = this._kernel.is_complete(content.code);\n const results = this.formatResult(res);\n return results;\n }\n\n /**\n * Respond to the commInfoRequest.\n *\n * @param content The incoming message with the comm target name.\n */\n async commInfo(\n content: any,\n parent: any,\n ): Promise<KernelMessage.ICommInfoReplyMsg['content']> {\n await this.setup(parent);\n\n const res = this._kernel.comm_info(content.target_name);\n const results = this.formatResult(res);\n\n return {\n comms: results,\n status: 'ok',\n };\n }\n\n /**\n * Respond to the commOpen.\n *\n * @param content The incoming message with the comm open.\n */\n async commOpen(content: any, parent: any) {\n await this.setup(parent);\n\n const res = this._kernel.comm_manager.comm_open(\n this._pyodide.toPy(null),\n this._pyodide.toPy(null),\n this._pyodide.toPy(content),\n );\n const results = this.formatResult(res);\n\n return results;\n }\n\n /**\n * Respond to the commMsg.\n *\n * @param content The incoming message with the comm msg.\n */\n async commMsg(content: any, parent: any) {\n await this.setup(parent);\n\n const res = this._kernel.comm_manager.comm_msg(\n this._pyodide.toPy(null),\n this._pyodide.toPy(null),\n this._pyodide.toPy(content),\n );\n const results = this.formatResult(res);\n\n return results;\n }\n\n /**\n * Respond to the commClose.\n *\n * @param content The incoming message with the comm close.\n */\n async commClose(content: any, parent: any) {\n await this.setup(parent);\n\n const res = this._kernel.comm_manager.comm_close(\n this._pyodide.toPy(null),\n this._pyodide.toPy(null),\n this._pyodide.toPy(content),\n );\n const results = this.formatResult(res);\n\n return results;\n }\n\n /**\n * Resolve the input request by getting back the reply from the main thread\n *\n * @param content The incoming message with the reply\n */\n async inputReply(content: any, parent: any) {\n await this.setup(parent);\n\n this._resolveInputReply(content);\n }\n\n /**\n * Send a input request to the front-end.\n *\n * @param prompt the text to show at the prompt\n * @param password Is the request for a password?\n */\n async sendInputRequest(prompt: string, password: boolean) {\n const content = {\n prompt,\n password,\n };\n\n this._sendWorkerMessage({\n type: 'input_request',\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n content,\n });\n }\n\n async getpass(prompt: string) {\n prompt = typeof prompt === 'undefined' ? '' : prompt;\n await this.sendInputRequest(prompt, true);\n const replyPromise = new Promise((resolve) => {\n this._resolveInputReply = resolve;\n });\n const result: any = await replyPromise;\n return result['value'];\n }\n\n async input(prompt: string) {\n prompt = typeof prompt === 'undefined' ? '' : prompt;\n await this.sendInputRequest(prompt, false);\n const replyPromise = new Promise((resolve) => {\n this._resolveInputReply = resolve;\n });\n const result: any = await replyPromise;\n return result['value'];\n }\n\n /**\n * Send a comm message to the front-end.\n *\n * @param type The type of the comm message.\n * @param content The content.\n * @param metadata The metadata.\n * @param ident The ident.\n * @param buffers The binary buffers.\n */\n async sendComm(type: string, content: any, metadata: any, ident: any, buffers: any) {\n this._sendWorkerMessage({\n type: type,\n content: this.formatResult(content),\n metadata: this.formatResult(metadata),\n ident: this.formatResult(ident),\n buffers: this.formatResult(buffers),\n parentHeader: this.formatResult(this._kernel._parent_header)['header'],\n });\n }\n\n /**\n * Initialization options.\n */\n protected _options: IPyodideWorkerKernel.IOptions | null = null;\n /**\n * A promise that resolves when all initiaization is complete.\n */\n protected _initialized: Promise<void>;\n private _initializer: {\n reject: () => void;\n resolve: () => void;\n } | null = null;\n protected _pyodide: Pyodide.PyodideInterface = null as any;\n /** TODO: real typing */\n protected _localPath = '';\n protected _driveName = '';\n protected _kernel: any;\n protected _interpreter: any;\n protected _stdout_stream: any;\n protected _stderr_stream: any;\n protected _resolveInputReply: any;\n protected _driveFS: DriveFS | null = null;\n protected _sendWorkerMessage: (msg: any) => void = () => {};\n}\n"],
5
+ "mappings": "k3BAaiBA,EAAAA,SAAAA,OAAjB,SAAiBA,EAAQ,CAyCvB,SAAgBC,EACdC,EACAC,EACAC,EAAQ,EACRC,EAAO,GAAE,CAET,IAAIC,EAAIJ,EAAM,OACd,GAAII,IAAM,EACR,MAAO,GAELF,EAAQ,EACVA,EAAQ,KAAK,IAAI,EAAGA,EAAQE,CAAC,EAE7BF,EAAQ,KAAK,IAAIA,EAAOE,EAAI,CAAC,EAE3BD,EAAO,EACTA,EAAO,KAAK,IAAI,EAAGA,EAAOC,CAAC,EAE3BD,EAAO,KAAK,IAAIA,EAAMC,EAAI,CAAC,EAE7B,IAAIC,EACAF,EAAOD,EACTG,EAAOF,EAAO,GAAKC,EAAIF,GAEvBG,EAAOF,EAAOD,EAAQ,EAExB,QAASI,EAAI,EAAGA,EAAID,EAAM,EAAEC,EAAG,CAC7B,IAAIC,GAAKL,EAAQI,GAAKF,EACtB,GAAIJ,EAAMO,CAAC,IAAMN,EACf,OAAOM,CAEV,CACD,MAAO,GAhCOT,EAAA,aAAYC,EA2E5B,SAAgBS,EACdR,EACAC,EACAC,EAAQ,GACRC,EAAO,EAAC,CAER,IAAIC,EAAIJ,EAAM,OACd,GAAII,IAAM,EACR,MAAO,GAELF,EAAQ,EACVA,EAAQ,KAAK,I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AIV,GAAe,CACjC,GAAIM,EACJ,KAAAC,EACA,YAAAC,EACA,QAAAC,EACA,UAAW,KAAK,WAChB,WAAAJ,CACF,CAAC,EACDC,EAAG,UAAUD,CAAU,EACvBC,EAAG,MAAMI,EAAS,CAAC,EAAGL,CAAU,EAChCC,EAAG,MAAMD,CAAU,EACnB,KAAK,SAAWK,CAClB,CACF,CACF,EAEMC,EAAS,IAAIR,GAEbS,GAAoBjB,GAAU,qBAAqB,KAAKA,EAAS,EACvEgB,EAAO,iBAAiBC,EAAiB,EAEzCjB,GAAU,WAAagB,EAAO,WAAW,KAAKA,CAAM,EACpDhB,GAAU,QAAUgB,EAAO,QAAQ,KAAKA,CAAM,EAC9ChB,GAAU,SAAWgB,EAAO,SAAS,KAAKA,CAAM,EAChDhB,GAAU,QAAUgB,EAAO,QAAQ,KAAKA,CAAM,EAC9ChB,GAAU,WAAagB,EAAO,WAAW,KAAKA,CAAM,EACpDhB,GAAU,SAAWgB,EAAO,SAAS,KAAKA,CAAM,EAChDhB,GAAU,SAAWgB,EAAO,SAAS,KAAKA,CAAM,EAChDhB,GAAU,QAAUgB,EAAO,QAAQ,KAAKA,CAAM,EAC9ChB,GAAU,UAAYgB,EAAO,UAAU,KAAKA,CAAM,EAClDhB,GAAU,WAAagB,EAAO,WAAW,KAAKA,CAAM",
6
+ "names": ["ArrayExt", "firstIndexOf", "array", "value", "start", "stop", "n", "span", "i", "j", "lastIndexOf", "findFirstIndex", "fn", "findLastIndex", "d", "findFirstValue", "index", "findLastValue", "lowerBound", "begin", "half", "middle", "upperBound", "shallowEqual", "a", "b", "slice", "options", "step", "length", "result", "move", "fromIndex", "toIndex", "reverse", "rotate", "delta", "pivot", "fill", "insert", "removeAt", "removeFirstOf", "removeLastOf", "removeAllOf", "count", "removeFirstWhere", "removeLastWhere", "removeAllWhere", "chain", "objects", "object", "empty", "enumerate", "filter", "find", "findIndex", "min", "max", "minmax", "vmin", "vmax", "toArray", "toObject", "key", "each", "every", "some", "map", "range", "Private", "rangeLength", "reduce", "initial", "it", "first", "second", "accumulator", "next", "repeat", "once", "retro", "topologicSort", "edges", "sorted", "visited", "graph", "edge", "addEdge", "k", "visit", "fromNode", "toNode", "children", "node", "child", "stride", "StringExt", "findIndices", "source", "query", "indices", "matchSumOfSquares", "score", "matchSumOfDeltas", "last", "highlight", "cmp", "take", "item", "zip", "iters", "obj", "tuple", "JSONExt", "isPrimitive", "value", "isArray", "isObject", "deepEqual", "first", "second", "a1", "a2", "deepArrayEqual", "deepObjectEqual", "deepCopy", "deepArrayCopy", "deepObjectCopy", "i", "n", "key", "firstValue", "secondValue", "result", "subvalue", "MimeData", "mime", "data", "PluginRegistry", "options", "v", "id", "plugin", "_b", "_a", "Private", "plugins", "force", "required", "t", "optional", "services", "service", "error", "kind", "promises", "pluginId", "manifest", "downstream", "token", "reason", "PluginData", "_c", "_d", "a", "s", "p", "createPluginData", "ensureNoCycle", "dependencies", "visit", "visited", "trace", "findDependents", "edges", "add", "acc", "dep", "newEdges", "edge", "oldSize", "previousSize", "packagesOfInterest", "poi", "sorted", "topologicSort", "index", "candidate", "collectStartupPlugins", "collection", "PromiseDelegate", "resolve", "reject", "Token", "name", "description", "fallbackRandomValues", "buffer", "Random", "crypto", "uuid4Factory", "getRandomValues", "bytes", "lut", "UUID", "Signal", "sender", "slot", "thisArg", "Private", "args", "disconnectBetween", "receiver", "disconnectSender", "disconnectReceiver", "disconnectAll", "object", "clearData", "getExceptionHandler", "setExceptionHandler", "handler", "old", "Stream", "PromiseDelegate", "pending", "next", "err", "connect", "signal", "receivers", "receiversForSender", "findConnection", "senders", "sendersForReceiver", "connection", "disconnect", "scheduleCleanup", "emit", "i", "n", "invokeSlot", "dirtySet", "schedule", "connections", "find", "array", "cleanupDirtySet", "cleanupConnections", "ArrayExt", "isDeadConnection", "signaling_1", "ActivityMonitor", "options", "value", "sender", "args", "exports", "DEFAULT_MAX_SIZE", "LruCache", "options", "key", "item", "value", "exports", "MarkdownCodeBlocks", "markdownExtensions", "MarkdownCodeBlock", "startLine", "isMarkdown", "extension", "findMarkdownCodeBlocks", "text", "lines", "codeBlocks", "currentBlock", "lineIndex", "line", "lineContainsMarker", "constructingBlock", "firstIndex", "lastIndex", "exports", "require_minimist", "__commonJSMin", "exports", "module", "hasKey", "obj", "keys", "o", "key", "isNumber", "x", "isConstructorOrProto", "args", "opts", "flags", "aliases", "aliasIsBoolean", "y", "k", "defaults", "argv", "argDefined", "arg", "setKey", "value", "i", "lastKey", "setArg", "val", "notFlags", "next", "m", "letters", "broken", "j", "require_path_browserify", "__commonJSMin", "exports", "module", "assertPath", "path", "normalizeStringPosix", "allowAboveRoot", "res", "lastSegmentLength", "lastSlash", "dots", "code", "i", "lastSlashIndex", "_format", "sep", "pathObject", "dir", "base", "posix", "resolvedPath", "resolvedAbsolute", "cwd", "isAbsolute", "trailingSeparator", "joined", "arg", "from", "to", "fromStart", "fromEnd", "fromLen", "toStart", "toEnd", "toLen", "length", "lastCommonSep", "fromCode", "toCode", "out", "hasRoot", "end", "matchedSlash", "ext", "start", "extIdx", "firstNonSlashEnd", "startDot", "startPart", "preDotState", "ret", "require_requires_port", "__commonJSMin", "exports", "module", "port", "protocol", "require_querystringify", "__commonJSMin", "exports", "has", "undef", "decode", "input", "encode", "querystring", "query", "parser", "result", "part", "key", "value", "querystringify", "obj", "prefix", "pairs", "require_url_parse", "__commonJSMin", "exports", "module", "required", "qs", "controlOrWhitespace", "CRHTLF", "slashes", "port", "protocolre", "windowsDriveLetter", "trimLeft", "str", "rules", "address", "url", "isSpecial", "ignore", "lolcation", "loc", "globalVar", "location", "finaldestination", "type", "key", "Url", "scheme", "extractProtocol", "match", "protocol", "forwardSlashes", "otherSlashes", "slashesCount", "rest", "resolve", "relative", "base", "path", "i", "last", "unshift", "up", "parser", "extracted", "parse", "instruction", "index", "instructions", "set", "part", "value", "fn", "char", "ins", "toString", "stringify", "query", "host", "result", "path_1", "url_parse_1", "__importDefault", "URLExt", "parse", "url", "a", "getHostName", "normalize", "join", "parts", "u", "isSchemaLess", "prefix", "path", "encodeParts", "objectToQueryString", "value", "keys", "key", "content", "queryStringToObject", "acc", "val", "isLocal", "allowRoot", "protocol", "exports", "el", "e", "key", "name", "value", "last", "options", "path", "mode", "_a", "workspace", "_b", "labOrDoc", "_c", "treePath", "_d", "baseUrl", "wsUrl", "format", "download", "notebookPath", "url", "notebookVersion", "val", "Extension", "populate", "raw", "error", "isDeferred", "id", "separatorIndex", "extName", "isDisabled", "path_1", "PathExt", "join", "paths", "path", "removeSlash", "joinWithLeadingSlash", "basename", "ext", "dirname", "dir", "extname", "normalize", "resolve", "parts", "relative", "from", "to", "normalizeExtension", "extension", "exports", "exports", "signalToPromise", "coreutils_1", "signal", "timeout", "waitForSignal", "cleanup", "slot", "sender", "args", "Text", "HAS_SURROGATES", "jsIndexToCharIndex", "jsIdx", "text", "charIdx", "i", "charCode", "nextCharCode", "charIndexToJsIndex", "camelCase", "str", "upper", "match", "p1", "p2", "titleCase", "word", "exports", "UNITS", "Time", "formatHuman", "value", "format", "lang", "formatter", "delta", "unit", "amount", "exports", "__exportStar", "exports", "exports", "createMessage", "isStreamMsg", "isDisplayDataMsg", "isUpdateDisplayDataMsg", "isExecuteInputMsg", "isExecuteResultMsg", "isErrorMsg", "isStatusMsg", "isClearOutputMsg", "isDebugEventMsg", "isCommOpenMsg", "isCommCloseMsg", "isCommMsgMsg", "isInfoRequestMsg", "isExecuteReplyMsg", "isDebugRequestMsg", "isDebugReplyMsg", "isInputRequestMsg", "isInputReplyMsg", "coreutils_1", "options", "_a", "_b", "_c", "_d", "_e", "_f", "msg", "supportedKernelWebSocketProtocols", "exports", "serialize", "deserialize", "KernelMessage", "__importStar", "msg", "protocol", "Private", "data", "deserializeV1KernelWebsocketJupyterOrg", "binMsg", "offsetNumber", "offsets", "i", "decoder", "channel", "header", "parent_header", "metadata", "content", "buffers", "serializeV1KernelWebsocketJupyterOrg", "parentHeader", "encoder", "channelEncoded", "headerEncoded", "parentHeaderEncoded", "metadataEncoded", "contentEncoded", "binMsgNoBuff", "length", "buffersByteLength", "buffer", "word", "deserializeDefault", "value", "deserializeBinary", "serializeDefault", "_a", "serializeBinary", "buf", "nbufs", "jsonBytes", "start", "stop", "origBuffers", "jsonUtf8", "b", "msgBuf", "view", "exports", "coreutils_1", "serialize_1", "WEBSOCKET", "ServerConnection", "makeSettings", "options", "Private", "makeRequest", "url", "init", "settings", "ResponseError", "response", "data", "message", "traceback", "e", "NetworkError", "original", "exports", "pageBaseUrl", "pageWsUrl", "baseUrl", "wsUrl", "appendTokenConfig", "appendToken", "_a", "handleRequest", "request", "authenticated", "xsrfToken", "getCookie", "name", "cookie", "matches", "signaling_1", "serverconnection_1", "BaseManager", "options", "_a", "exports", "coreutils_1", "__1", "SERVICE_CONFIG_URL", "ConfigSectionManager", "options", "_a", "section", "DefaultConfigSection", "exports", "ConfigSection", "create", "_configSectionManager", "_setConfigSectionManager", "manager", "settings", "response", "newdata", "init", "ConfigWithDefaults", "_b", "key", "data", "value", "d", "d2", "ConnectionStatus", "exports", "DisposableDelegate", "fn", "ObservableDisposableDelegate", "Signal", "DisposableSet", "item", "from", "items", "set", "ObservableDisposableSet", "exports", "validateProperty", "object", "name", "typeName", "values", "value", "valid", "v", "exports", "validateContentsModel", "validateCheckpointModel", "validate_1", "model", "coreutils_1", "disposable_1", "signaling_1", "__1", "validate", "__importStar", "SERVICE_DRIVE_URL", "FILES_URL", "Contents", "validateContentsModel", "contents", "validateCheckpointModel", "checkpoint", "exports", "ContentsManager", "options", "serverSettings", "_a", "_b", "Drive", "drive", "path", "provider", "parts", "firstParts", "root", "driveName", "localPath", "resolved", "contentsModel", "listing", "item", "globalPath", "newPath", "drive1", "path1", "drive2", "path2", "fromFile", "toDir", "checkpointID", "sender", "args", "newValue", "oldValue", "_c", "restContentProvider", "RestContentProvider", "ContentProviderRegistry", "registry", "change", "baseUrl", "url", "cookie", "xsrfTokenMatch", "fullUrl", "body", "Private", "settings", "init", "response", "data", "oldLocalPath", "newLocalPath", "i", "normalizeExtension", "extension", "identifier", "fileChangedProxy", "_provider", "content", "hash", "params", "Poll", "options", "Signal", "PromiseDelegate", "_a", "Private", "frequency", "max", "JSONExt", "backoff", "interval", "standby", "_", "phase", "next", "pending", "scheduled", "state", "execute", "resolved", "rejected", "sleep", "last", "growth", "random", "getRandomIntInclusive", "min", "RateLimiter", "fn", "limit", "args", "payload", "Debouncer", "Throttler", "idle", "coreutils_1", "polling_1", "signaling_1", "serverconnection_1", "SERVICE_EVENTS_URL", "EventManager", "options", "_a", "socket", "event", "serverSettings", "baseUrl", "makeRequest", "ResponseError", "url", "init", "response", "_", "reject", "appendToken", "token", "WebSocket", "wsUrl", "stream", "msg", "exports", "exports", "validateMessage", "validateModel", "validateModels", "validate_1", "HEADER_FIELDS", "IOPUB_CONTENT_FIELDS", "validateHeader", "header", "i", "msg", "validateIOPubContent", "fields", "names", "content", "args", "model", "models", "d", "exports", "listRunning", "startNew", "restartKernel", "interruptKernel", "shutdownKernel", "getKernelModel", "serverconnection_1", "coreutils_1", "validate_1", "settings", "url", "response", "data", "options", "init", "id", "msg", "KernelAPIClient", "_a", "disposable_1", "KernelMessage", "__importStar", "CommHandler", "target", "id", "kernel", "disposeCb", "cb", "data", "metadata", "buffers", "msg", "disposeOnDone", "future", "onClose", "ioMsg", "exports", "coreutils_1", "disposable_1", "KernelMessage", "__importStar", "KernelFutureHandler", "cb", "msg", "expectReply", "disposeOnDone", "kernel", "Private", "hook", "content", "parent_header", "reply", "stdin", "process", "iopub", "flag", "exports", "KernelControlFutureHandler", "KernelShellFutureHandler", "defer", "HookList", "index", "processing", "continueHandling", "i", "err", "numNulls", "len", "KernelFutureFlag", "exports", "validateSpecModel", "validateSpecModels", "validate_1", "data", "spec", "metadata", "env", "keys", "kernelspecs", "defaultSpec", "i", "ks", "exports", "getSpecs", "serverconnection_1", "validate_1", "coreutils_1", "KERNELSPEC_SERVICE_URL", "settings", "url", "response", "data", "coreutils_1", "polling_1", "signaling_1", "restapi", "__importStar", "basemanager_1", "KernelSpecManager", "options", "_", "_a", "specs", "exports", "KernelSpec", "__importStar", "exports", "KernelSpecAPI", "__exportStar", "coreutils_1", "coreutils_2", "signaling_1", "__1", "comm_1", "KernelMessage", "__importStar", "future_1", "validate", "kernelspec_1", "restapi_1", "KERNEL_INFO_TIMEOUT", "RESTARTING_KERNEL_SESSION", "STARTING_KERNEL_SESSION", "KernelConnection", "_KernelConnection", "options", "useProtocols", "settings", "partialUrl", "display", "url", "token", "supportedProtocols", "alreadyCalledOnclose", "getKernelModel", "evt", "model", "err", "_a", "_b", "timeout", "Private", "earlyClose", "msg", "error", "_c", "_d", "_e", "_f", "value", "specs", "cleanup", "future", "expectReply", "disposeOnDone", "ctor", "msgId", "displayIds", "displayId", "msgIds", "idx", "queue", "result", "fulfill", "sender", "status", "reply", "e", "supportedFeatures", "content", "metadata", "defaults", "parent_header", "targetName", "commId", "comm", "callback", "hook", "parentIds", "updateMsg", "parentId", "onClose", "onMsg", "connectionStatus", "restarting", "p", "sendPendingCalled", "sendPendingOnce", "timeoutHandle", "handled", "parentHeader", "owned", "executionState", "exports", "logKernelStatus", "kernel", "handleShellMessage", "loadObject", "name", "moduleName", "registry", "resolve", "reject", "mod", "getRandomIntInclusive", "min", "max", "polling_1", "signaling_1", "__1", "basemanager_1", "restapi_1", "default_1", "KernelManager", "options", "_a", "_b", "x", "id", "handleComms", "kc", "kernelConnection", "createOptions", "connectOptions", "model", "models", "err", "existing", "status", "exports", "NoopManager", "Kernel", "__importStar", "exports", "KernelMessage", "KernelAPI", "default_1", "__exportStar", "coreutils_1", "serverconnection_1", "BUILD_SETTINGS_URL", "BuildManager", "options", "_a", "baseUrl", "appUrl", "_url", "serverSettings", "response", "data", "init", "message", "exports", "coreutils_1", "serverconnection_1", "coreutils_2", "NBCONVERT_SETTINGS_URL", "NbConvertManager", "options", "_a", "base", "url", "serverSettings", "response", "data", "exportList", "key", "mimeType", "force", "exports", "exports", "validateModel", "updateLegacySessionModel", "validateModels", "validate_1", "validate_2", "data", "models", "d", "exports", "listRunning", "getSessionUrl", "shutdownSession", "getSessionModel", "startSession", "updateSession", "serverconnection_1", "coreutils_1", "validate_1", "settings", "url", "response", "data", "m", "baseUrl", "id", "servicesBase", "result", "init", "msg", "_a", "options", "model", "SessionAPIClient", "signaling_1", "__1", "coreutils_1", "restapi_1", "SessionConnection", "options", "_a", "_b", "_c", "_d", "_e", "model", "oldModel", "oldValue", "newValue", "path", "name", "type", "kc", "sender", "state", "msg", "args", "body", "exports", "polling_1", "signaling_1", "serverconnection_1", "basemanager_1", "default_1", "restapi_1", "SessionManager", "options", "_a", "_b", "x", "sessionConnection", "createOptions", "connectOptions", "model", "id", "path", "matches", "value", "m", "models", "err", "existing", "_c", "_d", "sc", "exports", "NoopManager", "Session", "__importStar", "exports", "SessionAPI", "__exportStar", "DataConnector", "query", "id", "value", "exports", "AttachedProperty", "options", "Private", "owner", "value", "map", "oldValue", "newValue", "create", "coerce", "compare", "changed", "clearData", "id", "ensureMap", "coreutils_1", "properties_1", "signaling_1", "RestorablePool", "options", "obj", "warning", "Private", "connector", "objName", "name", "data", "_b", "_a", "fn", "values", "value", "filtered", "command", "registry", "when", "namespace", "promises", "saved", "id", "index", "args", "injected", "oldName", "newName", "exports", "signaling_1", "StateDB", "_StateDB", "options", "connector", "transform", "transformation", "contents", "type", "id", "namespace", "value", "ids", "values", "acc", "val", "idx", "key", "exports", "Connector", "coreutils_1", "exports", "__exportStar", "exports", "coreutils_1", "statedb_1", "serverconnection_1", "SERVICE_SETTINGS_URL", "SettingManager", "options", "_a", "id", "serverSettings", "baseUrl", "appUrl", "makeRequest", "ResponseError", "base", "url", "Private", "response", "query", "json", "ids", "_b", "plugin", "values", "_d", "_c", "raw", "init", "exports", "idsOnly", "idsOnlyParam", "settingsBase", "result", "exports", "isAvailable", "startNew", "listRunning", "shutdownTerminal", "coreutils_1", "serverconnection_1", "settings", "name", "cwd", "Private", "url", "init", "response", "data", "workspacesBase", "msg", "_a", "errorIfNotAvailable", "restapi_1", "exports", "coreutils_1", "coreutils_2", "signaling_1", "__1", "restapi_1", "TerminalConnection", "_TerminalConnection", "options", "name", "settings", "url", "token", "event", "data", "_a", "message", "queue", "msg", "result", "fulfill", "sender", "status", "timeout", "Private", "connectionStatus", "exports", "getTermUrl", "baseUrl", "getRandomIntInclusive", "min", "max", "polling_1", "signaling_1", "__1", "basemanager_1", "restapi_1", "default_1", "TerminalManager", "options", "_", "_a", "x", "terminalConnection", "model", "name", "models", "err", "_b", "names", "tc", "exports", "NoopManager", "id", "Terminal", "__importStar", "exports", "TerminalAPI", "__exportStar", "coreutils_1", "coreutils_2", "polling_1", "signaling_1", "serverconnection_1", "basemanager_1", "SERVICE_USER_URL", "SERVICE_ID", "UserManager", "options", "_", "_a", "baseUrl", "makeRequest", "ResponseError", "url", "response", "oldUser", "newUser", "identity", "localStorage", "data", "localUser", "Private", "exports", "userColors", "coreutils_1", "statedb_1", "serverconnection_1", "SERVICE_WORKSPACES_URL", "WorkspaceManager", "options", "_a", "id", "serverSettings", "baseUrl", "appUrl", "makeRequest", "ResponseError", "base", "url", "Private", "response", "workspace", "init", "exports", "workspacesBase", "result", "signaling_1", "builder_1", "contents_1", "event_1", "kernel_1", "kernelspec_1", "nbconvert_1", "serverconnection_1", "session_1", "setting_1", "terminal_1", "user_1", "workspace_1", "ServiceManager", "options", "defaultDrive", "serverSettings", "_a", "standby", "_b", "normalized", "readyList", "sender", "err", "exports", "coreutils_1", "exports", "__exportStar", "exports", "require_Mime", "__commonJSMin", "exports", "module", "Mime", "typeMap", "force", "type", "extensions", "t", "i", "ext", "path", "last", "hasPath", "require_standard", "__commonJSMin", "exports", "module", "require_other", "__commonJSMin", "exports", "module", "require_mime", "__commonJSMin", "exports", "module", "Mime", "import_coreutils", "import_mime", "MIME", "FILE", "IBroadcastChannelWrapper", "init_tokens", "__esmMin", "TYPES", "getType", "ext", "defaultType", "fileType", "fileExt", "mime", "hasFormat", "fileFormat", "import_coreutils", "import_services", "import_signaling", "DEFAULT_STORAGE_NAME", "DRIVE_NAME", "N_CHECKPOINTS", "encoder", "decoder", "BrowserStorageDrive", "Private", "init_drive", "__esmMin", "init_tokens", "options", "data", "byte", "_a", "path", "driver", "type", "_b", "created", "dirname", "basename", "extname", "item", "name", "file", "counter", "MIME", "ext", "_c", "mimetype", "FILE", "format", "key", "toDir", "toPath", "folder", "storage", "serverItem", "model", "contentMap", "serverContents", "content", "oldLocalPath", "newLocalPath", "modified", "newFile", "child", "chunk", "appendChunk", "originalContent", "lastChunk", "contentBinaryString", "slashed", "toDelete", "checkpoints", "copies", "id", "checkpointID", "newContent", "newContentBinaryString", "binaryString", "bytes", "i", "fileUrl", "response", "contentText", "contentBuffer", "contentBytes", "apiURL", "json", "err", "counters", "instanceOfStream", "nodeOrStream", "DIR_MODE", "FILE_MODE", "SEEK_CUR", "SEEK_END", "init_emscripten", "__esmMin", "DRIVE_SEPARATOR", "DRIVE_API_PATH", "BLOCK_SIZE", "encoder", "decoder", "flagNeedsWrite", "DriveFSEmscriptenStreamOps", "DriveFSEmscriptenNodeOps", "ContentsAPI", "ServiceWorkerContentsAPI", "DriveFS", "init_drivefs", "__esmMin", "init_emscripten", "fs", "stream", "path", "flags", "parsedFlags", "needsWrite", "buffer", "offset", "length", "position", "size", "_a", "oldData", "whence", "nodeOrStream", "instanceOfStream", "value", "node", "attr", "key", "file", "parent", "name", "result", "mode", "dev", "newDir", "newName", "oldNode", "newDirNode", "oldPath", "driveName", "mountpoint", "FS", "ERRNO_CODES", "newPath", "dirlist", "response", "serializedContent", "format", "binString", "len", "data", "i", "binary", "stats", "baseUrl", "xhr", "e", "options", "mount", "parts", "currentNode", "import_coreutils", "DriveContentsProcessor", "init_drivecontents", "__esmMin", "init_drivefs", "options", "request", "model", "response", "subcontent", "defaultDate", "BLOCK_SIZE", "BroadcastChannelWrapper", "init_broadcast", "__esmMin", "init_drivefs", "init_drivecontents", "options", "event", "request", "response", "DriveContentsProcessor", "DRIVE_API_PATH", "lib_exports", "__export", "BLOCK_SIZE", "BroadcastChannelWrapper", "BrowserStorageDrive", "ContentsAPI", "DIR_MODE", "DRIVE_API_PATH", "DRIVE_NAME", "DRIVE_SEPARATOR", "DriveContentsProcessor", "DriveFS", "DriveFSEmscriptenNodeOps", "DriveFSEmscriptenStreamOps", "FILE", "FILE_MODE", "IBroadcastChannelWrapper", "MIME", "SEEK_CUR", "SEEK_END", "ServiceWorkerContentsAPI", "instanceOfStream", "init_lib", "__esmMin", "init_drive", "init_drivefs", "init_tokens", "init_broadcast", "init_emscripten", "init_drivecontents", "FUNCTION", "CHANNEL", "MAIN", "THREAD", "GET", "HAS", "SET", "isArray", "SharedArrayBuffer", "window", "notify", "wait", "waitAsync", "postPatched", "buffer", "onmessage", "w", "ids", "resolvers", "postMessage", "listener", "event", "_a", "details", "CHANNEL", "id", "sb", "data", "rest", "resolve", "buff", "i", "as", "Int32Array", "Map", "Uint16Array", "I32_BYTES", "UI16_BYTES", "waitInterrupt", "sb", "delay", "handler", "wait", "buffers", "context", "syncResult", "fn", "uid", "coincident", "self", "parse", "stringify", "transform", "interrupt", "sendMessage", "postPatched", "post", "transfer", "args", "CHANNEL", "FUNCTION", "decoder", "waitFor", "isAsync", "waitAsync", "seppuku", "HAS", "_", "action", "GET", "id", "SharedArrayBuffer", "deadlock", "length", "bytes", "SET", "actions", "callback", "type", "results", "event", "_a", "details", "isArray", "rest", "error", "result", "serialized", "ui16a", "i", "notify", "esm_default", "init_lib", "PyodideRemoteKernel", "resolve", "reject", "options", "_a", "parts", "pyodideUrl", "indexUrl", "loadPyodide", "pipliteWheelUrl", "disablePyPIFallback", "pipliteUrls", "loadPyodideOptions", "preloaded", "toLoad", "scriptLines", "pkgName", "globals", "mountpoint", "FS", "PATH", "ERRNO_CODES", "baseUrl", "DriveFS", "driveFS", "obj", "out", "value", "key", "res", "m", "callback", "parent", "content", "publishExecutionResult", "prompt_count", "data", "metadata", "bundle", "publishExecutionError", "ename", "evalue", "traceback", "clearOutputCallback", "wait", "displayDataCallback", "transient", "updateDisplayDataCallback", "publishStreamCallback", "name", "text", "results", "prompt", "password", "type", "ident", "buffers", "workerAPI", "esm_default", "SharedBufferContentsAPI", "ContentsAPI", "data", "PyodideDriveFS", "DriveFS", "options", "PyodideCoincidentKernel", "PyodideRemoteKernel", "mountpoint", "FS", "PATH", "ERRNO_CODES", "baseUrl", "driveFS", "worker", "sendWorkerMessage"]
7
7
  }