RetroArch/pkg/emscripten/browserfs.js.map

143 lines
1.0 MiB
Plaintext
Raw Normal View History

{
"version": 3,
"sources": [
"node_modules/grunt-browserify/node_modules/browserify/node_modules/browser-pack/_prelude.js",
"node_modules/async/lib/async.js",
"node_modules\\bfs-buffer\\ts\\buffer.ts",
"node_modules\\bfs-buffer\\ts\\buffer_core.ts",
"node_modules\\bfs-buffer\\ts\\buffer_core_array.ts",
"node_modules\\bfs-buffer\\ts\\buffer_core_arraybuffer.ts",
"node_modules\\bfs-buffer\\ts\\buffer_core_imagedata.ts",
"node_modules\\bfs-buffer\\ts\\extended_ascii.ts",
"node_modules\\bfs-buffer\\ts\\string_util.ts",
"node_modules\\bfs-buffer\\ts\\util.ts",
"node_modules\\bfs-path\\js\\node_modules\\bfs-path\\ts\\path.ts",
"node_modules\\bfs-process\\ts\\index.ts",
"node_modules\\bfs-process\\js\\node_modules\\bfs-process\\ts\\process.ts",
"node_modules\\bfs-process\\js\\node_modules\\bfs-process\\ts\\tty.ts",
"node_modules/browserify/node_modules/events/events.js",
"node_modules/browserify/node_modules/inherits/inherits_browser.js",
"node_modules/browserify/node_modules/isarray/index.js",
"node_modules/browserify/node_modules/readable-stream/duplex.js",
"node_modules/browserify/node_modules/readable-stream/lib/_stream_duplex.js",
"node_modules/browserify/node_modules/readable-stream/lib/_stream_passthrough.js",
"node_modules/browserify/node_modules/readable-stream/lib/_stream_readable.js",
"node_modules/browserify/node_modules/readable-stream/lib/_stream_transform.js",
"node_modules/browserify/node_modules/readable-stream/lib/_stream_writable.js",
"node_modules/browserify/node_modules/readable-stream/node_modules/core-util-is/lib/util.js",
"node_modules/browserify/node_modules/readable-stream/node_modules/process-nextick-args/index.js",
"node_modules/browserify/node_modules/readable-stream/node_modules/util-deprecate/browser.js",
"node_modules/browserify/node_modules/readable-stream/passthrough.js",
"node_modules/browserify/node_modules/readable-stream/readable.js",
"node_modules/browserify/node_modules/readable-stream/transform.js",
"node_modules/browserify/node_modules/readable-stream/writable.js",
"node_modules/browserify/node_modules/stream-browserify/index.js",
"node_modules/browserify/node_modules/string_decoder/index.js",
"node_modules/grunt-browserify/node_modules/browserify/node_modules/browser-resolve/empty.js",
"node_modules/grunt-browserify/node_modules/browserify/node_modules/insert-module-globals/node_modules/is-buffer/index.js",
"node_modules/pako/dist/pako_inflate.min.js",
"src/backend/AsyncMirror.ts",
"src/backend/Dropbox.ts",
"src/backend/FolderAdapter.ts",
"src/backend/HTML5FS.ts",
"src/backend/InMemory.ts",
"src/backend/IndexedDB.ts",
"src/backend/LocalStorage.ts",
"src/backend/MountableFileSystem.ts",
"src/backend/OverlayFS.ts",
"src/backend/WorkerFS.ts",
"src/backend/XmlHttpRequest.ts",
"src/backend/ZipFS.ts",
"src/browserify_main.ts",
"src/core/FS.ts",
"src/core/api_error.ts",
"src/core/backends.ts",
"src/core/browserfs.ts",
"src/core/file.ts",
"src/core/file_flag.ts",
"src/core/file_system.ts",
"src/core/global.ts",
"src/core/node_fs.ts",
"src/core/node_fs_stats.ts",
"src/core/util.ts",
"src/generic/emscripten_fs.ts",
"src/generic/file_index.ts",
"src/generic/inode.ts",
"src/generic/key_value_filesystem.ts",
"src/generic/preload_file.ts",
"src/generic/xhr.ts",
"src/main.ts"
],
"names": [],
"mappings": "AAAA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA
"file": "generated.js",
"sourceRoot": "",
"sourcesContent": [
"(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})",
"/*!\n * async\n * https://github.com/caolan/async\n *\n * Copyright 2010-2014 Caolan McMahon\n * Released under the MIT license\n */\n(function () {\n\n var async = {};\n function noop() {}\n function identity(v) {\n return v;\n }\n function toBool(v) {\n return !!v;\n }\n function notId(v) {\n return !v;\n }\n\n // global on the server, window in the browser\n var previous_async;\n\n // Establish the root object, `window` (`self`) in the browser, `global`\n // on the server, or `this` in some virtual machines. We use `self`\n // instead of `window` for `WebWorker` support.\n var root = typeof self === 'object' && self.self === self && self ||\n typeof global === 'object' && global.global === global && global ||\n this;\n\n if (root != null) {\n previous_async = root.async;\n }\n\n async.noConflict = function () {\n root.async = previous_async;\n return async;\n };\n\n function only_once(fn) {\n return function() {\n if (fn === null) throw new Error(\"Callback was already called.\");\n fn.apply(this, arguments);\n fn = null;\n };\n }\n\n function _once(fn) {\n return function() {\n if (fn === null) return;\n fn.apply(this, arguments);\n fn = null;\n };\n }\n\n //// cross-browser compatiblity functions ////\n\n var _toString = Object.prototype.toString;\n\n var _isArray = Array.isArray || function (obj) {\n return _toString.call(obj) === '[object Array]';\n };\n\n // Ported from underscore.js isObject\n var _isObject = function(obj) {\n var type = typeof obj;\n return type === 'function' || type === 'object' && !!obj;\n };\n\n function _isArrayLike(arr) {\n return _isArray(arr) || (\n // has a positive integer length property\n typeof arr.length === \"number\" &&\n arr.length >= 0 &&\n arr.length % 1 === 0\n );\n }\n\n function _arrayEach(arr, iterator) {\n var index = -1,\n length = arr.length;\n\n while (++index < length) {\n iterator(arr[index], index, arr);\n }\n }\n\n function _map(arr, iterator) {\n var index = -1,\n length = arr.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iterator(arr[index], index, arr);\n }\n return result;\n }\n\n function _range(count) {\n return _map(Array(count), function (v, i) { return i; });\n }\n\n function _reduce(arr, iterator, memo) {\n _arrayEach(arr, function (x, i, a) {\n memo = iterator(memo, x, i, a);\n });\n return memo;\n }\n\n function _forEachOf(object, iterator) {\n _arrayEach(_keys(object), function (key) {\n iterator(object[key], key);\n });\n }\n\n function _indexOf(arr, item) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] === item) return i;\n }\n return -1;\n }\n\n var _keys = Object.keys || function (obj) {\n var keys = [];\n for (var k in obj) {\n if (obj.hasOwnProperty(k)) {\n keys.push(k);\n }\n }\n return keys;\n };\n\n function _keyIterator(coll) {\n var i = -1;\n var len;\n var keys;\n if (_isArrayLike(coll)) {\n len = coll.length;\n return function next() {\n i++;\n return i < len ? i : null;\n };\n } else {\n keys = _keys(coll);\n len = keys.length;\n return function next() {\n i++;\n return i < len ? keys[i] : null;\n };\n }\n }\n\n // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)\n // This accumulates the arguments passed into an array, after a given
"/**\n * Buffer module. Exports an appropriate version of Buffer for the current\n * platform.\n */\nimport buffer_core = require('./buffer_core');\nimport BufferCoreArray = require('./buffer_core_array');\nimport BufferCoreArrayBuffer = require('./buffer_core_arraybuffer');\nimport BufferCoreImageData = require('./buffer_core_imagedata');\nimport {StringUtil, FindUtil} from './string_util';\nimport {isArrayBuffer, isArrayBufferView} from './util';\n\n// BC implementations earlier in the array are preferred.\nvar BufferCorePreferences: buffer_core.BufferCoreImplementation[] = [\n BufferCoreArrayBuffer,\n BufferCoreImageData,\n BufferCoreArray\n];\n\nvar PreferredBufferCore: buffer_core.BufferCoreImplementation = (function(): buffer_core.BufferCoreImplementation {\n var i: number, bci: buffer_core.BufferCoreImplementation;\n for (i = 0; i < BufferCorePreferences.length; i++) {\n bci = BufferCorePreferences[i];\n if (bci.isAvailable()) return bci;\n }\n // Should never happen; Array works in all browsers.\n throw new Error(\"This browser does not support any available BufferCore implementations.\");\n})();\n\n/**\n * Checks integer writes.\n */\nfunction checkInt(buffer: NodeBuffer, value: number, offset: number, ext: number, max: number, min: number) {\n if (value > max || value < min) {\n throw new TypeError('value is out of bounds');\n } else if (offset + ext > buffer.length) {\n throw new RangeError('index out of range');\n }\n}\n\n/**\n * Checks floating point writes.\n */\nfunction checkFloat(buffer: NodeBuffer, value: number, offset: number, ext: number) {\n if (offset + ext > buffer.length) {\n throw new RangeError('index out of range');\n }\n}\n\n/**\n * Check offset into buffer.\n */\nfunction checkOffset(offset: number, ext: number, length: number): void {\n if (offset + ext > length) {\n throw new RangeError('index out of range');\n }\n}\n\n/**\n * MAX_INT for various byte sizes.\n */\nconst enum MaxInt {\n INT0 = 0,\n INT8 = 0x7F,\n INT16 = 0x7FFF,\n INT24 = 0x7FFFFF,\n INT32 = 0x7FFFFFFF,\n INT40 = 0x7FFFFFFFFF,\n INT48 = 0x7FFFFFFFFFFF\n}\n\n/**\n * MIN_INT for various byte sizes.\n */\nconst enum MinInt {\n INT0 = 0,\n INT8 = -0x80,\n INT16 = -0x8000,\n INT24 = -0x800000,\n INT32 = -0x80000000,\n INT40 = -0x8000000000,\n INT48 = -0x800000000000\n}\n\n/**\n * MAX_UINT for various sizes.\n */\nconst enum MaxUInt {\n INT0 = 0,\n INT8 = 0xFF,\n INT16 = 0xFFFF,\n INT24 = 0xFFFFFF,\n INT32 = 0xFFFFFFFF,\n INT40 = 0xFFFFFFFFFF,\n INT48 = 0xFFFFFFFFFFFF\n}\n\nvar byte2maxint: {[byte: number]: number} = {};\nbyte2maxint[0] = MaxInt.INT0;\nbyte2maxint[1] = MaxInt.INT8;\nbyte2maxint[2] = MaxInt.INT16;\nbyte2maxint[3] = MaxInt.INT24;\nbyte2maxint[4] = MaxInt.INT32;\nbyte2maxint[5] = MaxInt.INT40;\nbyte2maxint[6] = MaxInt.INT48;\nvar byte2minint: {[byte: number]: number} = {};\nbyte2minint[0] = MinInt.INT0;\nbyte2minint[1] = MinInt.INT8;\nbyte2minint[2] = MinInt.INT16;\nbyte2minint[3] = MinInt.INT24;\nbyte2minint[4] = MinInt.INT32;\nbyte2minint[5] = MinInt.INT40;\nbyte2minint[6] = MinInt.INT48;\nvar byte2maxuint: {[byte: number]: number} = {};\nbyte2maxuint[0] = MaxUInt.INT0;\nbyte2maxuint[1] = MaxUInt.INT8;\nbyte2maxuint[2] = MaxUInt.INT16;\nbyte2maxuint[3] = MaxUInt.INT24;\nbyte2maxuint[4] = MaxUInt.INT32;\nbyte2maxuint[5] = MaxUInt.INT40;\nbyte2maxuint[6] = MaxUInt.INT48;\n\n/**\n * We extend Node's buffer interface to account for differences in the browser\n * environment.\n */\nexport interface BFSBuffer extends NodeBuffer {\n // It's not tractable to emulate array indexing by defining numeric properties\n // for each index of the buffer, so we have getters/setters.\n get(index: number): number;\n set(index: number, value: number): void;\n // Used by backends to get the backing data.\n getBufferCore(): buffer_core.BufferCore;\n // Used by backends in conjunction with getBufferCore() and the length\n // property to determine which segment of the backing memory is applicable\n // for a given operation.\n getOffset(): number;\n // Like Buffer.slice,
"/**\n * !!!NOTE: This file should not depend on any other file!!!\n *\n * Buffers are referenced everywhere, so it can cause a circular dependency.\n */\n\nvar FLOAT_POS_INFINITY = Math.pow(2, 128);\nvar FLOAT_NEG_INFINITY = -1 * FLOAT_POS_INFINITY;\nvar FLOAT_POS_INFINITY_AS_INT = 0x7F800000;\nvar FLOAT_NEG_INFINITY_AS_INT = -8388608;\nvar FLOAT_NaN_AS_INT = 0x7fc00000;\n\n/**\n * The core data-writing and reading methods of any buffer.\n */\nexport interface BufferCore {\n /**\n * Get the size of this buffer core, in bytes.\n */\n getLength(): number;\n /**\n * Writes bottom 8 bits of the given integer at the provided index.\n */\n writeInt8(i: number, data: number): void;\n /**\n * Writes bottom 16 bits of the given integer at the provided index.\n * Little endian.\n */\n writeInt16LE(i: number, data: number): void;\n /**\n * Writes bottom 16 bits of the given integer at the provided index.\n * Big endian.\n */\n writeInt16BE(i: number, data: number): void;\n /**\n * Writes all 32 bits of the given integer at the provided index.\n * Little endian.\n */\n writeInt32LE(i: number, data: number): void;\n /**\n * Writes all 32 bits of the given integer at the provided index.\n * Big endian.\n */\n writeInt32BE(i: number, data: number): void;\n /**\n * Writes the number as an 8 bit unsigned integer.\n */\n writeUInt8(i: number, data: number): void;\n /**\n * Writes the number as a 16 bit unsigned integer.\n * Little endian.\n */\n writeUInt16LE(i: number, data: number): void;\n /**\n * Writes the number as a 16 bit unsigned integer.\n * Big endian.\n */\n writeUInt16BE(i: number, data: number): void;\n /**\n * Writes the number as a 32 bit unsigned integer.\n * Little endian.\n */\n writeUInt32LE(i: number, data: number): void;\n /**\n * Writes the number as a 32 bit unsigned integer.\n * Big endian.\n */\n writeUInt32BE(i: number, data: number): void;\n /**\n * Writes the number as a 32-bit float.\n * Little endian.\n */\n writeFloatLE(i: number, data: number): void;\n /**\n * Writes the number as a 32-bit float.\n * Big endian.\n */\n writeFloatBE(i: number, data: number): void;\n /**\n * Writes the number as a 64-bit float.\n * Little endian.\n */\n writeDoubleLE(i: number, data: number): void;\n /**\n * Writes the number as a 64-bit float.\n * Big endian.\n */\n writeDoubleBE(i: number, data: number): void;\n /**\n * Reads the byte at the given index.\n */\n readInt8(i: number): number;\n /**\n * Reads the two bytes at the given index (little endian).\n */\n readInt16LE(i: number): number;\n /**\n * Reads the two bytes at the given index (big endian).\n */\n readInt16BE(i: number): number;\n /**\n * Reads the four bytes at the given index (little endian).\n */\n readInt32LE(i: number): number;\n /**\n * Reads the four bytes at the given index (big endian).\n */\n readInt32BE(i: number): number;\n /**\n * Reads the byte at the given index as an unsigned integer.\n */\n readUInt8(i: number): number;\n /**\n * Reads the two bytes at the given index as an unsigned integer (little endian).\n */\n readUInt16LE(i: number): number;\n /**\n * Reads the two bytes at the given index as an unsigned integer (big endian).\n */\n readUInt16BE(i: number): number;\n /**\n * Reads the four bytes at the given index as an unsigned integer (little endian).\n */\n readUInt32LE(i: number): number;\n /**\n * Reads the four bytes at the given index as an unsigned integer (big endian).\n */\n readUInt32BE(i: number): number;\n /**\n * Reads a 32-bit floating point number at the given index (little endian).\n */\n readFloatLE(i: number): number;\n /**\n * Reads a 32-bit floating point number at the given index (big endian).\n */\n readFloatBE(i: number): number;\n /**\n * Reads a 64-bit floating point number at the given index (little endian).\n */\n readDoubleLE(i: number): number;\n /**\n * Reads a 64-bit floating point number at the given index (
"import {BufferCoreCommon, BufferCore, BufferCoreImplementation} from './buffer_core';\n\n// Used to clear segments of an array index.\nvar clearMasks: number[] = [0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF, 0x00FFFFFF];\n\n/**\n * Implementation of BufferCore that is backed by an array of 32-bit ints.\n * Data is stored little endian.\n * Example: Bytes 0 through 3 are present in the first int:\n * BYTE 3 BYTE 2 BYTE 1 BYTE 0\n * 0000 0000 | 0000 0000 | 0000 0000 | 0000 0000\n */\nclass BufferCoreArray extends BufferCoreCommon implements BufferCore {\n public static isAvailable(): boolean {\n return true;\n }\n\n public static name = \"Array\";\n\n private buff: number[];\n private length: number;\n constructor(length: number) {\n super();\n this.length = length;\n this.buff = new Array(Math.ceil(length/4));\n // Zero-fill the array.\n var bufflen = this.buff.length;\n for (var i = 0; i < bufflen; i++) {\n this.buff[i] = 0;\n }\n }\n public getLength(): number {\n return this.length;\n }\n public writeUInt8(i: number, data: number): void {\n data &= 0xFF;\n // Which int? (Equivalent to (i/4)|0)\n var arrIdx = i >> 2;\n // Which offset? (Equivalent to i - arrIdx*4)\n var intIdx = i & 3;\n this.buff[arrIdx] = this.buff[arrIdx] & clearMasks[intIdx];\n this.buff[arrIdx] = this.buff[arrIdx] | (data << (intIdx << 3));\n }\n public readUInt8(i: number): number {\n // Which int?\n var arrIdx = i >> 2;\n // Which offset?\n var intIdx = i & 3;\n // Bring the data we want into the lowest 8 bits, and truncate.\n return (this.buff[arrIdx] >> (intIdx << 3)) & 0xFF;\n }\n public copy(start: number, end: number): BufferCore {\n // Stupid unoptimized copy. Later, we could do optimizations when aligned.\n var newBC = new BufferCoreArray(end - start);\n for (var i = start; i < end; i++) {\n newBC.writeUInt8(i - start, this.readUInt8(i));\n }\n return newBC;\n }\n}\n\n// Type-check the class.\nvar _: BufferCoreImplementation = BufferCoreArray;\n\nexport = BufferCoreArray;\n",
"import {BufferCoreCommon, BufferCore, BufferCoreImplementation} from './buffer_core';\nimport {isArrayBuffer, isArrayBufferView} from './util';\n\n/**\n * Represents data using an ArrayBuffer.\n */\nclass BufferCoreArrayBuffer extends BufferCoreCommon implements BufferCore {\n public static isAvailable(): boolean {\n return typeof DataView !== 'undefined';\n }\n\n public static name = \"ArrayBuffer\";\n\n private buff: DataView;\n private length: number;\n constructor(length: number);\n constructor(buff: ArrayBufferView);\n constructor(buff: ArrayBuffer);\n constructor(arg1: number | ArrayBufferView | ArrayBuffer) {\n super();\n if (typeof arg1 === 'number') {\n this.buff = new DataView(new ArrayBuffer(arg1));\n } else if (arg1 instanceof DataView) {\n this.buff = arg1;\n } else if (isArrayBufferView(arg1)) {\n this.buff = new DataView(arg1.buffer, arg1.byteOffset, arg1.byteLength);\n } else if (isArrayBuffer(arg1)) {\n this.buff = new DataView(<ArrayBuffer> arg1);\n } else {\n throw new TypeError(\"Invalid argument.\");\n }\n this.length = this.buff.byteLength;\n }\n public getLength(): number {\n return this.length;\n }\n public writeInt8(i: number, data: number): void {\n this.buff.setInt8(i, data);\n }\n public writeInt16LE(i: number, data: number): void {\n this.buff.setInt16(i, data, true);\n }\n public writeInt16BE(i: number, data: number): void {\n this.buff.setInt16(i, data, false);\n }\n public writeInt32LE(i: number, data: number): void {\n this.buff.setInt32(i, data, true);\n }\n public writeInt32BE(i: number, data: number): void {\n this.buff.setInt32(i, data, false);\n }\n public writeUInt8(i: number, data: number): void {\n this.buff.setUint8(i, data);\n }\n public writeUInt16LE(i: number, data: number): void {\n this.buff.setUint16(i, data, true);\n }\n public writeUInt16BE(i: number, data: number): void {\n this.buff.setUint16(i, data, false);\n }\n public writeUInt32LE(i: number, data: number): void {\n this.buff.setUint32(i, data, true);\n }\n public writeUInt32BE(i: number, data: number): void {\n this.buff.setUint32(i, data, false);\n }\n public writeFloatLE(i: number, data: number): void {\n this.buff.setFloat32(i, data, true);\n }\n public writeFloatBE(i: number, data: number): void {\n this.buff.setFloat32(i, data, false);\n }\n public writeDoubleLE(i: number, data: number): void {\n this.buff.setFloat64(i, data, true);\n }\n public writeDoubleBE(i: number, data: number): void {\n this.buff.setFloat64(i, data, false);\n }\n public readInt8(i: number): number {\n return this.buff.getInt8(i);\n }\n public readInt16LE(i: number): number {\n return this.buff.getInt16(i, true);\n }\n public readInt16BE(i: number): number {\n return this.buff.getInt16(i, false);\n }\n public readInt32LE(i: number): number {\n return this.buff.getInt32(i, true);\n }\n public readInt32BE(i: number): number {\n return this.buff.getInt32(i, false);\n }\n public readUInt8(i: number): number {\n return this.buff.getUint8(i);\n }\n public readUInt16LE(i: number): number {\n return this.buff.getUint16(i, true);\n }\n public readUInt16BE(i: number): number {\n return this.buff.getUint16(i, false);\n }\n public readUInt32LE(i: number): number {\n return this.buff.getUint32(i, true);\n }\n public readUInt32BE(i: number): number {\n return this.buff.getUint32(i, false);\n }\n public readFloatLE(i: number): number {\n return this.buff.getFloat32(i, true);\n }\n public readFloatBE(i: number): number {\n return this.buff.getFloat32(i, false);\n }\n public readDoubleLE(i: number): number {\n return this.buff.getFloat64(i, true);\n }\n public readDoubleBE(i: number): number {\n return this.buff.getFloat64(i, false);\n }\n public copy(start: number, end: number): BufferCore {\n let aBuff = this.buff.buffer;\n let aBuffOff = this.buff.byteOffset;\n let newBuff: ArrayBuffer;\n // Some ArrayBuffer implementations (IE10
"import {BufferCoreCommon, BufferCore, BufferCoreImplementation} from './buffer_core';\n\n/**\n * Deprecated type, so it is not present in TypeScript's lib.d.ts.\n */\ninterface CanvasPixelArray {\n // Values are [0,255].\n [index: number]: number;\n length: number;\n}\ndeclare var CanvasPixelArray: CanvasPixelArray;\n\n/**\n * Implementation of BufferCore that is backed by an ImageData object.\n * Useful in browsers with HTML5 canvas support, but no TypedArray support\n * (IE9).\n */\nclass BufferCoreImageData extends BufferCoreCommon implements BufferCore {\n private static imageDataFactory: CanvasRenderingContext2D;\n /**\n * Constructs a CanvasPixelArray that represents the given amount of bytes.\n */\n private static getCanvasPixelArray(bytes: number): CanvasPixelArray {\n var ctx: CanvasRenderingContext2D = BufferCoreImageData.imageDataFactory;\n // Lazily initialize, otherwise every browser (even those that will never\n // use this code) will create a canvas on script load.\n if (ctx === undefined) {\n BufferCoreImageData.imageDataFactory = ctx = document.createElement('canvas').getContext('2d');\n }\n // You cannot create image data with size 0, so up it to size 1.\n if (bytes === 0) bytes = 1;\n return ctx.createImageData(Math.ceil(bytes / 4), 1).data;\n }\n public static isAvailable(): boolean {\n // Modern browsers have removed this deprecated API, so it is not always around.\n // NOTE: IE11 in IE8 compat. mode has CanvasPixelArray defined, but you can't\n // use it! Hence the check for getContext.\n return typeof(CanvasPixelArray) !== 'undefined' && document.createElement('canvas')['getContext'] !== undefined;\n }\n public static name = \"ImageData\";\n\n private buff: CanvasPixelArray;\n private length: number;\n constructor(length: number) {\n super();\n this.length = length;\n this.buff = BufferCoreImageData.getCanvasPixelArray(length);\n }\n public getLength(): number {\n return this.length;\n }\n public writeUInt8(i: number, data: number): void {\n this.buff[i] = data;\n }\n public readUInt8(i: number): number {\n return this.buff[i];\n }\n public copy(start: number, end: number): BufferCore {\n // AFAIK, there's no efficient way to clone ImageData.\n var newBC = new BufferCoreImageData(end - start);\n for (var i = start; i < end; i++) {\n newBC.writeUInt8(i - start, this.buff[i]);\n }\n return newBC;\n }\n}\n\n// Type-check the class.\nvar _: BufferCoreImplementation = BufferCoreImageData;\n\nexport = BufferCoreImageData;\n",
"/**\n * (Nonstandard) String utility function for 8-bit ASCII with the extended\n * character set. Unlike the ASCII above, we do not mask the high bits.\n *\n * Placed into a separate file so it can be used with other Buffer implementations.\n * @see http://en.wikipedia.org/wiki/Extended_ASCII\n */\nexport default class ExtendedASCII {\n private static extendedChars = [ '\\u00C7', '\\u00FC', '\\u00E9', '\\u00E2', '\\u00E4',\n '\\u00E0', '\\u00E5', '\\u00E7', '\\u00EA', '\\u00EB', '\\u00E8', '\\u00EF',\n '\\u00EE', '\\u00EC', '\\u00C4', '\\u00C5', '\\u00C9', '\\u00E6', '\\u00C6',\n '\\u00F4', '\\u00F6', '\\u00F2', '\\u00FB', '\\u00F9', '\\u00FF', '\\u00D6',\n '\\u00DC', '\\u00F8', '\\u00A3', '\\u00D8', '\\u00D7', '\\u0192', '\\u00E1',\n '\\u00ED', '\\u00F3', '\\u00FA', '\\u00F1', '\\u00D1', '\\u00AA', '\\u00BA',\n '\\u00BF', '\\u00AE', '\\u00AC', '\\u00BD', '\\u00BC', '\\u00A1', '\\u00AB',\n '\\u00BB', '_', '_', '_', '\\u00A6', '\\u00A6', '\\u00C1', '\\u00C2', '\\u00C0',\n '\\u00A9', '\\u00A6', '\\u00A6', '+', '+', '\\u00A2', '\\u00A5', '+', '+', '-',\n '-', '+', '-', '+', '\\u00E3', '\\u00C3', '+', '+', '-', '-', '\\u00A6', '-',\n '+', '\\u00A4', '\\u00F0', '\\u00D0', '\\u00CA', '\\u00CB', '\\u00C8', 'i',\n '\\u00CD', '\\u00CE', '\\u00CF', '+', '+', '_', '_', '\\u00A6', '\\u00CC', '_',\n '\\u00D3', '\\u00DF', '\\u00D4', '\\u00D2', '\\u00F5', '\\u00D5', '\\u00B5',\n '\\u00FE', '\\u00DE', '\\u00DA', '\\u00DB', '\\u00D9', '\\u00FD', '\\u00DD',\n '\\u00AF', '\\u00B4', '\\u00AD', '\\u00B1', '_', '\\u00BE', '\\u00B6', '\\u00A7',\n '\\u00F7', '\\u00B8', '\\u00B0', '\\u00A8', '\\u00B7', '\\u00B9', '\\u00B3',\n '\\u00B2', '_', ' ' ];\n\n public static str2byte(str: string, buf: NodeBuffer): number {\n var length = str.length > buf.length ? buf.length : str.length;\n for (var i = 0; i < length; i++) {\n var charCode = str.charCodeAt(i);\n if (charCode > 0x7F) {\n // Check if extended ASCII.\n var charIdx = ExtendedASCII.extendedChars.indexOf(str.charAt(i));\n if (charIdx > -1) {\n charCode = charIdx + 0x80;\n }\n // Otherwise, keep it as-is.\n }\n buf.writeUInt8(charCode, i);\n }\n return length;\n }\n\n public static byte2str(buff: NodeBuffer): string {\n var chars = new Array(buff.length);\n for (var i = 0; i < buff.length; i++) {\n var charCode = buff.readUInt8(i);\n if (charCode > 0x7F) {\n chars[i] = ExtendedASCII.extendedChars[charCode - 128]\n } else {\n chars[i] = String.fromCharCode(charCode);\n }\n }\n return chars.join('');\n }\n\n public static byteLength(str: string): number { return str.length; }\n}\n",
"import buffer = require(\"./buffer\");\nimport ExtendedASCII from './extended_ascii';\n\nvar fromCharCode = String.fromCharCode;\n\n/**\n * Efficiently converts an array of character codes into a JS string.\n * Avoids an issue with String.fromCharCode when the number of arguments is too large.\n */\nexport function fromCharCodes(charCodes: number[]): string {\n // 8K blocks.\n var numChars = charCodes.length,\n numChunks = ((numChars - 1) >> 13) + 1,\n chunks: string[] = new Array<string>(numChunks), i: number;\n for (i = 0; i < numChunks; i++) {\n chunks[i] = fromCharCode.apply(String, charCodes.slice(i * 0x2000, (i + 1) * 0x2000));\n }\n return chunks.join(\"\");\n}\n\n/**\n * Contains string utility functions, mainly for converting between JavaScript\n * strings and binary buffers of arbitrary encoding types.\n */\n\n/**\n * Encapsulates utility functions for a particular string encoding.\n */\nexport interface StringUtil {\n /**\n * Converts the string into its binary representation, and then writes the\n * binary representation into the buffer at the given offset.\n *\n * We assume that the offset / length is pre-validated.\n * @param [BrowserFS.node.Buffer] buf the buffer to write into\n * @param [String] str the string that will be converted\n * @param [Number] offset the offset to start writing into the buffer at\n * @param [Number] length an upper bound on the length of the string that we\n * can write\n * @return [Number] number of bytes written into the buffer\n */\n str2byte(str: string, buf: NodeBuffer): number;\n /**\n * Converts the data in the byte array into a string.\n * @todo Is this the best API? Are we doing needless copying?\n * @param [Array] byteArray an array of bytes\n * @return [String] the array interpreted as a binary string\n */\n byte2str(buf: NodeBuffer): string;\n /**\n * Returns the number of bytes that the string will take up using the given\n * encoding.\n * @param [String] str the string to get the byte length for\n * @return [Number] the number of bytes that the string will take up using the\n * given encoding.\n */\n byteLength(str: string): number;\n}\n\n/**\n * Find the 'utility' object for the given string encoding. Throws an exception\n * if the encoding is invalid.\n * @param [String] encoding a string encoding\n * @return [BrowserFS.StringUtil.*] The StringUtil object for the given encoding\n */\nexport function FindUtil(encoding: string): StringUtil {\n encoding = (function() {\n switch (typeof encoding) {\n case 'object':\n return \"\" + encoding; // Implicitly calls toString on any object (Node does this)\n case 'string':\n return encoding; // No transformation needed.\n default:\n throw new TypeError('Invalid encoding argument specified');\n }\n })();\n encoding = encoding.toLowerCase();\n // This is the same logic as Node's source code.\n switch (encoding) {\n case 'utf8':\n case 'utf-8':\n return UTF8;\n case 'ascii':\n return ASCII;\n case 'binary':\n return BINARY;\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return UCS2;\n case 'hex':\n return HEX;\n case 'base64':\n return BASE64;\n // Custom BFS: For efficiently representing data as JavaScript UTF-16\n // strings.\n case 'binary_string':\n return BINSTR;\n case 'binary_string_ie':\n return BINSTRIE;\n case 'extended_ascii':\n return ExtendedASCII;\n default:\n throw new TypeError(`Unknown encoding: ${encoding}`);\n }\n}\n\n/**\n * String utility functions for UTF-8. Note that some UTF-8 strings *cannot* be\n * expressed in terms of JavaScript UTF-16 strings.\n * @see http://en.wikipedia.org/wiki/UTF-8\n */\nexport class UTF8 {\n public static str2byte(str: string, buf: NodeBuffer): number {\n var maxJ = buf.length,\n i = 0,\n j = 0,\n strLen = str.length;\n while (i < strLen && j < maxJ) {\n var code = str.charCodeAt(i++);\n if (0xD800 <= code &&
"/**\n * Check if the input is an array buffer view.\n */\nexport var isArrayBufferView: (ab: any) => ab is ArrayBufferView;\n/**\n * Check if the input is an array buffer.\n * (Note: Must check if ab is null / an object first.)\n */\nexport var isArrayBuffer: (ab: any) => ab is ArrayBuffer;\n\nif (typeof(ArrayBuffer) === 'undefined') {\n isArrayBufferView = (ab: any): ab is ArrayBufferView => false;\n isArrayBuffer = (ab: any): ab is ArrayBuffer => false;\n} else {\n isArrayBuffer = function(ab: any): ab is ArrayBuffer {\n return typeof ab.byteLength === 'number';\n };\n if (ArrayBuffer['isView']) {\n isArrayBufferView = function(ab: any): ab is ArrayBufferView {\n return ArrayBuffer.isView(ab);\n };\n } else {\n isArrayBufferView = function(ab: any): ab is ArrayBufferView {\n return isArrayBuffer(ab['buffer']);\n }\n }\n}",
"// Type information only.\nimport _path = require('path');\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nvar splitPathRe = /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;\nfunction posixSplitPath(filename: string): string[] {\n var out = splitPathRe.exec(filename);\n out.shift();\n return out;\n}\n\n/**\n * Emulates Node's `path` module. This module contains utilities for handling and\n * transforming file paths. **All** of these methods perform only string\n * transformations. The file system is not consulted to check whether paths are\n * valid.\n * @see http://nodejs.org/api/path.html\n * @class\n */\nclass path {\n /**\n * Normalize a string path, taking care of '..' and '.' parts.\n *\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 * @example Usage example\n * path.normalize('/foo/bar//baz/asdf/quux/..')\n * // returns\n * '/foo/bar/baz/asdf'\n * @param [String] p The path to normalize.\n * @return [String]\n */\n public static normalize(p: string): string {\n // Special case: '' -> '.'\n if (p === '') {\n p = '.';\n }\n // It's very important to know if the path is relative or not, since it\n // changes how we process .. and reconstruct the split string.\n var absolute = p.charAt(0) === path.sep;\n // Remove repeated //s\n p = path._removeDuplicateSeps(p);\n // Try to remove as many '../' as possible, and remove '.' completely.\n var components = p.split(path.sep);\n var goodComponents: string[] = [];\n for (var idx = 0; idx < components.length; idx++) {\n var c = components[idx];\n if (c === '.') {\n continue;\n } else if (c === '..' && (absolute || (!absolute && goodComponents.length > 0 && goodComponents[0] !== '..'))) {\n // In the absolute case: Path is relative to root, so we may pop even if\n // goodComponents is empty (e.g. /../ => /)\n // In the relative case: We're getting rid of a directory that preceded\n // it (e.g. /foo/../bar -> /bar)\n goodComponents.pop();\n } else {\n goodComponents.push(c);\n }\n }\n\n // Add in '.' when it's a relative path with no other nonempty components.\n // Possible results: '.' and './' (input: [''] or [])\n // @todo Can probably simplify this logic.\n if (!absolute && goodComponents.length < 2) {\n switch (goodComponents.length) {\n case 1:\n if (goodComponents[0] === '') {\n goodComponents.unshift('.');\n }\n break;\n default:\n goodComponents.push('.');\n }\n }\n p = goodComponents.join(path.sep);\n if (absolute && p.charAt(0) !== path.sep) {\n p = path.sep + p;\n }\n return p;\n }\n\n /**\n * Join all arguments together and normalize the resulting path.\n *\n * Arguments must be strings.\n * @example Usage\n * path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')\n * // returns\n * '/foo/bar/baz/asdf'\n *\n * path.join('foo', {}, 'bar')\n * // throws exception\n * TypeError: Arguments to path.join must be strings\n * @param [String,...] paths Each component of the path\n * @return [String]\n */\n public static join(...paths: any[]): string {\n // Required: Prune any non-strings from the path. I also prune empty segments\n // so we can do a simple join of the array.\n var processed: string[] = [];\n for (var i = 0; i < paths.length; i++) {\n var segment = paths[i];\n if (typeof segment !== 'string') {\n throw new TypeError(\"Invalid argument type to path.join: \" + (typeof segment));\n } else if (segment !== '') {\n processed.push(segment);\n }\n }\n return path.normalize(processed.join(path.sep));\n }\n\n /**\n * Resolves to to an absolute path.\n *\n * If to isn't already absolute from arguments are prepended in ri
"import Process = require('./process');\nimport TTD = require('./tty');\n\nvar process = new Process(),\n processProxy: Process = <any> {};\n\nfunction defineKey(key: string) {\n if ((<any> processProxy)[key]) {\n // Probably a builtin Object property we don't care about.\n return;\n }\n if (typeof (<any> process)[key] === 'function') {\n (<any> processProxy)[key] = function() {\n return (<Function> (<any> process)[key]).apply(process, arguments);\n };\n } else {\n (<any> processProxy)[key] = (<any> process)[key];\n }\n}\n\nfor (var key in process) {\n // Don't check if process.hasOwnProperty; we want to also expose objects\n // up the prototype hierarchy.\n defineKey(key);\n}\n\n// Special key: Ensure we update public-facing values of stdin/stdout/stderr.\nprocessProxy.initializeTTYs = function() {\n if (process.stdin === null) {\n process.initializeTTYs();\n processProxy.stdin = process.stdin;\n processProxy.stdout = process.stdout;\n processProxy.stderr = process.stderr;\n }\n};\n\nprocess.nextTick(() => {\n processProxy.initializeTTYs();\n});\n\nexport = processProxy;\n",
"// Use path and TTY for type information only. We lazily pull them in\n// to avoid circular dependencies :(\n// (path depends on process for cwd(), TTY depends on streams which depends\n// on process.nextTick/process.stdout/stderr/stdin).\nimport _path = require('path');\nimport _TTY = require('./tty');\nimport events = require('events');\n\n// Path depends on process. Avoid a circular reference by dynamically including path when we need it.\nvar path: typeof _path = null;\n\nclass Item {\n private fun: Function;\n private array: any[];\n constructor(fun: Function, array: any[]) {\n this.fun = fun;\n this.array = array;\n }\n\n public run(): void {\n this.fun.apply(null, this.array);\n }\n}\n\n/**\n * Contains a queue of Items for process.nextTick.\n * Inspired by node-process: https://github.com/defunctzombie/node-process\n */\nclass NextTickQueue {\n private _queue: Item[] = [];\n private _draining = false;\n // Used/assigned by the drainQueue function.\n private _currentQueue: Item[] = null;\n private _queueIndex = -1;\n\n public push(item: Item): void {\n if (this._queue.push(item) === 1 && !this._draining) {\n setTimeout(() => this._drainQueue(), 0);\n }\n }\n\n private _cleanUpNextTick() {\n this._draining = false;\n if (this._currentQueue && this._currentQueue.length) {\n this._queue = this._currentQueue.concat(this._queue);\n } else {\n this._queueIndex = -1;\n }\n if (this._queue.length) {\n this._drainQueue();\n }\n }\n\n private _drainQueue() {\n if (this._draining) {\n return;\n }\n // If an Item throws an unhandled exception, this function will clean things up.\n var timeout = setTimeout(() => this._cleanUpNextTick());\n this._draining = true;\n\n var len = this._queue.length;\n while(len) {\n this._currentQueue = this._queue;\n this._queue = [];\n while (++this._queueIndex < len) {\n if (this._currentQueue) {\n this._currentQueue[this._queueIndex].run();\n }\n }\n this._queueIndex = -1;\n len = this._queue.length;\n }\n this._currentQueue = null;\n this._draining = false;\n clearTimeout(timeout);\n }\n}\n\n/**\n * Partial implementation of Node's `process` module.\n * We implement the portions that are relevant for the filesystem.\n * @see http://nodejs.org/api/process.html\n * @class\n */\nclass Process extends events.EventEmitter implements NodeJS.Process {\n private startTime = Date.now();\n\n private _cwd: string = '/';\n /**\n * Changes the current working directory.\n *\n * **Note**: BrowserFS does not validate that the directory actually exists.\n *\n * @example Usage example\n * console.log('Starting directory: ' + process.cwd());\n * process.chdir('/tmp');\n * console.log('New directory: ' + process.cwd());\n * @param [String] dir The directory to change to.\n */\n public chdir(dir: string): void {\n // XXX: Circular dependency hack.\n if (path === null) {\n path = require('path');\n }\n this._cwd = path.resolve(dir);\n }\n /**\n * Returns the current working directory.\n * @example Usage example\n * console.log('Current directory: ' + process.cwd());\n * @return [String] The current working directory.\n */\n public cwd(): string {\n return this._cwd;\n }\n /**\n * Returns what platform you are running on.\n * @return [String]\n */\n public platform: string = 'browser';\n /**\n * Number of seconds BrowserFS has been running.\n * @return [Number]\n */\n public uptime(): number {\n return ((Date.now() - this.startTime) / 1000) | 0;\n }\n\n public argv: string[] = [];\n public stdout: _TTY = null;\n public stderr: _TTY = null;\n public stdin: _TTY = null;\n\n private _queue: NextTickQueue = new NextTickQueue();\n\n public nextTick(fun: any, ...args: any[]) {\n this._queue.push(new Item(fun, args));\n }\n\n public execPath = __dirname;\n\n public abort(): void {\n this.emit('abort');\n }\n\n public env: {[name: string]: string} = {};\n
"import stream = require('stream');\n\nclass TTY extends stream.Duplex {\n public isRaw: boolean = false;\n public columns: number = 80;\n public rows: number = 120;\n public isTTY: boolean = true;\n private _bufferedWrites: Buffer[] = [];\n private _waitingForWrites: boolean = false;\n\n constructor() {\n super();\n }\n\n /**\n * Toggle raw mode.\n */\n public setRawMode(mode: boolean): void {\n if (this.isRaw !== mode) {\n this.isRaw = mode;\n // [BFS] TTY implementations can use this to change their event emitting\n // patterns.\n this.emit('modeChange');\n }\n }\n\n /**\n * [BFS] Update the number of columns available on the terminal.\n */\n public changeColumns(columns: number): void {\n if (columns !== this.columns) {\n this.columns = columns;\n // Resize event.\n this.emit('resize');\n }\n }\n\n /**\n * [BFS] Update the number of rows available on the terminal.\n */\n public changeRows(rows: number): void {\n if (rows !== this.rows) {\n this.rows = rows;\n // Resize event.\n this.emit('resize');\n }\n }\n\n /**\n * Returns 'true' if the given object is a TTY.\n */\n public static isatty(fd: any): fd is TTY {\n return fd && fd instanceof TTY;\n }\n\n public _write(chunk: any, encoding: string, cb: Function): void {\n var error: any;\n try {\n var data: Buffer;\n if (typeof(chunk) === 'string') {\n data = new Buffer(chunk, encoding);\n } else {\n data = chunk;\n }\n this._bufferedWrites.push(data);\n if (this._waitingForWrites) {\n this._read(1024);\n }\n } catch (e) {\n error = e;\n } finally {\n cb(error);\n }\n }\n\n public _read(size: number): void {\n // Size is advisory -- we can ignore it.\n if (this._bufferedWrites.length === 0) {\n this._waitingForWrites = true;\n } else {\n while (this._bufferedWrites.length > 0) {\n this._waitingForWrites = this.push(this._bufferedWrites.shift());\n if (!this._waitingForWrites) {\n break;\n }\n }\n }\n }\n}\n\nexport = TTY;\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\nfunction EventEmitter() {\n this._events = this._events || {};\n this._maxListeners = this._maxListeners || undefined;\n}\nmodule.exports = EventEmitter;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function(n) {\n if (!isNumber(n) || n < 0 || isNaN(n))\n throw TypeError('n must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nEventEmitter.prototype.emit = function(type) {\n var er, handler, len, args, i, listeners;\n\n if (!this._events)\n this._events = {};\n\n // If there is no 'error' event listener then throw.\n if (type === 'error') {\n if (!this._events.error ||\n (isObject(this._events.error) && !this._events.error.length)) {\n er = arguments[1];\n if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n }\n throw TypeError('Uncaught, unspecified \"error\" event.');\n }\n }\n\n handler = this._events[type];\n\n if (isUndefined(handler))\n return false;\n\n if (isFunction(handler)) {\n switch (arguments.length) {\n // fast cases\n case 1:\n handler.call(this);\n break;\n case 2:\n handler.call(this, arguments[1]);\n break;\n case 3:\n handler.call(this, arguments[1], arguments[2]);\n break;\n // slower\n default:\n args = Array.prototype.slice.call(arguments, 1);\n handler.apply(this, args);\n }\n } else if (isObject(handler)) {\n args = Array.prototype.slice.call(arguments, 1);\n listeners = handler.slice();\n len = listeners.length;\n for (i = 0; i < len; i++)\n listeners[i].apply(this, args);\n }\n\n return true;\n};\n\nEventEmitter.prototype.addListener = function(type, listener) {\n var m;\n\n if (!isFunction(listener))\n throw TypeError('listener must be a function');\n\n if (!this._events)\n this._events = {};\n\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (this._events.newListener)\n this.emit('newListener', type,\n isFunction(listener.listener) ?\n listener.listener : listener);\n\n if (!this._events[type])\n // Optimize the case of one listener. Don't need the extra array object.\n this._events[type] = listener;\n else if (isObject(this._events[type]))\n // If we've already got an array, just append.\n this._even
"if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\n",
"module.exports = Array.isArray || function (arr) {\n return Object.prototype.toString.call(arr) == '[object Array]';\n};\n",
"module.exports = require(\"./lib/_stream_duplex.js\")\n",
"// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/*<replacement>*/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) keys.push(key);\n return keys;\n}\n/*</replacement>*/\n\n\nmodule.exports = Duplex;\n\n/*<replacement>*/\nvar processNextTick = require('process-nextick-args');\n/*</replacement>*/\n\n\n\n/*<replacement>*/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\nvar keys = objectKeys(Writable.prototype);\nfor (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method])\n Duplex.prototype[method] = Writable.prototype[method];\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex))\n return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false)\n this.readable = false;\n\n if (options && options.writable === false)\n this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false)\n this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended)\n return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n processNextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nfunction forEach (xs, f) {\n for (var i = 0, l = xs.length; i < l; i++) {\n f(xs[i], i);\n }\n}\n",
"// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\n/*<replacement>*/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough))\n return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function(chunk, encoding, cb) {\n cb(null, chunk);\n};\n",
"'use strict';\n\nmodule.exports = Readable;\n\n/*<replacement>*/\nvar processNextTick = require('process-nextick-args');\n/*</replacement>*/\n\n\n/*<replacement>*/\nvar isArray = require('isarray');\n/*</replacement>*/\n\n\n/*<replacement>*/\nvar Buffer = require('buffer').Buffer;\n/*</replacement>*/\n\nReadable.ReadableState = ReadableState;\n\nvar EE = require('events');\n\n/*<replacement>*/\nvar EElistenerCount = function(emitter, type) {\n return emitter.listeners(type).length;\n};\n/*</replacement>*/\n\n\n\n/*<replacement>*/\nvar Stream;\n(function (){try{\n Stream = require('st' + 'ream');\n}catch(_){}finally{\n if (!Stream)\n Stream = require('events').EventEmitter;\n}}())\n/*</replacement>*/\n\nvar Buffer = require('buffer').Buffer;\n\n/*<replacement>*/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/*</replacement>*/\n\n\n\n/*<replacement>*/\nvar debugUtil = require('util');\nvar debug;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/*</replacement>*/\n\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar Duplex;\nfunction ReadableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (stream instanceof Duplex)\n this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;\n\n // cast to ints.\n this.highWaterMark = ~~this.highWaterMark;\n\n this.buffer = [];\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // when piping, we only care about 'readable' events that happen\n // after read()ing all the bytes and not getting any pushback.\n this.ranOut = false;\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder)\n StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nvar Duplex;\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable))\n return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options && typeof options.read === 'function')\n this._read = options.read;\n\n Stream.call(this);\n}\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.proto
"// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/*<replacement>*/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/*</replacement>*/\n\nutil.inherits(Transform, Duplex);\n\n\nfunction TransformState(stream) {\n this.afterTransform = function(er, data) {\n return afterTransform(stream, er, data);\n };\n\n this.needTransform = false;\n this.transforming = false;\n this.writecb = null;\n this.writechunk = null;\n}\n\nfunction afterTransform(stream, er, data) {\n var ts = stream._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb)\n return stream.emit('error', new Error('no writecb in Transform class'));\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data !== null && data !== undefined)\n stream.push(data);\n\n if (cb)\n cb(er);\n\n var rs = stream._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n stream._read(rs.highWaterMark);\n }\n}\n\n\nfunction Transform(options) {\n if (!(this instanceof Transform))\n return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = new TransformState(this);\n\n // when the writable side finishes, then flush out anything remaining.\n var stream = this;\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform
"// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\nmodule.exports = Writable;\n\n/*<replacement>*/\nvar processNextTick = require('process-nextick-args');\n/*</replacement>*/\n\n\n/*<replacement>*/\nvar Buffer = require('buffer').Buffer;\n/*</replacement>*/\n\nWritable.WritableState = WritableState;\n\n\n/*<replacement>*/\nvar util = require('core-util-is');\nutil.inherits = require('inherits');\n/*</replacement>*/\n\n\n/*<replacement>*/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/*</replacement>*/\n\n\n\n/*<replacement>*/\nvar Stream;\n(function (){try{\n Stream = require('st' + 'ream');\n}catch(_){}finally{\n if (!Stream)\n Stream = require('events').EventEmitter;\n}}())\n/*</replacement>*/\n\nvar Buffer = require('buffer').Buffer;\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\nvar Duplex;\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (stream instanceof Duplex)\n this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;\n\n // cast to ints.\n this.highWaterMark = ~~this.highWaterMark;\n\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function(er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is rel
"// 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// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n",
"'use strict';\n\nif (!process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = nextTick;\n} else {\n module.exports = process.nextTick;\n}\n\nfunction nextTick(fn) {\n var args = new Array(arguments.length - 1);\n var i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n}\n",
"\n/**\n * Module exports.\n */\n\nmodule.exports = deprecate;\n\n/**\n * Mark that a method should not be used.\n * Returns a modified function which warns once by default.\n *\n * If `localStorage.noDeprecation = true` is set, then it is a no-op.\n *\n * If `localStorage.throwDeprecation = true` is set, then deprecated functions\n * will throw an Error when invoked.\n *\n * If `localStorage.traceDeprecation = true` is set, then deprecated functions\n * will invoke `console.trace()` instead of `console.error()`.\n *\n * @param {Function} fn - the function to deprecate\n * @param {String} msg - the string to print to the console when `fn` is invoked\n * @returns {Function} a new \"deprecated\" version of `fn`\n * @api public\n */\n\nfunction deprecate (fn, msg) {\n if (config('noDeprecation')) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (config('throwDeprecation')) {\n throw new Error(msg);\n } else if (config('traceDeprecation')) {\n console.trace(msg);\n } else {\n console.warn(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n}\n\n/**\n * Checks `localStorage` for boolean values for the given `name`.\n *\n * @param {String} name\n * @returns {Boolean}\n * @api private\n */\n\nfunction config (name) {\n // accessing global.localStorage can trigger a DOMException in sandboxed iframes\n try {\n if (!global.localStorage) return false;\n } catch (_) {\n return false;\n }\n var val = global.localStorage[name];\n if (null == val) return false;\n return String(val).toLowerCase() === 'true';\n}\n",
"module.exports = require(\"./lib/_stream_passthrough.js\")\n",
"var Stream = (function (){\n try {\n return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify\n } catch(_){}\n}());\nexports = module.exports = require('./lib/_stream_readable.js');\nexports.Stream = Stream || exports;\nexports.Readable = exports;\nexports.Writable = require('./lib/_stream_writable.js');\nexports.Duplex = require('./lib/_stream_duplex.js');\nexports.Transform = require('./lib/_stream_transform.js');\nexports.PassThrough = require('./lib/_stream_passthrough.js');\n",
"module.exports = require(\"./lib/_stream_transform.js\")\n",
"module.exports = require(\"./lib/_stream_writable.js\")\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\nmodule.exports = Stream;\n\nvar EE = require('events').EventEmitter;\nvar inherits = require('inherits');\n\ninherits(Stream, EE);\nStream.Readable = require('readable-stream/readable.js');\nStream.Writable = require('readable-stream/writable.js');\nStream.Duplex = require('readable-stream/duplex.js');\nStream.Transform = require('readable-stream/transform.js');\nStream.PassThrough = require('readable-stream/passthrough.js');\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream;\n\n\n\n// old-style streams. Note that the pipe method (the only relevant\n// part of this class) is overridden in the Readable class.\n\nfunction Stream() {\n EE.call(this);\n}\n\nStream.prototype.pipe = function(dest, options) {\n var source = this;\n\n function ondata(chunk) {\n if (dest.writable) {\n if (false === dest.write(chunk) && source.pause) {\n source.pause();\n }\n }\n }\n\n source.on('data', ondata);\n\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume();\n }\n }\n\n dest.on('drain', ondrain);\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend);\n source.on('close', onclose);\n }\n\n var didOnEnd = false;\n function onend() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n dest.end();\n }\n\n\n function onclose() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n if (typeof dest.destroy === 'function') dest.destroy();\n }\n\n // don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup();\n if (EE.listenerCount(this, 'error') === 0) {\n throw er; // Unhandled stream error in pipe.\n }\n }\n\n source.on('error', onerror);\n dest.on('error', onerror);\n\n // remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata);\n dest.removeListener('drain', ondrain);\n\n source.removeListener('end', onend);\n source.removeListener('close', onclose);\n\n source.removeListener('error', onerror);\n dest.removeListener('error', onerror);\n\n source.removeListener('end', cleanup);\n source.removeListener('close', cleanup);\n\n dest.removeListener('close', cleanup);\n }\n\n source.on('end', cleanup);\n source.on('close', cleanup);\n\n dest.on('close', cleanup);\n\n dest.emit('pipe', source);\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest;\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\nvar Buffer = require('buffer').Buffer;\n\nvar isBufferEncoding = Buffer.isEncoding\n || function(encoding) {\n switch (encoding && encoding.toLowerCase()) {\n case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;\n default: return false;\n }\n }\n\n\nfunction assertEncoding(encoding) {\n if (encoding && !isBufferEncoding(encoding)) {\n throw new Error('Unknown encoding: ' + encoding);\n }\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters. CESU-8 is handled as part of the UTF-8 encoding.\n//\n// @TODO Handling all encodings inside a single object makes it very difficult\n// to reason about this code, so it should be split up in the future.\n// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code\n// points as used by CESU-8.\nvar StringDecoder = exports.StringDecoder = function(encoding) {\n this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');\n assertEncoding(encoding);\n switch (this.encoding) {\n case 'utf8':\n // CESU-8 represents each of Surrogate Pair by 3-bytes\n this.surrogateSize = 3;\n break;\n case 'ucs2':\n case 'utf16le':\n // UTF-16 represents each of Surrogate Pair by 2-bytes\n this.surrogateSize = 2;\n this.detectIncompleteChar = utf16DetectIncompleteChar;\n break;\n case 'base64':\n // Base-64 stores 3 bytes in 4 chars, and pads the remainder.\n this.surrogateSize = 3;\n this.detectIncompleteChar = base64DetectIncompleteChar;\n break;\n default:\n this.write = passThroughWrite;\n return;\n }\n\n // Enough space to store all bytes of a single character. UTF-8 needs 4\n // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).\n this.charBuffer = new Buffer(6);\n // Number of bytes received for the current incomplete multi-byte character.\n this.charReceived = 0;\n // Number of bytes expected for the current incomplete multi-byte character.\n this.charLength = 0;\n};\n\n\n// write decodes the given buffer and returns it as JS string that is\n// guaranteed to not contain any partial multi-byte characters. Any partial\n// character found at the end of the buffer is buffered up, and will be\n// returned when calling write again with the remaining bytes.\n//\n// Note: Converting a Buffer containing an orphan surrogate to a String\n// currently works, but converting a String to a Buffer (via `new Buffer`, or\n// Buffer#write) will replace incomplete surrogates with the unicode\n// replacement character. See https://codereview.chromium.org/121173009/ .\nStringDecoder.prototype.write = function(buffer) {\n var charStr = '';\n // if our last write ended with an i
null,
"/**\n * Determine if an object is Buffer\n *\n * Author: Feross Aboukhadijeh <feross@feross.org> <http://feross.org>\n * License: MIT\n *\n * `npm install is-buffer`\n */\n\nmodule.exports = function (obj) {\n return !!(obj != null &&\n (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor)\n (obj.constructor &&\n typeof obj.constructor.isBuffer === 'function' &&\n obj.constructor.isBuffer(obj))\n ))\n}\n",
"/* pako 1.0.0 nodeca/pako */\n!function(e){if(\"object\"==typeof exports&&\"undefined\"!=typeof module)module.exports=e();else if(\"function\"==typeof define&&define.amd)define([],e);else{var t;t=\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:this,t.pako=e()}}(function(){return function e(t,i,n){function a(o,s){if(!i[o]){if(!t[o]){var f=\"function\"==typeof require&&require;if(!s&&f)return f(o,!0);if(r)return r(o,!0);var l=new Error(\"Cannot find module '\"+o+\"'\");throw l.code=\"MODULE_NOT_FOUND\",l}var d=i[o]={exports:{}};t[o][0].call(d.exports,function(e){var i=t[o][1][e];return a(i?i:e)},d,d.exports,e,t,i,n)}return i[o].exports}for(var r=\"function\"==typeof require&&require,o=0;o<n.length;o++)a(n[o]);return a}({1:[function(e,t,i){\"use strict\";var n=\"undefined\"!=typeof Uint8Array&&\"undefined\"!=typeof Uint16Array&&\"undefined\"!=typeof Int32Array;i.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if(\"object\"!=typeof i)throw new TypeError(i+\"must be non-object\");for(var n in i)i.hasOwnProperty(n)&&(e[n]=i[n])}}return e},i.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var a={arraySet:function(e,t,i,n,a){if(t.subarray&&e.subarray)return void e.set(t.subarray(i,i+n),a);for(var r=0;n>r;r++)e[a+r]=t[i+r]},flattenChunks:function(e){var t,i,n,a,r,o;for(n=0,t=0,i=e.length;i>t;t++)n+=e[t].length;for(o=new Uint8Array(n),a=0,t=0,i=e.length;i>t;t++)r=e[t],o.set(r,a),a+=r.length;return o}},r={arraySet:function(e,t,i,n,a){for(var r=0;n>r;r++)e[a+r]=t[i+r]},flattenChunks:function(e){return[].concat.apply([],e)}};i.setTyped=function(e){e?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,a)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(n)},{}],2:[function(e,t,i){\"use strict\";function n(e,t){if(65537>t&&(e.subarray&&o||!e.subarray&&r))return String.fromCharCode.apply(null,a.shrinkBuf(e,t));for(var i=\"\",n=0;t>n;n++)i+=String.fromCharCode(e[n]);return i}var a=e(\"./common\"),r=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(s){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(s){o=!1}for(var f=new a.Buf8(256),l=0;256>l;l++)f[l]=l>=252?6:l>=248?5:l>=240?4:l>=224?3:l>=192?2:1;f[254]=f[254]=1,i.string2buf=function(e){var t,i,n,r,o,s=e.length,f=0;for(r=0;s>r;r++)i=e.charCodeAt(r),55296===(64512&i)&&s>r+1&&(n=e.charCodeAt(r+1),56320===(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),f+=128>i?1:2048>i?2:65536>i?3:4;for(t=new a.Buf8(f),o=0,r=0;f>o;r++)i=e.charCodeAt(r),55296===(64512&i)&&s>r+1&&(n=e.charCodeAt(r+1),56320===(64512&n)&&(i=65536+(i-55296<<10)+(n-56320),r++)),128>i?t[o++]=i:2048>i?(t[o++]=192|i>>>6,t[o++]=128|63&i):65536>i?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},i.buf2binstring=function(e){return n(e,e.length)},i.binstring2buf=function(e){for(var t=new a.Buf8(e.length),i=0,n=t.length;n>i;i++)t[i]=e.charCodeAt(i);return t},i.buf2string=function(e,t){var i,a,r,o,s=t||e.length,l=new Array(2*s);for(a=0,i=0;s>i;)if(r=e[i++],128>r)l[a++]=r;else if(o=f[r],o>4)l[a++]=65533,i+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&s>i;)r=r<<6|63&e[i++],o--;o>1?l[a++]=65533:65536>r?l[a++]=r:(r-=65536,l[a++]=55296|r>>10&1023,l[a++]=56320|1023&r)}return n(l,a)},i.utf8border=function(e,t){var i;for(t=t||e.length,t>e.length&&(t=e.length),i=t-1;i>=0&&128===(192&e[i]);)i--;return 0>i?t:0===i?t:i+f[e[i]]>t?i:t}},{\"./common\":1}],3:[function(e,t,i){\"use strict\";function n(e,t,i,n){for(var a=65535&e|0,r=e>>>16&65535|0,o=0;0!==i;){o=i>2e3?2e3:i,i-=o;do a=a+t[n++]|0,r=r+a|0;while(--o);a%=65521,r%=65521}return a|r<<16|0}t.exports=n},{}],4:[function(e,t,i){\"use strict\";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_
"import file_system = require('../core/file_system');\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport file_flag = require('../core/file_flag');\r\nimport file = require('../core/file');\r\nimport Stats from '../core/node_fs_stats';\r\nimport preload_file = require('../generic/preload_file');\r\n\r\ninterface IAsyncOperation {\r\n\tapiMethod: string;\r\n\targuments: any[];\r\n}\r\n\r\n/**\r\n * We define our own file to interpose on syncSync() for mirroring purposes.\r\n */\r\nclass MirrorFile extends preload_file.PreloadFile<AsyncMirror> implements file.File {\r\n constructor(fs: AsyncMirror, path: string, flag: file_flag.FileFlag, stat: Stats, data: Buffer) {\r\n super(fs, path, flag, stat, data);\r\n }\r\n\r\n public syncSync(): void {\r\n if (this.isDirty()) {\r\n this._fs._syncSync(this);\r\n this.resetDirty();\r\n }\r\n }\r\n\r\n public closeSync(): void {\r\n this.syncSync();\r\n }\r\n}\r\n\r\n/**\r\n * AsyncMirrorFS mirrors a synchronous filesystem into an asynchronous filesystem\r\n * by:\r\n * * Performing operations over the in-memory copy, while asynchronously pipelining them\r\n * to the backing store.\r\n * * During application loading, the contents of the async file system can be reloaded into\r\n * the synchronous store, if desired.\r\n * The two stores will be kept in sync. The most common use-case is to pair a synchronous\r\n * in-memory filesystem with an asynchronous backing store.\r\n */\r\nexport default class AsyncMirror extends file_system.SynchronousFileSystem implements file_system.FileSystem {\r\n /**\r\n * Queue of pending asynchronous operations.\r\n */\r\n private _queue: IAsyncOperation[] = [];\r\n private _queueRunning: boolean = false;\r\n private _sync: file_system.FileSystem;\r\n private _async: file_system.FileSystem;\r\n private _isInitialized: boolean = false;\r\n private _initializeCallbacks: ((e?: ApiError) => void)[] = [];\r\n constructor(sync: file_system.FileSystem, async: file_system.FileSystem) {\r\n super();\r\n this._sync = sync;\r\n this._async = async;\r\n if (!sync.supportsSynch()) {\r\n throw new Error(\"Expected synchronous storage.\");\r\n }\r\n if (async.supportsSynch()) {\r\n throw new Error(\"Expected asynchronous storage.\");\r\n }\r\n }\r\n\r\n public getName(): string {\r\n\t \treturn \"AsyncMirror\";\r\n }\r\n\r\n public static isAvailable(): boolean {\r\n return true;\r\n }\r\n\r\n public _syncSync(fd: preload_file.PreloadFile<any>) {\r\n this._sync.writeFileSync(fd.getPath(), fd.getBuffer(), null, file_flag.FileFlag.getFileFlag('w'), fd.getStats().mode);\r\n this.enqueueOp({\r\n apiMethod: 'writeFile',\r\n arguments: [fd.getPath(), fd.getBuffer(), null, fd.getFlag(), fd.getStats().mode]\r\n });\r\n }\r\n\r\n /**\r\n * Called once to load up files from async storage into sync storage.\r\n */\r\n public initialize(userCb: (err?: ApiError) => void): void {\r\n const callbacks = this._initializeCallbacks;\r\n\r\n const end = (e?: ApiError): void => {\r\n this._isInitialized = !e;\r\n this._initializeCallbacks = [];\r\n callbacks.forEach((cb) => cb(e));\r\n };\r\n\r\n if (!this._isInitialized) {\r\n // First call triggers initialization, the rest wait.\r\n if (callbacks.push(userCb) === 1) {\r\n const copyDirectory = (p: string, mode: number, cb: (err?: ApiError) => void) => {\r\n if (p !== '/') {\r\n this._sync.mkdirSync(p, mode);\r\n }\r\n this._async.readdir(p, (err, files) => {\r\n if (err) {\r\n cb(err);\r\n } else {\r\n var i = 0;\r\n function copyNextFile(err?: ApiError) {\r\n if (err) {\r\n cb(err);\r\n } else if (i < files.length) {\r\n copyItem(`${p}/${files[i]}`, copyNextFile);\r\n i++;\r\n } else {\r\n cb();\r\n }\r\n }\r\n copyNe
"import preload_file = require('../generic/preload_file');\r\nimport file_system = require('../core/file_system');\r\nimport file_flag = require('../core/file_flag');\r\nimport {default as Stats, FileType} from '../core/node_fs_stats';\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport file = require('../core/file');\r\nimport async = require('async');\r\nimport path = require('path');\r\nimport {arrayBuffer2Buffer, buffer2ArrayBuffer} from '../core/util';\r\n\r\nvar errorCodeLookup: {[dropboxErrorCode: number]: ErrorCode} = null;\r\n// Lazily construct error code lookup, since DropboxJS might be loaded *after* BrowserFS (or not at all!)\r\nfunction constructErrorCodeLookup() {\r\n if (errorCodeLookup !== null) {\r\n return;\r\n }\r\n errorCodeLookup = {};\r\n // This indicates a network transmission error on modern browsers. Internet Explorer might cause this code to be reported on some API server errors.\r\n errorCodeLookup[Dropbox.ApiError.NETWORK_ERROR] = ErrorCode.EIO;\r\n // This happens when the contentHash parameter passed to a Dropbox.Client#readdir or Dropbox.Client#stat matches the most recent content, so the API call response is omitted, to save bandwidth.\r\n // errorCodeLookup[Dropbox.ApiError.NO_CONTENT];\r\n // The error property on {Dropbox.ApiError#response} should indicate which input parameter is invalid and why.\r\n errorCodeLookup[Dropbox.ApiError.INVALID_PARAM] = ErrorCode.EINVAL;\r\n // The OAuth token used for the request will never become valid again, so the user should be re-authenticated.\r\n errorCodeLookup[Dropbox.ApiError.INVALID_TOKEN] = ErrorCode.EPERM;\r\n // This indicates a bug in dropbox.js and should never occur under normal circumstances.\r\n // ^ Actually, that's false. This occurs when you try to move folders to themselves, or move a file over another file.\r\n errorCodeLookup[Dropbox.ApiError.OAUTH_ERROR] = ErrorCode.EPERM;\r\n // This happens when trying to read from a non-existing file, readdir a non-existing directory, write a file into a non-existing directory, etc.\r\n errorCodeLookup[Dropbox.ApiError.NOT_FOUND] = ErrorCode.ENOENT;\r\n // This indicates a bug in dropbox.js and should never occur under normal circumstances.\r\n errorCodeLookup[Dropbox.ApiError.INVALID_METHOD] = ErrorCode.EINVAL;\r\n // This happens when a Dropbox.Client#readdir or Dropbox.Client#stat call would return more than a maximum amount of directory entries.\r\n errorCodeLookup[Dropbox.ApiError.NOT_ACCEPTABLE] = ErrorCode.EINVAL;\r\n // This is used by some backend methods to indicate that the client needs to download server-side changes and perform conflict resolution. Under normal usage, errors with this code should never surface to the code using dropbox.js.\r\n errorCodeLookup[Dropbox.ApiError.CONFLICT] = ErrorCode.EINVAL;\r\n // Status value indicating that the application is making too many requests.\r\n errorCodeLookup[Dropbox.ApiError.RATE_LIMITED] = ErrorCode.EBUSY;\r\n // The request should be retried after some time.\r\n errorCodeLookup[Dropbox.ApiError.SERVER_ERROR] = ErrorCode.EBUSY;\r\n // Status value indicating that the user's Dropbox is over its storage quota.\r\n errorCodeLookup[Dropbox.ApiError.OVER_QUOTA] = ErrorCode.ENOSPC;\r\n}\r\n\r\ninterface ICachedPathInfo {\r\n stat: Dropbox.File.Stat;\r\n}\r\n\r\ninterface ICachedFileInfo extends ICachedPathInfo {\r\n contents: ArrayBuffer;\r\n}\r\n\r\nfunction isFileInfo(cache: ICachedPathInfo): cache is ICachedFileInfo {\r\n return cache && cache.stat.isFile;\r\n}\r\n\r\ninterface ICachedDirInfo extends ICachedPathInfo {\r\n contents: string[];\r\n}\r\n\r\nfunction isDirInfo(cache: ICachedPathInfo): cache is ICachedDirInfo {\r\n return cache && cache.stat.isFolder;\r\n}\r\n\r\nfunction isArrayBuffer(ab: any): ab is ArrayBuffer {\r\n // Accept null / undefined, too.\r\n return ab === null || ab === undefined || (typeof(ab) === 'object' && typeof(ab['byteLength']) === 'number');\r\n}\r\n\r\n/**\r\n * Wraps a Dropbox client and caches operations.\r\n */\r\nclass CachedDropboxClient
"import {BaseFileSystem, FileSystem} from '../core/file_system';\r\nimport path = require('path');\r\nimport {ApiError} from '../core/api_error';\r\n\r\n/**\r\n * The FolderAdapter file system wraps a file system, and scopes all interactions to a subfolder of that file system.\r\n */\r\nexport default class FolderAdapter extends BaseFileSystem implements FileSystem {\r\n private _wrapped: FileSystem;\r\n private _folder: string;\r\n constructor(folder: string, wrapped: FileSystem) {\r\n super();\r\n this._folder = folder;\r\n this._wrapped = wrapped;\r\n }\r\n\r\n /**\r\n * Initialize the file system. Ensures that the wrapped file system\r\n * has the given folder.\r\n */\r\n public initialize(cb: (e?: ApiError) => void) {\r\n this._wrapped.exists(this._folder, (exists: boolean) => {\r\n if (exists) {\r\n cb();\r\n } else if (this._wrapped.isReadOnly()) {\r\n cb(ApiError.ENOENT(this._folder));\r\n } else {\r\n this._wrapped.mkdir(this._folder, 0x1ff, cb);\r\n }\r\n });\r\n }\r\n\r\n public getName(): string { return this._wrapped.getName(); }\r\n public isReadOnly(): boolean { return this._wrapped.isReadOnly(); }\r\n public supportsProps(): boolean { return this._wrapped.supportsProps(); }\r\n public supportsSynch(): boolean { return this._wrapped.supportsSynch(); }\r\n public supportsLinks(): boolean { return false; }\r\n\r\n public static isAvailable(): boolean {\r\n return true;\r\n }\r\n}\r\n\r\nfunction translateError(folder: string, e: any): any {\r\n if (e !== null && typeof e === 'object') {\r\n let err = <ApiError> e;\r\n let p = err.path;\r\n if (p) {\r\n p = '/' + path.relative(folder, p);\r\n err.message = err.message.replace(err.path, p);\r\n err.path = p;\r\n }\r\n }\r\n return e;\r\n}\r\n\r\nfunction wrapCallback(folder: string, cb: any): any {\r\n if (typeof cb === 'function') {\r\n return function(err) {\r\n if (arguments.length > 0) {\r\n arguments[0] = translateError(folder, err);\r\n }\r\n (<Function> cb).apply(null, arguments);\r\n };\r\n } else {\r\n return cb;\r\n }\r\n}\r\n\r\nfunction wrapFunction(name: string, wrapFirst: boolean, wrapSecond: boolean): Function {\r\n if (name.slice(name.length - 4) !== 'Sync') {\r\n // Async function. Translate error in callback.\r\n return function() {\r\n if (arguments.length > 0) {\r\n if (wrapFirst) {\r\n arguments[0] = path.join(this._folder, arguments[0]);\r\n }\r\n if (wrapSecond) {\r\n arguments[1] = path.join(this._folder, arguments[1]);\r\n }\r\n arguments[arguments.length - 1] = wrapCallback(this._folder, arguments[arguments.length - 1]);\r\n }\r\n return this._wrapped[name].apply(this._wrapped, arguments);\r\n };\r\n } else {\r\n // Sync function. Translate error in catch.\r\n return function() {\r\n try {\r\n if (wrapFirst) {\r\n arguments[0] = path.join(this._folder, arguments[0]);\r\n }\r\n if (wrapSecond) {\r\n arguments[1] = path.join(this._folder, arguments[1]);\r\n }\r\n return this._wrapped[name].apply(this._wrapped, arguments);\r\n } catch (e) {\r\n throw translateError(this._folder, e);\r\n }\r\n };\r\n }\r\n}\r\n\r\n// First argument is a path.\r\n['diskSpace', 'stat', 'statSync', 'open', 'openSync', 'unlink', 'unlinkSync',\r\n 'rmdir', 'rmdirSync' ,'mkdir', 'mkdirSync', 'readdir', 'readdirSync', 'exists',\r\n 'existsSync', 'realpath', 'realpathSync', 'truncate', 'truncateSync', 'readFile',\r\n 'readFileSync', 'writeFile', 'writeFileSync', 'appendFile', 'appendFileSync',\r\n 'chmod', 'chmodSync', 'chown', 'chownSync', 'utimes', 'utimeSync', 'readlink',\r\n 'readlinkSync'].forEach((name: string) => {\r\n FolderAdapter.prototype[name] = wrapFunction(name, true, false);\r\n});\r\n\r\n// First and second arguments are paths.\r\n['rename', 'renameSync', 'link', 'linkSync', 'symlink', 'symlinkSync'].forEach((name: string) => {\r\n FolderA
"import preload_file = require('../generic/preload_file');\r\nimport file_system = require('../core/file_system');\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport {FileFlag, ActionType} from '../core/file_flag';\r\nimport {default as Stats, FileType} from '../core/node_fs_stats';\r\nimport file = require('../core/file');\r\nimport path = require('path');\r\nimport global = require('../core/global');\r\nimport async = require('async');\r\nimport {buffer2ArrayBuffer, arrayBuffer2Buffer} from '../core/util';\r\n\r\nfunction isDirectoryEntry(entry: Entry): entry is DirectoryEntry {\r\n return entry.isDirectory;\r\n}\r\n\r\nvar _getFS: (type:number, size:number, successCallback: FileSystemCallback, errorCallback?: ErrorCallback) => void = global.webkitRequestFileSystem || global.requestFileSystem || null;\r\n\r\nfunction _requestQuota(type: number, size: number, success: (size: number) => void, errorCallback: ErrorCallback) {\r\n // We cast navigator and window to '<any>' because everything here is\r\n // nonstandard functionality, despite the fact that Chrome has the only\r\n // implementation of the HTML5FS and is likely driving the standardization\r\n // process. Thus, these objects defined off of navigator and window are not\r\n // present in the DefinitelyTyped TypeScript typings for FileSystem.\r\n if (typeof (<any> navigator)['webkitPersistentStorage'] !== 'undefined') {\r\n switch(type) {\r\n case global.PERSISTENT:\r\n (<any> navigator).webkitPersistentStorage.requestQuota(size, success, errorCallback);\r\n break;\r\n case global.TEMPORARY:\r\n (<any> navigator).webkitTemporaryStorage.requestQuota(size, success, errorCallback);\r\n break\r\n default:\r\n errorCallback(new TypeError(`Invalid storage type: ${type}`));\r\n break;\r\n }\r\n } else {\r\n (<any> global).webkitStorageInfo.requestQuota(type, size, success, errorCallback);\r\n }\r\n}\r\n\r\nfunction _toArray(list?: any[]): any[] {\r\n return Array.prototype.slice.call(list || [], 0);\r\n}\r\n\r\n// A note about getFile and getDirectory options:\r\n// These methods are called at numerous places in this file, and are passed\r\n// some combination of these two options:\r\n// - create: If true, the entry will be created if it doesn't exist.\r\n// If false, an error will be thrown if it doesn't exist.\r\n// - exclusive: If true, only create the entry if it doesn't already exist,\r\n// and throw an error if it does.\r\n\r\nexport class HTML5FSFile extends preload_file.PreloadFile<HTML5FS> implements file.File {\r\n constructor(_fs: HTML5FS, _path: string, _flag: FileFlag, _stat: Stats, contents?: NodeBuffer) {\r\n super(_fs, _path, _flag, _stat, contents);\r\n }\r\n\r\n public sync(cb: (e?: ApiError) => void): void {\r\n if (this.isDirty()) {\r\n // Don't create the file (it should already have been created by `open`)\r\n var opts = {\r\n create: false\r\n };\r\n var _fs = this._fs;\r\n var success: FileEntryCallback = (entry) => {\r\n entry.createWriter((writer) => {\r\n var buffer = this.getBuffer();\r\n var blob = new Blob([buffer2ArrayBuffer(buffer)]);\r\n var length = blob.size;\r\n writer.onwriteend = () => {\r\n writer.onwriteend = null;\r\n writer.truncate(length);\r\n this.resetDirty();\r\n cb();\r\n };\r\n writer.onerror = (err: DOMError) => {\r\n cb(_fs.convert(err, this.getPath(), false));\r\n };\r\n writer.write(blob);\r\n });\r\n };\r\n var error = (err: DOMError) => {\r\n cb(_fs.convert(err, this.getPath(), false));\r\n };\r\n _fs.fs.root.getFile(this.getPath(), opts, success, error);\r\n } else {\r\n cb();\r\n }\r\n }\r\n\r\n public close(cb: (e?: ApiError) => void): void {\r\n this.sync(cb);\r\n }\r\n}\r\n\r\nexport default class HTML5FS extends file_system.BaseFileSystem implements file_system.Fi
"import kvfs = require('../generic/key_value_filesystem');\r\n\r\n/**\r\n * A simple in-memory key-value store backed by a JavaScript object.\r\n */\r\nexport class InMemoryStore implements kvfs.SyncKeyValueStore, kvfs.SimpleSyncStore {\r\n private store: { [key: string]: NodeBuffer } = {};\r\n\r\n public name() { return 'In-memory'; }\r\n public clear() { this.store = {}; }\r\n\r\n public beginTransaction(type: string): kvfs.SyncKeyValueRWTransaction {\r\n return new kvfs.SimpleSyncRWTransaction(this);\r\n }\r\n\r\n public get(key: string): NodeBuffer {\r\n return this.store[key];\r\n }\r\n\r\n public put(key: string, data: NodeBuffer, overwrite: boolean): boolean {\r\n if (!overwrite && this.store.hasOwnProperty(key)) {\r\n return false;\r\n }\r\n this.store[key] = data;\r\n return true;\r\n }\r\n\r\n public del(key: string): void {\r\n delete this.store[key];\r\n }\r\n}\r\n\r\n/**\r\n * A simple in-memory file system backed by an InMemoryStore.\r\n */\r\nexport default class InMemoryFileSystem extends kvfs.SyncKeyValueFileSystem {\r\n constructor() {\r\n super({ store: new InMemoryStore() });\r\n }\r\n}\r\n",
"import kvfs = require('../generic/key_value_filesystem');\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport global = require('../core/global');\r\nimport {arrayBuffer2Buffer, buffer2ArrayBuffer} from '../core/util';\r\n/**\r\n * Get the indexedDB constructor for the current browser.\r\n */\r\nvar indexedDB: IDBFactory = global.indexedDB ||\r\n (<any>global).mozIndexedDB ||\r\n (<any>global).webkitIndexedDB ||\r\n global.msIndexedDB;\r\n\r\n/**\r\n * Converts a DOMException or a DOMError from an IndexedDB event into a\r\n * standardized BrowserFS API error.\r\n */\r\nfunction convertError(e: {name: string}, message: string = e.toString()): ApiError {\r\n switch(e.name) {\r\n case \"NotFoundError\":\r\n return new ApiError(ErrorCode.ENOENT, message);\r\n case \"QuotaExceededError\":\r\n return new ApiError(ErrorCode.ENOSPC, message);\r\n default:\r\n // The rest do not seem to map cleanly to standard error codes.\r\n return new ApiError(ErrorCode.EIO, message);\r\n }\r\n}\r\n\r\n/**\r\n * Produces a new onerror handler for IDB. Our errors are always fatal, so we\r\n * handle them generically: Call the user-supplied callback with a translated\r\n * version of the error, and let the error bubble up.\r\n */\r\nfunction onErrorHandler(cb: (e: ApiError) => void,\r\n code: ErrorCode = ErrorCode.EIO, message: string = null): (e?: any) => void {\r\n return function (e?: any): void {\r\n // Prevent the error from canceling the transaction.\r\n e.preventDefault();\r\n cb(new ApiError(code, message));\r\n };\r\n}\r\n\r\nexport class IndexedDBROTransaction implements kvfs.AsyncKeyValueROTransaction {\r\n constructor(public tx: IDBTransaction, public store: IDBObjectStore) { }\r\n\r\n get(key: string, cb: (e: ApiError, data?: NodeBuffer) => void): void {\r\n try {\r\n var r: IDBRequest = this.store.get(key);\r\n r.onerror = onErrorHandler(cb);\r\n r.onsuccess = (event) => {\r\n // IDB returns the value 'undefined' when you try to get keys that\r\n // don't exist. The caller expects this behavior.\r\n var result: any = (<any>event.target).result;\r\n if (result === undefined) {\r\n cb(null, result);\r\n } else {\r\n // IDB data is stored as an ArrayBuffer\r\n cb(null, arrayBuffer2Buffer(result));\r\n }\r\n };\r\n } catch (e) {\r\n cb(convertError(e));\r\n }\r\n }\r\n}\r\n\r\nexport class IndexedDBRWTransaction extends IndexedDBROTransaction implements kvfs.AsyncKeyValueRWTransaction, kvfs.AsyncKeyValueROTransaction {\r\n constructor(tx: IDBTransaction, store: IDBObjectStore) {\r\n super(tx, store);\r\n }\r\n\r\n public put(key: string, data: NodeBuffer, overwrite: boolean, cb: (e: ApiError, committed?: boolean) => void): void {\r\n try {\r\n var arraybuffer = buffer2ArrayBuffer(data),\r\n r: IDBRequest;\r\n if (overwrite) {\r\n r = this.store.put(arraybuffer, key);\r\n } else {\r\n // 'add' will never overwrite an existing key.\r\n r = this.store.add(arraybuffer, key);\r\n }\r\n // XXX: NEED TO RETURN FALSE WHEN ADD HAS A KEY CONFLICT. NO ERROR.\r\n r.onerror = onErrorHandler(cb);\r\n r.onsuccess = (event) => {\r\n cb(null, true);\r\n };\r\n } catch (e) {\r\n cb(convertError(e));\r\n }\r\n }\r\n\r\n public del(key: string, cb: (e?: ApiError) => void): void {\r\n try {\r\n // NOTE: IE8 has a bug with identifiers named 'delete' unless used as a string\r\n // like this.\r\n // http://stackoverflow.com/a/26479152\r\n var r: IDBRequest = this.store['delete'](key);\r\n r.onerror = onErrorHandler(cb);\r\n r.onsuccess = (event) => {\r\n cb();\r\n };\r\n } catch (e) {\r\n cb(convertError(e));\r\n }\r\n }\r\n\r\n public commit(cb: (e?: ApiError) => void): void {\r\n // Return to the event loop to commit the transaction.\r\n setTimeout(cb, 0);\r\
"import kvfs = require('../generic/key_value_filesystem');\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport global = require('../core/global');\r\n\r\n// Some versions of FF and all versions of IE do not support the full range of\r\n// 16-bit numbers encoded as characters, as they enforce UTF-16 restrictions.\r\n// http://stackoverflow.com/questions/11170716/are-there-any-characters-that-are-not-allowed-in-localstorage/11173673#11173673\r\nvar supportsBinaryString: boolean = false,\r\n binaryEncoding: string;\r\ntry {\r\n global.localStorage.setItem(\"__test__\", String.fromCharCode(0xD800));\r\n supportsBinaryString = global.localStorage.getItem(\"__test__\") === String.fromCharCode(0xD800);\r\n} catch (e) {\r\n // IE throws an exception.\r\n supportsBinaryString = false;\r\n}\r\nbinaryEncoding = supportsBinaryString ? 'binary_string' : 'binary_string_ie';\r\nif (!Buffer.isEncoding(binaryEncoding)) {\r\n // Fallback for non BrowserFS implementations of buffer that lack a\r\n // binary_string format.\r\n binaryEncoding = \"base64\";\r\n}\r\n\r\n/**\r\n * A synchronous key-value store backed by localStorage.\r\n */\r\nexport class LocalStorageStore implements kvfs.SyncKeyValueStore, kvfs.SimpleSyncStore {\r\n constructor() { }\r\n\r\n public name(): string {\r\n return 'LocalStorage';\r\n }\r\n\r\n public clear(): void {\r\n global.localStorage.clear();\r\n }\r\n\r\n public beginTransaction(type: string): kvfs.SyncKeyValueRWTransaction {\r\n // No need to differentiate.\r\n return new kvfs.SimpleSyncRWTransaction(this);\r\n }\r\n\r\n public get(key: string): NodeBuffer {\r\n try {\r\n var data = global.localStorage.getItem(key);\r\n if (data !== null) {\r\n return new Buffer(data, binaryEncoding);\r\n }\r\n } catch (e) {\r\n\r\n }\r\n // Key doesn't exist, or a failure occurred.\r\n return undefined;\r\n }\r\n\r\n public put(key: string, data: NodeBuffer, overwrite: boolean): boolean {\r\n try {\r\n if (!overwrite && global.localStorage.getItem(key) !== null) {\r\n // Don't want to overwrite the key!\r\n return false;\r\n }\r\n global.localStorage.setItem(key, data.toString(binaryEncoding));\r\n return true;\r\n } catch (e) {\r\n throw new ApiError(ErrorCode.ENOSPC, \"LocalStorage is full.\");\r\n }\r\n }\r\n\r\n public del(key: string): void {\r\n try {\r\n global.localStorage.removeItem(key);\r\n } catch (e) {\r\n throw new ApiError(ErrorCode.EIO, \"Unable to delete key \" + key + \": \" + e);\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * A synchronous file system backed by localStorage. Connects our\r\n * LocalStorageStore to our SyncKeyValueFileSystem.\r\n */\r\nexport default class LocalStorageFileSystem extends kvfs.SyncKeyValueFileSystem {\r\n constructor() { super({ store: new LocalStorageStore() }); }\r\n public static isAvailable(): boolean {\r\n return typeof global.localStorage !== 'undefined';\r\n }\r\n}\r\n",
"import file_system = require('../core/file_system');\r\nimport InMemoryFileSystem from './InMemory';\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport fs = require('../core/node_fs');\r\nimport path = require('path');\r\nimport {mkdirpSync} from '../core/util';\r\n\r\n/**\r\n * The MountableFileSystem allows you to mount multiple backend types or\r\n * multiple instantiations of the same backend into a single file system tree.\r\n * The file systems do not need to know about each other; all interactions are\r\n * automatically facilitated through this interface.\r\n *\r\n * For example, if a file system is mounted at /mnt/blah, and a request came in\r\n * for /mnt/blah/foo.txt, the file system would see a request for /foo.txt.\r\n */\r\nexport default class MountableFileSystem extends file_system.BaseFileSystem implements file_system.FileSystem {\r\n private mntMap: {[path: string]: file_system.FileSystem};\r\n // Contains the list of mount points in mntMap, sorted by string length in decreasing order.\r\n // Ensures that we scan the most specific mount points for a match first, which lets us\r\n // nest mount points.\r\n private mountList: string[] = [];\r\n private rootFs: file_system.FileSystem;\r\n constructor() {\r\n super();\r\n this.mntMap = {};\r\n // The InMemory file system serves purely to provide directory listings for\r\n // mounted file systems.\r\n this.rootFs = new InMemoryFileSystem();\r\n }\r\n\r\n /**\r\n * Mounts the file system at the given mount point.\r\n */\r\n public mount(mountPoint: string, fs: file_system.FileSystem): void {\r\n if (mountPoint[0] !== '/') {\r\n mountPoint = `/${mountPoint}`;\r\n }\r\n mountPoint = path.resolve(mountPoint);\r\n if (this.mntMap[mountPoint]) {\r\n throw new ApiError(ErrorCode.EINVAL, \"Mount point \" + mountPoint + \" is already taken.\");\r\n }\r\n mkdirpSync(mountPoint, 0x1ff, this.rootFs);\r\n this.mntMap[mountPoint] = fs;\r\n this.mountList.push(mountPoint);\r\n this.mountList = this.mountList.sort((a, b) => b.length - a.length);\r\n }\r\n\r\n public umount(mountPoint: string): void {\r\n if (mountPoint[0] !== '/') {\r\n mountPoint = `/${mountPoint}`;\r\n }\r\n mountPoint = path.resolve(mountPoint);\r\n if (!this.mntMap[mountPoint]) {\r\n throw new ApiError(ErrorCode.EINVAL, \"Mount point \" + mountPoint + \" is already unmounted.\");\r\n }\r\n delete this.mntMap[mountPoint];\r\n this.mountList.splice(this.mountList.indexOf(mountPoint), 1);\r\n\r\n while (mountPoint !== '/') {\r\n if (this.rootFs.readdirSync(mountPoint).length === 0) {\r\n this.rootFs.rmdirSync(mountPoint);\r\n mountPoint = path.dirname(mountPoint);\r\n } else {\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Returns the file system that the path points to.\r\n */\r\n public _getFs(path: string): {fs: file_system.FileSystem; path: string} {\r\n let mountList = this.mountList, len = mountList.length;\r\n for (let i = 0; i < len; i++) {\r\n let mountPoint = mountList[i];\r\n // We know path is normalized, so it is a substring of the mount point.\r\n if (mountPoint.length <= path.length && path.indexOf(mountPoint) === 0) {\r\n path = path.substr(mountPoint.length > 1 ? mountPoint.length : 0);\r\n if (path === '') {\r\n path = '/';\r\n }\r\n return {fs: this.mntMap[mountPoint], path: path};\r\n }\r\n }\r\n // Query our root file system.\r\n return {fs: this.rootFs, path: path};\r\n }\r\n\r\n // Global information methods\r\n\r\n public getName(): string {\r\n return 'MountableFileSystem';\r\n }\r\n\r\n public static isAvailable(): boolean {\r\n return true;\r\n }\r\n\r\n public diskSpace(path: string, cb: (total: number, free: number) => void): void {\r\n cb(0, 0);\r\n }\r\n\r\n public isReadOnly(): boolean {\r\n return false;\r\n }\r\n\r\n public supportsLinks(): boolean {\r\n // I'm not ready for cross-FS links yet.\r\n return
"import file_system = require('../core/file_system');\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport {FileFlag, ActionType} from '../core/file_flag';\r\nimport util = require('../core/util');\r\nimport file = require('../core/file');\r\nimport Stats from '../core/node_fs_stats';\r\nimport preload_file = require('../generic/preload_file');\r\nimport path = require('path');\r\nlet deletionLogPath = '/.deletedFiles.log';\r\n\r\n/**\r\n * Given a read-only mode, makes it writable.\r\n */\r\nfunction makeModeWritable(mode: number): number {\r\n return 0x92 | mode;\r\n}\r\n\r\n/**\r\n * Overlays a RO file to make it writable.\r\n */\r\nclass OverlayFile extends preload_file.PreloadFile<OverlayFS> implements file.File {\r\n constructor(fs: OverlayFS, path: string, flag: FileFlag, stats: Stats, data: Buffer) {\r\n super(fs, path, flag, stats, data);\r\n }\r\n\r\n public syncSync(): void {\r\n if (this.isDirty()) {\r\n this._fs._syncSync(this);\r\n this.resetDirty();\r\n }\r\n }\r\n\r\n public closeSync(): void {\r\n this.syncSync();\r\n }\r\n}\r\n\r\n/**\r\n * OverlayFS makes a read-only filesystem writable by storing writes on a second,\r\n * writable file system. Deletes are persisted via metadata stored on the writable\r\n * file system.\r\n *\r\n * Currently only works for two synchronous file systems.\r\n */\r\nexport default class OverlayFS extends file_system.SynchronousFileSystem implements file_system.FileSystem {\r\n private _writable: file_system.FileSystem;\r\n private _readable: file_system.FileSystem;\r\n private _isInitialized: boolean = false;\r\n private _initializeCallbacks: ((e?: ApiError) => void)[] = [];\r\n private _deletedFiles: {[path: string]: boolean} = {};\r\n private _deleteLog: file.File = null;\r\n\r\n constructor(writable: file_system.FileSystem, readable: file_system.FileSystem) {\r\n super();\r\n this._writable = writable;\r\n this._readable = readable;\r\n if (this._writable.isReadOnly()) {\r\n throw new ApiError(ErrorCode.EINVAL, \"Writable file system must be writable.\");\r\n }\r\n if (!this._writable.supportsSynch() || !this._readable.supportsSynch()) {\r\n throw new ApiError(ErrorCode.EINVAL, \"OverlayFS currently only operates on synchronous file systems.\");\r\n }\r\n }\r\n\r\n private checkInitialized(): void {\r\n if (!this._isInitialized) {\r\n throw new ApiError(ErrorCode.EPERM, \"OverlayFS is not initialized. Please initialize OverlayFS using its initialize() method before using it.\");\r\n }\r\n }\r\n\r\n public getOverlayedFileSystems(): { readable: file_system.FileSystem; writable: file_system.FileSystem; } {\r\n return {\r\n readable: this._readable,\r\n writable: this._writable\r\n };\r\n }\r\n\r\n /**\r\n * With the given path, create the needed parent directories on the writable storage\r\n * should they not exist. Use modes from the read-only storage.\r\n */\r\n private createParentDirectories(p: string): void {\r\n var parent = path.dirname(p), toCreate: string[] = [];\r\n while (!this._writable.existsSync(parent)) {\r\n toCreate.push(parent);\r\n parent = path.dirname(parent);\r\n }\r\n toCreate = toCreate.reverse();\r\n\r\n toCreate.forEach((p: string) => {\r\n this._writable.mkdirSync(p, this.statSync(p, false).mode);\r\n });\r\n }\r\n\r\n public static isAvailable(): boolean {\r\n return true;\r\n }\r\n\r\n public _syncSync(file: preload_file.PreloadFile<any>): void {\r\n this.createParentDirectories(file.getPath());\r\n this._writable.writeFileSync(file.getPath(), file.getBuffer(), null, FileFlag.getFileFlag('w'), file.getStats().mode);\r\n }\r\n\r\n public getName() {\r\n return \"OverlayFS\";\r\n }\r\n\r\n /**\r\n * Called once to load up metadata stored on the writable file system.\r\n */\r\n public initialize(cb: (err?: ApiError) => void): void {\r\n const callbackArray = this._initializeCallbacks;\r\n\r\n const end = (e?: ApiError): void => {\r\n this._isInitialized
"import file_system = require('../core/file_system');\r\nimport {ApiError} from '../core/api_error';\r\nimport file_flag = require('../core/file_flag');\r\nimport {buffer2ArrayBuffer, arrayBuffer2Buffer} from '../core/util';\r\nimport file = require('../core/file');\r\nimport {default as Stats, FileType} from '../core/node_fs_stats';\r\nimport preload_file = require('../generic/preload_file');\r\nimport global = require('../core/global');\r\nimport fs = require('../core/node_fs');\r\n\r\ninterface IBrowserFSMessage {\r\n browserfsMessage: boolean;\r\n}\r\n\r\nenum SpecialArgType {\r\n // Callback\r\n CB,\r\n // File descriptor\r\n FD,\r\n // API error\r\n API_ERROR,\r\n // Stats object\r\n STATS,\r\n // Initial probe for file system information.\r\n PROBE,\r\n // FileFlag object.\r\n FILEFLAG,\r\n // Buffer object.\r\n BUFFER,\r\n // Generic Error object.\r\n ERROR\r\n}\r\n\r\ninterface ISpecialArgument {\r\n type: SpecialArgType;\r\n}\r\n\r\ninterface IProbeResponse extends ISpecialArgument {\r\n isReadOnly: boolean;\r\n supportsLinks: boolean;\r\n supportsProps: boolean;\r\n}\r\n\r\ninterface ICallbackArgument extends ISpecialArgument {\r\n // The callback ID.\r\n id: number;\r\n}\r\n\r\n/**\r\n * Converts callback arguments into ICallbackArgument objects, and back\r\n * again.\r\n */\r\nclass CallbackArgumentConverter {\r\n private _callbacks: { [id: number]: Function } = {};\r\n private _nextId: number = 0;\r\n\r\n public toRemoteArg(cb: Function): ICallbackArgument {\r\n var id = this._nextId++;\r\n this._callbacks[id] = cb;\r\n return {\r\n type: SpecialArgType.CB,\r\n id: id\r\n };\r\n }\r\n\r\n public toLocalArg(id: number): Function {\r\n var cb = this._callbacks[id];\r\n delete this._callbacks[id];\r\n return cb;\r\n }\r\n}\r\n\r\ninterface IFileDescriptorArgument extends ISpecialArgument {\r\n // The file descriptor's id on the remote side.\r\n id: number;\r\n // The entire file's data, as an array buffer.\r\n data: ArrayBuffer;\r\n // The file's stat object, as an array buffer.\r\n stat: ArrayBuffer;\r\n // The path to the file.\r\n path: string;\r\n // The flag of the open file descriptor.\r\n flag: string;\r\n}\r\n\r\nclass FileDescriptorArgumentConverter {\r\n private _fileDescriptors: { [id: number]: file.File } = {};\r\n private _nextId: number = 0;\r\n\r\n public toRemoteArg(fd: file.File, p: string, flag: file_flag.FileFlag, cb: (err: ApiError, arg?: IFileDescriptorArgument) => void): void {\r\n var id = this._nextId++,\r\n data: ArrayBuffer,\r\n stat: ArrayBuffer,\r\n argsLeft: number = 2;\r\n this._fileDescriptors[id] = fd;\r\n\r\n // Extract needed information asynchronously.\r\n fd.stat((err, stats) => {\r\n if (err) {\r\n cb(err);\r\n } else {\r\n stat = bufferToTransferrableObject(stats.toBuffer());\r\n // If it's a readable flag, we need to grab contents.\r\n if (flag.isReadable()) {\r\n fd.read(new Buffer(stats.size), 0, stats.size, 0, (err, bytesRead, buff) => {\r\n if (err) {\r\n cb(err);\r\n } else {\r\n data = bufferToTransferrableObject(buff);\r\n cb(null, {\r\n type: SpecialArgType.FD,\r\n id: id,\r\n data: data,\r\n stat: stat,\r\n path: p,\r\n flag: flag.getFlagString()\r\n });\r\n }\r\n });\r\n } else {\r\n // File is not readable, which means writing to it will append or\r\n // truncate/replace existing contents. Return an empty arraybuffer.\r\n cb(null, {\r\n type: SpecialArgType.FD,\r\n id: id,\r\n data: new ArrayBuffer(0),\r\n stat: stat,\r\n path: p,\r\n flag: flag.getFlagString()\r\n });\r\n }\r\n }\r\n });\r\n }\r\n\r\n private _applyFdChanges(remoteFd: IFileDescriptorArgument, cb: (err: ApiError, fd?: file.File) => void): vo
"import file_system = require('../core/file_system');\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport {FileFlag, ActionType} from '../core/file_flag';\r\nimport {copyingSlice} from '../core/util';\r\nimport file = require('../core/file');\r\nimport Stats from '../core/node_fs_stats';\r\nimport preload_file = require('../generic/preload_file');\r\nimport xhr = require('../generic/xhr');\r\nimport {FileIndex, DirInode, FileInode, Inode, isFileInode, isDirInode} from '../generic/file_index';\r\n\r\n/**\r\n * Try to convert the given buffer into a string, and pass it to the callback.\r\n * Optimization that removes the needed try/catch into a helper function, as\r\n * this is an uncommon case.\r\n */\r\nfunction tryToString(buff: Buffer, encoding: string, cb: (e: ApiError, rv?: string) => void) {\r\n try {\r\n cb(null, buff.toString(encoding));\r\n } catch (e) {\r\n cb(e);\r\n }\r\n}\r\n\r\n/**\r\n * A simple filesystem backed by XmlHttpRequests.\r\n */\r\nexport default class XmlHttpRequest extends file_system.BaseFileSystem implements file_system.FileSystem {\r\n private _index: FileIndex<{}>;\r\n public prefixUrl: string;\r\n /**\r\n * Constructs the file system.\r\n * @param listingUrlOrObj index object or the path to the JSON file index generated by\r\n * tools/XHRIndexer.coffee. This can be relative to the current webpage URL\r\n * or absolutely specified.\r\n * @param prefixUrl The url prefix to use for all web-server requests.\r\n */\r\n constructor(listingUrlOrObj: string | Object, prefixUrl: string = '') {\r\n super();\r\n if (!listingUrlOrObj) {\r\n listingUrlOrObj = 'index.json';\r\n }\r\n // prefix_url must end in a directory separator.\r\n if (prefixUrl.length > 0 && prefixUrl.charAt(prefixUrl.length - 1) !== '/') {\r\n prefixUrl = prefixUrl + '/';\r\n }\r\n this.prefixUrl = prefixUrl;\r\n\r\n let listing: Object = null;\r\n if (typeof(listingUrlOrObj) === \"string\") {\r\n listing = this._requestFileSync(<string> listingUrlOrObj, 'json');\r\n if (!listing) {\r\n throw new Error(\"Unable to find listing at URL: ${listingUrlOrObj}\");\r\n }\r\n } else {\r\n listing = listingUrlOrObj;\r\n }\r\n\r\n this._index = FileIndex.fromListing(listing);\r\n }\r\n\r\n public empty(): void {\r\n this._index.fileIterator(function(file: Stats) {\r\n file.file_data = null;\r\n });\r\n }\r\n\r\n private getXhrPath(filePath: string): string {\r\n if (filePath.charAt(0) === '/') {\r\n filePath = filePath.slice(1);\r\n }\r\n return this.prefixUrl + filePath;\r\n }\r\n\r\n /**\r\n * Only requests the HEAD content, for the file size.\r\n */\r\n public _requestFileSizeAsync(path: string, cb: (err: ApiError, size?: number) => void): void {\r\n xhr.getFileSizeAsync(this.getXhrPath(path), cb);\r\n }\r\n public _requestFileSizeSync(path: string): number {\r\n return xhr.getFileSizeSync(this.getXhrPath(path));\r\n }\r\n\r\n /**\r\n * Asynchronously download the given file.\r\n */\r\n private _requestFileAsync(p: string, type: 'buffer', cb: (err: ApiError, data?: NodeBuffer) => void): void;\r\n private _requestFileAsync(p: string, type: 'json', cb: (err: ApiError, data?: any) => void): void;\r\n private _requestFileAsync(p: string, type: string, cb: (err: ApiError, data?: any) => void): void;\r\n private _requestFileAsync(p: string, type: string, cb: (err: ApiError, data?: any) => void): void {\r\n xhr.asyncDownloadFile(this.getXhrPath(p), type, cb);\r\n }\r\n\r\n /**\r\n * Synchronously download the given file.\r\n */\r\n private _requestFileSync(p: string, type: 'buffer'): NodeBuffer;\r\n private _requestFileSync(p: string, type: 'json'): any;\r\n private _requestFileSync(p: string, type: string): any;\r\n private _requestFileSync(p: string, type: string): any {\r\n return xhr.syncDownloadFile(this.getXhrPath(p), type);\r\n }\r\n\r\n public getName(): string {\r\n return 'XmlHttpRequest';\r\n }\r\n\r\n public static isAvailable(): boolean
"/**\r\n * Zip file-backed filesystem\r\n * Implemented according to the standard:\r\n * http://www.pkware.com/documents/casestudies/APPNOTE.TXT\r\n *\r\n * While there are a few zip libraries for JavaScript (e.g. JSZip and zip.js),\r\n * they are not a good match for BrowserFS. In particular, these libraries\r\n * perform a lot of unneeded data copying, and eagerly decompress every file\r\n * in the zip file upon loading to check the CRC32. They also eagerly decode\r\n * strings. Furthermore, these libraries duplicate functionality already present\r\n * in BrowserFS (e.g. UTF-8 decoding and binary data manipulation).\r\n *\r\n * This filesystem takes advantage of BrowserFS's Buffer implementation, which\r\n * efficiently represents the zip file in memory (in both ArrayBuffer-enabled\r\n * browsers *and* non-ArrayBuffer browsers), and which can neatly be 'sliced'\r\n * without copying data. Each struct defined in the standard is represented with\r\n * a buffer slice pointing to an offset in the zip file, and has getters for\r\n * each field. As we anticipate that this data will not be read often, we choose\r\n * not to store each struct field in the JavaScript object; instead, to reduce\r\n * memory consumption, we retrieve it directly from the binary data each time it\r\n * is requested.\r\n *\r\n * When the filesystem is instantiated, we determine the directory structure\r\n * of the zip file as quickly as possible. We lazily decompress and check the\r\n * CRC32 of files. We do not cache decompressed files; if this is a desired\r\n * feature, it is best implemented as a generic file system wrapper that can\r\n * cache data from arbitrary file systems.\r\n *\r\n * For inflation, we use `pajo`'s implementation:\r\n * https://github.com/nodeca/pako\r\n *\r\n * Unfortunately, their implementation falls back to an array of bytes for non-\r\n * TypedArray browsers, which is results in a much larger memory footprint in\r\n * those browsers. Perhaps one day we'll have an implementation of inflate that\r\n * works on Buffers? :)\r\n *\r\n * Current limitations:\r\n * * No encryption.\r\n * * No ZIP64 support.\r\n * * Read-only.\r\n * Write support would require that we:\r\n * - Keep track of changed/new files.\r\n * - Compress changed files, and generate appropriate metadata for each.\r\n * - Update file offsets for other files in the zip file.\r\n * - Stream it out to a location.\r\n * This isn't that bad, so we might do this at a later date.\r\n */\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport {default as Stats, FileType} from '../core/node_fs_stats';\r\nimport file_system = require('../core/file_system');\r\nimport file = require('../core/file');\r\nimport {FileFlag, ActionType} from '../core/file_flag';\r\nimport preload_file = require('../generic/preload_file');\r\nimport {Arrayish, buffer2Arrayish, arrayish2Buffer, copyingSlice} from '../core/util';\r\nimport ExtendedASCII from 'bfs-buffer/js/extended_ascii';\r\nvar inflateRaw: {\r\n (data: Arrayish<number>, options?: {\r\n chunkSize: number;\r\n }): Arrayish<number>;\r\n} = require('pako/dist/pako_inflate.min').inflateRaw;\r\nimport {FileIndex, DirInode, FileInode, isDirInode, isFileInode} from '../generic/file_index';\r\n\r\n\r\n/**\r\n * 4.4.2.2: Indicates the compatibiltiy of a file's external attributes.\r\n */\r\nexport enum ExternalFileAttributeType {\r\n MSDOS = 0, AMIGA = 1, OPENVMS = 2, UNIX = 3, VM_CMS = 4, ATARI_ST = 5,\r\n OS2_HPFS = 6, MAC = 7, Z_SYSTEM = 8, CP_M = 9, NTFS = 10, MVS = 11, VSE = 12,\r\n ACORN_RISC = 13, VFAT = 14, ALT_MVS = 15, BEOS = 16, TANDEM = 17, OS_400 = 18,\r\n OSX = 19\r\n}\r\n\r\n/**\r\n * 4.4.5\r\n */\r\nexport enum CompressionMethod {\r\n STORED = 0, // The file is stored (no compression)\r\n SHRUNK = 1, // The file is Shrunk\r\n REDUCED_1 = 2, // The file is Reduced with compression factor 1\r\n REDUCED_2 = 3, // The file is Reduced with compression factor 2\r\n REDUCED_3 = 4, // The file is Reduced with compression factor 3\r\n REDUCED_4 = 5, // The file is Reduced
"/// <reference path=\"../typings/tsd.d.ts\" />\r\n\r\n// Shim for Browserify so we can reference tsd.d.ts without\r\n// accidentally referencing it in our *.d.ts files, which\r\n// causes problems for TypeScript projects that depend on\r\n// us.\r\n\r\nexport = require('./main');\r\n",
"import {File} from './file';\r\nimport {ApiError, ErrorCode} from './api_error';\r\nimport file_system = require('./file_system');\r\nimport {FileFlag} from './file_flag';\r\nimport path = require('path');\r\nimport Stats from './node_fs_stats';\r\n// Typing info only.\r\nimport _fs = require('fs');\r\n\r\ndeclare var __numWaiting: number;\r\ndeclare var setImmediate: (cb: Function) => void;\r\n\r\n/**\r\n * Wraps a callback with a setImmediate call.\r\n * @param [Function] cb The callback to wrap.\r\n * @param [Number] numArgs The number of arguments that the callback takes.\r\n * @return [Function] The wrapped callback.\r\n */\r\nfunction wrapCb<T extends Function>(cb: T, numArgs: number): T {\r\n if (typeof cb !== 'function') {\r\n throw new ApiError(ErrorCode.EINVAL, 'Callback must be a function.');\r\n }\r\n // @todo This is used for unit testing. Maybe we should inject this logic\r\n // dynamically rather than bundle it in 'production' code.\r\n if (typeof __numWaiting === 'undefined') {\r\n __numWaiting = 0;\r\n }\r\n __numWaiting++;\r\n // We could use `arguments`, but Function.call/apply is expensive. And we only\r\n // need to handle 1-3 arguments\r\n switch (numArgs) {\r\n case 1:\r\n return <any> function(arg1: any) {\r\n setImmediate(function() {\r\n __numWaiting--;\r\n return cb(arg1);\r\n });\r\n };\r\n case 2:\r\n return <any> function(arg1: any, arg2: any) {\r\n setImmediate(function() {\r\n __numWaiting--;\r\n return cb(arg1, arg2);\r\n });\r\n };\r\n case 3:\r\n return <any> function(arg1: any, arg2: any, arg3: any) {\r\n setImmediate(function() {\r\n __numWaiting--;\r\n return cb(arg1, arg2, arg3);\r\n });\r\n };\r\n default:\r\n throw new Error('Invalid invocation of wrapCb.');\r\n }\r\n}\r\n\r\nfunction normalizeMode(mode: number|string, def: number): number {\r\n switch(typeof mode) {\r\n case 'number':\r\n // (path, flag, mode, cb?)\r\n return <number> mode;\r\n case 'string':\r\n // (path, flag, modeString, cb?)\r\n var trueMode = parseInt(<string> mode, 8);\r\n if (trueMode !== NaN) {\r\n return trueMode;\r\n }\r\n // FALL THROUGH if mode is an invalid string!\r\n default:\r\n return def;\r\n }\r\n}\r\n\r\nfunction normalizeTime(time: number | Date): Date {\r\n if (time instanceof Date) {\r\n return time;\r\n } else if (typeof time === 'number') {\r\n return new Date(time * 1000);\r\n } else {\r\n throw new ApiError(ErrorCode.EINVAL, `Invalid time.`);\r\n }\r\n}\r\n\r\nfunction normalizePath(p: string): string {\r\n // Node doesn't allow null characters in paths.\r\n if (p.indexOf('\\u0000') >= 0) {\r\n throw new ApiError(ErrorCode.EINVAL, 'Path must be a string without null bytes.');\r\n } else if (p === '') {\r\n throw new ApiError(ErrorCode.EINVAL, 'Path must not be empty.');\r\n }\r\n return path.resolve(p);\r\n}\r\n\r\nfunction normalizeOptions(options: any, defEnc: string, defFlag: string, defMode: number): {encoding: string; flag: string; mode: number} {\r\n switch (typeof options) {\r\n case 'object':\r\n return {\r\n encoding: typeof options['encoding'] !== 'undefined' ? options['encoding'] : defEnc,\r\n flag: typeof options['flag'] !== 'undefined' ? options['flag'] : defFlag,\r\n mode: normalizeMode(options['mode'], defMode)\r\n };\r\n case 'string':\r\n return {\r\n encoding: options,\r\n flag: defFlag,\r\n mode: defMode\r\n };\r\n default:\r\n return {\r\n encoding: defEnc,\r\n flag: defFlag,\r\n mode: defMode\r\n };\r\n }\r\n}\r\n\r\n// The default callback is a NOP.\r\nfunction nopCb() {};\r\n\r\n/**\r\n * The node frontend to all filesystems.\r\n * This layer handles:\r\n *\r\n * * Sanity checking inputs.\r\n * * Normalizing paths.\r\n * * Resetting stack depth for asynchronous operations which may not go through\r\n * the brow
"/**\r\n * Standard libc error codes. Add more to this enum and ErrorStrings as they are\r\n * needed.\r\n * @url http://www.gnu.org/software/libc/manual/html_node/Error-Codes.html\r\n */\r\nexport enum ErrorCode {\r\n EPERM, ENOENT, EIO, EBADF, EACCES, EBUSY, EEXIST, ENOTDIR, EISDIR, EINVAL,\r\n EFBIG, ENOSPC, EROFS, ENOTEMPTY, ENOTSUP\r\n}\r\n/**\r\n * Strings associated with each error code.\r\n */\r\nvar ErrorStrings: {[code: string]: string} = {};\r\nErrorStrings[ErrorCode.EPERM] = 'Operation not permitted.';\r\nErrorStrings[ErrorCode.ENOENT] = 'No such file or directory.';\r\nErrorStrings[ErrorCode.EIO] = 'Input/output error.';\r\nErrorStrings[ErrorCode.EBADF] = 'Bad file descriptor.';\r\nErrorStrings[ErrorCode.EACCES] = 'Permission denied.';\r\nErrorStrings[ErrorCode.EBUSY] = 'Resource busy or locked.';\r\nErrorStrings[ErrorCode.EEXIST] = 'File exists.';\r\nErrorStrings[ErrorCode.ENOTDIR] = 'File is not a directory.';\r\nErrorStrings[ErrorCode.EISDIR] = 'File is a directory.';\r\nErrorStrings[ErrorCode.EINVAL] = 'Invalid argument.';\r\nErrorStrings[ErrorCode.EFBIG] = 'File is too big.';\r\nErrorStrings[ErrorCode.ENOSPC] = 'No space left on disk.';\r\nErrorStrings[ErrorCode.EROFS] = 'Cannot modify a read-only file system.';\r\nErrorStrings[ErrorCode.ENOTEMPTY] = 'Directory is not empty.';\r\nErrorStrings[ErrorCode.ENOTSUP] = 'Operation is not supported.';\r\n\r\n/**\r\n * Represents a BrowserFS error. Passed back to applications after a failed\r\n * call to the BrowserFS API.\r\n * errno?: number;\r\n code?: string;\r\n path?: string;\r\n syscall?: string;\r\n stack?: string;\r\n */\r\nexport class ApiError extends Error implements NodeJS.ErrnoException {\r\n public errno: ErrorCode;\r\n public code: string;\r\n public path: string;\r\n // Unsupported.\r\n public syscall: string = \"\";\r\n public stack: string;\r\n\r\n /**\r\n * Represents a BrowserFS error. Passed back to applications after a failed\r\n * call to the BrowserFS API.\r\n *\r\n * Error codes mirror those returned by regular Unix file operations, which is\r\n * what Node returns.\r\n * @constructor ApiError\r\n * @param type The type of the error.\r\n * @param [message] A descriptive error message.\r\n */\r\n constructor(type: ErrorCode, message: string = ErrorStrings[type], path: string = null) {\r\n super(message);\r\n this.errno = type;\r\n this.code = ErrorCode[type];\r\n this.path = path;\r\n this.stack = (<any>new Error()).stack;\r\n this.message = `Error: ${this.code}: ${message}${this.path ? `, '${this.path}'` : ''}`;\r\n }\r\n\r\n /**\r\n * @return A friendly error message.\r\n */\r\n public toString(): string {\r\n return this.message;\r\n }\r\n\r\n public toJSON(): any {\r\n return {\r\n errno: this.errno,\r\n code: this.code,\r\n path: this.path,\r\n stack: this.stack,\r\n message: this.message\r\n };\r\n }\r\n\r\n public static fromJSON(json: any): ApiError {\r\n var err = new ApiError(0);\r\n err.errno = json.errno;\r\n err.code = json.code;\r\n err.path = json.path;\r\n err.stack = json.stack;\r\n err.message = json.message;\r\n return err;\r\n }\r\n\r\n /**\r\n * Writes the API error into a buffer.\r\n */\r\n public writeToBuffer(buffer: Buffer = new Buffer(this.bufferSize()), i: number = 0): Buffer {\r\n var bytesWritten = buffer.write(JSON.stringify(this.toJSON()), i + 4);\r\n buffer.writeUInt32LE(bytesWritten, i);\r\n return buffer;\r\n }\r\n\r\n /**\r\n * Creates an ApiError object from a buffer.\r\n */\r\n public static fromBuffer(buffer: Buffer, i: number = 0): ApiError {\r\n return ApiError.fromJSON(JSON.parse(buffer.toString('utf8', i + 4, i + 4 + buffer.readUInt32LE(i))));\r\n }\r\n\r\n /**\r\n * The size of the API error in buffer-form in bytes.\r\n */\r\n public bufferSize(): number {\r\n // 4 bytes for string length.\r\n return 4 + Buffer.byteLength(JSON.stringify(this.toJSON()));\r\n }\r\n\r\n public static FileError(code: ErrorCode, p: st
"import AsyncMirror from '../backend/AsyncMirror';\nimport Dropbox from '../backend/Dropbox';\nimport FolderAdapter from '../backend/FolderAdapter';\nimport HTML5FS from '../backend/HTML5FS';\nimport IndexedDB from '../backend/IndexedDB';\nimport InMemory from '../backend/InMemory';\nimport LocalStorage from '../backend/LocalStorage';\nimport MountableFileSystem from '../backend/MountableFileSystem';\nimport OverlayFS from '../backend/OverlayFS';\nimport WorkerFS from '../backend/WorkerFS';\nimport XmlHttpRequest from '../backend/XmlHttpRequest';\nimport ZipFS from '../backend/ZipFS';\nexport {AsyncMirror, Dropbox, FolderAdapter, HTML5FS, IndexedDB, InMemory, LocalStorage, MountableFileSystem, OverlayFS, WorkerFS, XmlHttpRequest, ZipFS};\n",
"/**\r\n * BrowserFS's main module. This is exposed in the browser via the BrowserFS global.\r\n */\r\n\r\nimport buffer = require('buffer');\r\nimport fs = require('./node_fs');\r\nimport path = require('path');\r\nimport file_system = require('./file_system');\r\nimport EmscriptenFS from '../generic/emscripten_fs';\r\nimport * as FileSystem from './backends';\r\nimport * as BFSUtils from './util';\r\n\r\nif (process['initializeTTYs']) {\r\n process['initializeTTYs']();\r\n}\r\n\r\n/**\r\n * Installs BrowserFS onto the given object.\r\n * We recommend that you run install with the 'window' object to make things\r\n * global, as in Node.\r\n *\r\n * Properties installed:\r\n *\r\n * * Buffer\r\n * * process\r\n * * require (we monkey-patch it)\r\n *\r\n * This allows you to write code as if you were running inside Node.\r\n * @param {object} obj - The object to install things onto (e.g. window)\r\n */\r\nexport function install(obj: any) {\r\n obj.Buffer = Buffer;\r\n obj.process = process;\r\n var oldRequire = obj.require != null ? obj.require : null;\r\n // Monkey-patch require for Node-style code.\r\n obj.require = function(arg: string) {\r\n var rv = BFSRequire(arg);\r\n if (rv == null) {\r\n return oldRequire.apply(null, Array.prototype.slice.call(arguments, 0))\r\n } else {\r\n return rv;\r\n }\r\n };\r\n}\r\n\r\nexport function registerFileSystem(name: string, fs: file_system.FileSystemConstructor) {\r\n (<any> FileSystem)[name] = fs;\r\n}\r\n\r\nexport function BFSRequire(module: 'fs'): typeof fs;\r\nexport function BFSRequire(module: 'path'): typeof path;\r\nexport function BFSRequire(module: 'buffer'): typeof buffer;\r\nexport function BFSRequire(module: 'process'): typeof process;\r\nexport function BFSRequire(module: 'bfs_utils'): typeof BFSUtils;\r\nexport function BFSRequire(module: string): any;\r\nexport function BFSRequire(module: string): any {\r\n switch(module) {\r\n case 'fs':\r\n return fs;\r\n case 'path':\r\n return path;\r\n case 'buffer':\r\n // The 'buffer' module has 'Buffer' as a property.\r\n return buffer;\r\n case 'process':\r\n return process;\r\n case 'bfs_utils':\r\n return BFSUtils;\r\n default:\r\n return FileSystem[module];\r\n }\r\n}\r\n\r\n/**\r\n * You must call this function with a properly-instantiated root file system\r\n * before using any file system API method.\r\n * @param {BrowserFS.FileSystem} rootFS - The root filesystem to use for the\r\n * entire BrowserFS file system.\r\n */\r\nexport function initialize(rootfs: file_system.FileSystem) {\r\n return fs.initialize(rootfs);\r\n}\r\n\r\nexport {EmscriptenFS, FileSystem};\r\n",
"import {ApiError, ErrorCode} from './api_error';\r\nimport Stats from './node_fs_stats';\r\n\r\nexport interface File {\r\n /**\r\n * **Core**: Get the current file position.\r\n * @return [Number]\r\n */\r\n getPos(): number;\r\n /**\r\n * **Core**: Asynchronous `stat`.\r\n * @param [Function(BrowserFS.ApiError, BrowserFS.node.fs.Stats)] cb\r\n */\r\n stat(cb: (err: ApiError, stats?: Stats) => any): void;\r\n /**\r\n * **Core**: Synchronous `stat`.\r\n * @param [Function(BrowserFS.ApiError, BrowserFS.node.fs.Stats)] cb\r\n */\r\n statSync(): Stats;\r\n /**\r\n * **Core**: Asynchronous close.\r\n * @param [Function(BrowserFS.ApiError)] cb\r\n */\r\n close(cb: Function): void;\r\n /**\r\n * **Core**: Synchronous close.\r\n */\r\n closeSync(): void;\r\n /**\r\n * **Core**: Asynchronous truncate.\r\n * @param [Number] len\r\n * @param [Function(BrowserFS.ApiError)] cb\r\n */\r\n truncate(len: number, cb: Function): void;\r\n /**\r\n * **Core**: Synchronous truncate.\r\n * @param [Number] len\r\n */\r\n truncateSync(len: number): void;\r\n /**\r\n * **Core**: Asynchronous sync.\r\n * @param [Function(BrowserFS.ApiError)] cb\r\n */\r\n sync(cb: (e?: ApiError) => void): void;\r\n /**\r\n * **Core**: Synchronous sync.\r\n */\r\n syncSync(): void;\r\n /**\r\n * **Core**: Write buffer to the file.\r\n * Note that it is unsafe to use fs.write multiple times on the same file\r\n * without waiting for the callback.\r\n * @param [BrowserFS.node.Buffer] buffer Buffer containing the data to write to\r\n * the file.\r\n * @param [Number] offset Offset in the buffer to start reading data from.\r\n * @param [Number] length The amount of bytes to write to the file.\r\n * @param [Number] position Offset from the beginning of the file where this\r\n * data should be written. If position is null, the data will be written at\r\n * the current position.\r\n * @param [Function(BrowserFS.ApiError, Number, BrowserFS.node.Buffer)]\r\n * cb The number specifies the number of bytes written into the file.\r\n */\r\n write(buffer: NodeBuffer, offset: number, length: number, position: number, cb: (err: ApiError, written?: number, buffer?: NodeBuffer) => any): void;\r\n /**\r\n * **Core**: Write buffer to the file.\r\n * Note that it is unsafe to use fs.writeSync multiple times on the same file\r\n * without waiting for it to return.\r\n * @param [BrowserFS.node.Buffer] buffer Buffer containing the data to write to\r\n * the file.\r\n * @param [Number] offset Offset in the buffer to start reading data from.\r\n * @param [Number] length The amount of bytes to write to the file.\r\n * @param [Number] position Offset from the beginning of the file where this\r\n * data should be written. If position is null, the data will be written at\r\n * the current position.\r\n * @return [Number]\r\n */\r\n writeSync(buffer: NodeBuffer, offset: number, length: number, position: number): number;\r\n /**\r\n * **Core**: Read data from the file.\r\n * @param [BrowserFS.node.Buffer] buffer The buffer that the data will be\r\n * written to.\r\n * @param [Number] offset The offset within the buffer where writing will\r\n * start.\r\n * @param [Number] length An integer specifying the number of bytes to read.\r\n * @param [Number] position An integer specifying where to begin reading from\r\n * in the file. If position is null, data will be read from the current file\r\n * position.\r\n * @param [Function(BrowserFS.ApiError, Number, BrowserFS.node.Buffer)] cb The\r\n * number is the number of bytes read\r\n */\r\n read(buffer: NodeBuffer, offset: number, length: number, position: number, cb: (err: ApiError, bytesRead?: number, buffer?: NodeBuffer) => void): void;\r\n /**\r\n * **Core**: Read data from the file.\r\n * @param [BrowserFS.node.Buffer] buffer The buffer that the data will be\r\n * written to.\r\n * @param [Number] offset The offset within the buffer where writing will\r\n *
"import api_error = require('./api_error');\r\n\r\n/**\r\n * @class\r\n */\r\nexport enum ActionType {\r\n // Indicates that the code should not do anything.\r\n NOP = 0,\r\n // Indicates that the code should throw an exception.\r\n THROW_EXCEPTION = 1,\r\n // Indicates that the code should truncate the file, but only if it is a file.\r\n TRUNCATE_FILE = 2,\r\n // Indicates that the code should create the file.\r\n CREATE_FILE = 3\r\n}\r\n\r\n/**\r\n * Represents one of the following file flags. A convenience object.\r\n *\r\n * * `'r'` - Open file for reading. An exception occurs if the file does not exist.\r\n * * `'r+'` - Open file for reading and writing. An exception occurs if the file does not exist.\r\n * * `'rs'` - Open file for reading in synchronous mode. Instructs the filesystem to not cache writes.\r\n * * `'rs+'` - Open file for reading and writing, and opens the file in synchronous mode.\r\n * * `'w'` - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).\r\n * * `'wx'` - Like 'w' but opens the file in exclusive mode.\r\n * * `'w+'` - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).\r\n * * `'wx+'` - Like 'w+' but opens the file in exclusive mode.\r\n * * `'a'` - Open file for appending. The file is created if it does not exist.\r\n * * `'ax'` - Like 'a' but opens the file in exclusive mode.\r\n * * `'a+'` - Open file for reading and appending. The file is created if it does not exist.\r\n * * `'ax+'` - Like 'a+' but opens the file in exclusive mode.\r\n *\r\n * Exclusive mode ensures that the file path is newly created.\r\n * @class\r\n */\r\nexport class FileFlag {\r\n // Contains cached FileMode instances.\r\n private static flagCache: { [mode: string]: FileFlag } = {};\r\n // Array of valid mode strings.\r\n private static validFlagStrs = ['r', 'r+', 'rs', 'rs+', 'w', 'wx', 'w+', 'wx+', 'a', 'ax', 'a+', 'ax+'];\r\n\r\n /**\r\n * Get an object representing the given file mode.\r\n * @param [String] modeStr The string representing the mode\r\n * @return [BrowserFS.FileMode] The FileMode object representing the mode\r\n * @throw [BrowserFS.ApiError] when the mode string is invalid\r\n */\r\n public static getFileFlag(flagStr: string): FileFlag {\r\n // Check cache first.\r\n if (FileFlag.flagCache.hasOwnProperty(flagStr)) {\r\n return FileFlag.flagCache[flagStr];\r\n }\r\n return FileFlag.flagCache[flagStr] = new FileFlag(flagStr);\r\n }\r\n\r\n private flagStr: string;\r\n /**\r\n * This should never be called directly.\r\n * @param [String] modeStr The string representing the mode\r\n * @throw [BrowserFS.ApiError] when the mode string is invalid\r\n */\r\n constructor(flagStr: string) {\r\n this.flagStr = flagStr;\r\n if (FileFlag.validFlagStrs.indexOf(flagStr) < 0) {\r\n throw new api_error.ApiError(api_error.ErrorCode.EINVAL, \"Invalid flag: \" + flagStr);\r\n }\r\n }\r\n\r\n /**\r\n * Get the underlying flag string for this flag.\r\n */\r\n public getFlagString(): string {\r\n return this.flagStr;\r\n }\r\n\r\n /**\r\n * Returns true if the file is readable.\r\n * @return [Boolean]\r\n */\r\n public isReadable(): boolean {\r\n return this.flagStr.indexOf('r') !== -1 || this.flagStr.indexOf('+') !== -1;\r\n }\r\n /**\r\n * Returns true if the file is writeable.\r\n * @return [Boolean]\r\n */\r\n public isWriteable(): boolean {\r\n return this.flagStr.indexOf('w') !== -1 || this.flagStr.indexOf('a') !== -1 || this.flagStr.indexOf('+') !== -1;\r\n }\r\n /**\r\n * Returns true if the file mode should truncate.\r\n * @return [Boolean]\r\n */\r\n public isTruncating(): boolean {\r\n return this.flagStr.indexOf('w') !== -1;\r\n }\r\n /**\r\n * Returns true if the file is appendable.\r\n * @return [Boolean]\r\n */\r\n public isAppendable(): boolean {\r\n return this.flagStr.indexOf('a') !== -1;\r\n }\r\n /**\r\n * Returns true if the file is open in synchronous mode.\r\n * @ret
"import {ApiError, ErrorCode} from './api_error';\r\nimport Stats from './node_fs_stats';\r\nimport file = require('./file');\r\nimport {FileFlag, ActionType} from './file_flag';\r\nimport path = require('path');\r\n\r\n/**\r\n * Interface for a filesystem. **All** BrowserFS FileSystems should implement\r\n * this interface.\r\n *\r\n * Below, we denote each API method as **Core**, **Supplemental**, or\r\n * **Optional**.\r\n *\r\n * ### Core Methods\r\n *\r\n * **Core** API methods *need* to be implemented for basic read/write\r\n * functionality.\r\n *\r\n * Note that read-only FileSystems can choose to not implement core methods\r\n * that mutate files or metadata. The default implementation will pass a\r\n * NOT_SUPPORTED error to the callback.\r\n *\r\n * ### Supplemental Methods\r\n *\r\n * **Supplemental** API methods do not need to be implemented by a filesystem.\r\n * The default implementation implements all of the supplemental API methods in\r\n * terms of the **core** API methods.\r\n *\r\n * Note that a file system may choose to implement supplemental methods for\r\n * efficiency reasons.\r\n *\r\n * The code for some supplemental methods was adapted directly from NodeJS's\r\n * fs.js source code.\r\n *\r\n * ### Optional Methods\r\n *\r\n * **Optional** API methods provide functionality that may not be available in\r\n * all filesystems. For example, all symlink/hardlink-related API methods fall\r\n * under this category.\r\n *\r\n * The default implementation will pass a NOT_SUPPORTED error to the callback.\r\n *\r\n * ### Argument Assumptions\r\n *\r\n * You can assume the following about arguments passed to each API method:\r\n *\r\n * * **Every path is an absolute path.** Meaning, `.`, `..`, and other items\r\n * are resolved into an absolute form.\r\n * * **All arguments are present.** Any optional arguments at the Node API level\r\n * have been passed in with their default values.\r\n * * **The callback will reset the stack depth.** When your filesystem calls the\r\n * callback with the requested information, it will use `setImmediate` to\r\n * reset the JavaScript stack depth before calling the user-supplied callback.\r\n * @class FileSystem\r\n */\r\nexport interface FileSystem {\r\n /**\r\n * **Optional**: Returns the name of the file system.\r\n * @method FileSystem#getName\r\n * @return {string}\r\n */\r\n getName(): string;\r\n /**\r\n * **Optional**: Passes the following information to the callback:\r\n *\r\n * * Total number of bytes available on this file system.\r\n * * number of free bytes available on this file system.\r\n *\r\n * @method FileSystem#diskSpace\r\n * @todo This info is not available through the Node API. Perhaps we could do a\r\n * polyfill of diskspace.js, or add a new Node API function.\r\n * @param {string} path The path to the location that is being queried. Only\r\n * useful for filesystems that support mount points.\r\n * @param {FileSystem~diskSpaceCallback} cb\r\n */\r\n diskSpace(p: string, cb: (total: number, free: number) => any): void;\r\n /**\r\n * **Core**: Is this filesystem read-only?\r\n * @method FileSystem#isReadOnly\r\n * @return {boolean} True if this FileSystem is inherently read-only.\r\n */\r\n isReadOnly(): boolean;\r\n /**\r\n * **Core**: Does the filesystem support optional symlink/hardlink-related\r\n * commands?\r\n * @method FileSystem#supportsLinks\r\n * @return {boolean} True if the FileSystem supports the optional\r\n * symlink/hardlink-related commands.\r\n */\r\n supportsLinks(): boolean;\r\n /**\r\n * **Core**: Does the filesystem support optional property-related commands?\r\n * @method FileSystem#supportsProps\r\n * @return {boolean} True if the FileSystem supports the optional\r\n * property-related commands (permissions, utimes, etc).\r\n */\r\n supportsProps(): boolean;\r\n /**\r\n * **Core**: Does the filesystem support the optional synchronous interface?\r\n * @method FileSystem#supportsSynch\r\n * @return {boolean} True if the File
"/**\r\n * Exports the global scope variable.\r\n * In the main browser thread, this is \"window\".\r\n * In a WebWorker, this is \"self\".\r\n * In Node, this is \"global\".\r\n */\r\ndeclare var global: any;\r\nvar toExport: any;\r\nif (typeof(window) !== 'undefined') {\r\n toExport = window;\r\n} else if (typeof(self) !== 'undefined') {\r\n toExport = self;\r\n} else {\r\n toExport = global;\r\n}\r\nexport = toExport;",
"import {default as FS, FSModule} from './FS';\r\nimport {FileSystem} from './file_system';\r\nimport {ApiError} from './api_error';\r\nimport Stats from './node_fs_stats';\r\n\r\n// Manually export the individual public functions of fs.\r\n// Required because some code will invoke functions off of the module.\r\n// e.g.:\r\n// let writeFile = fs.writeFile;\r\n// writeFile(...)\r\n\r\nlet fs = new FS();\r\nlet _fsMock: FSModule = <any> {};\r\n\r\nlet FSProto = FS.prototype;\r\nObject.keys(FSProto).forEach((key) => {\r\n if (typeof fs[key] === 'function') {\r\n _fsMock[key] = function() {\r\n return (<Function> fs[key]).apply(fs, arguments);\r\n };\r\n } else {\r\n _fsMock[key] = fs[key];\r\n }\r\n});\r\n\r\n_fsMock['changeFSModule'] = function(newFs: FS): void {\r\n fs = newFs;\r\n}\r\n_fsMock['getFSModule'] = function(): FS {\r\n return fs;\r\n}\r\n_fsMock['_wrapCb'] = function(cb: Function, numArgs: number): Function {\r\n return fs._wrapCb(cb, numArgs);\r\n};\r\n_fsMock['FS'] = FS;\r\n\r\nexport = _fsMock;\r\n",
"import fs = require('fs');\r\nimport file = require('./file');\r\n\r\n/**\r\n * Indicates the type of the given file. Applied to 'mode'.\r\n */\r\nexport enum FileType {\r\n FILE = 0x8000,\r\n DIRECTORY = 0x4000,\r\n SYMLINK = 0xA000\r\n}\r\n\r\n/**\r\n * Emulation of Node's `fs.Stats` object.\r\n *\r\n * Attribute descriptions are from `man 2 stat'\r\n * @see http://nodejs.org/api/fs.html#fs_class_fs_stats\r\n * @see http://man7.org/linux/man-pages/man2/stat.2.html\r\n * @class\r\n */\r\nexport default class Stats implements fs.Stats {\r\n public blocks: number;\r\n /**\r\n * UNSUPPORTED ATTRIBUTES\r\n * I assume no one is going to need these details, although we could fake\r\n * appropriate values if need be.\r\n */\r\n // ID of device containing file\r\n public dev: number = 0;\r\n // inode number\r\n public ino: number = 0;\r\n // device ID (if special file)\r\n public rdev: number = 0;\r\n // number of hard links\r\n public nlink: number = 1;\r\n // blocksize for file system I/O\r\n public blksize: number = 4096;\r\n // @todo Maybe support these? atm, it's a one-user filesystem.\r\n // user ID of owner\r\n public uid: number = 0;\r\n // group ID of owner\r\n public gid: number = 0;\r\n // time file was created (currently unsupported)\r\n public birthtime: Date = new Date(0);\r\n // XXX: Some file systems stash data on stats objects.\r\n public file_data: NodeBuffer = null;\r\n\r\n /**\r\n * Provides information about a particular entry in the file system.\r\n * @param [Number] item_type type of the item (FILE, DIRECTORY, SYMLINK, or SOCKET)\r\n * @param [Number] size Size of the item in bytes. For directories/symlinks,\r\n * this is normally the size of the struct that represents the item.\r\n * @param [Number] mode Unix-style file mode (e.g. 0o644)\r\n * @param [Date?] atime time of last access\r\n * @param [Date?] mtime time of last modification\r\n * @param [Date?] ctime time of creation\r\n */\r\n constructor(\r\n item_type: FileType,\r\n public size: number,\r\n public mode?: number,\r\n public atime: Date = new Date(),\r\n public mtime: Date = new Date(),\r\n public ctime: Date = new Date()) {\r\n if (this.mode == null) {\r\n switch(item_type) {\r\n case FileType.FILE:\r\n this.mode = 0x1a4;\r\n break;\r\n case FileType.DIRECTORY:\r\n default:\r\n this.mode = 0x1ff;\r\n }\r\n }\r\n // number of 512B blocks allocated\r\n this.blocks = Math.ceil(size / 512);\r\n // Check if mode also includes top-most bits, which indicate the file's\r\n // type.\r\n if (this.mode < 0x1000) {\r\n this.mode |= item_type;\r\n }\r\n }\r\n\r\n public toBuffer(): Buffer {\r\n var buffer = new Buffer(32);\r\n buffer.writeUInt32LE(this.size, 0);\r\n buffer.writeUInt32LE(this.mode, 4);\r\n buffer.writeDoubleLE(this.atime.getTime(), 8);\r\n buffer.writeDoubleLE(this.mtime.getTime(), 16);\r\n buffer.writeDoubleLE(this.ctime.getTime(), 24);\r\n return buffer;\r\n }\r\n\r\n public static fromBuffer(buffer: Buffer): Stats {\r\n var size = buffer.readUInt32LE(0),\r\n mode = buffer.readUInt32LE(4),\r\n atime = buffer.readDoubleLE(8),\r\n mtime = buffer.readDoubleLE(16),\r\n ctime = buffer.readDoubleLE(24);\r\n\r\n return new Stats(mode & 0xF000, size, mode & 0xFFF, new Date(atime), new Date(mtime), new Date(ctime));\r\n }\r\n\r\n /**\r\n * **Nonstandard**: Clone the stats object.\r\n * @return [BrowserFS.node.fs.Stats]\r\n */\r\n public clone(): Stats {\r\n return new Stats(this.mode & 0xF000, this.size, this.mode & 0xFFF, this.atime, this.mtime, this.ctime);\r\n }\r\n\r\n /**\r\n * @return [Boolean] True if this item is a file.\r\n */\r\n public isFile(): boolean {\r\n return (this.mode & 0xF000) === FileType.FILE;\r\n }\r\n\r\n /**\r\n * @return [Boolean] True if this item is a directory.\r\n */\r\n public isDirectory(): boolean {\r\n return (this.mode & 0xF000) === FileType.DIRECTORY;\r\n }\r\n\r\
"/**\r\n * Grab bag of utility functions used across the code.\r\n */\r\nimport {FileSystem} from './file_system';\r\nimport path = require('path');\r\n\r\nconst SUPPORTS_TYPED_ARRAYS = typeof(ArrayBuffer) !== 'undefined';\r\n\r\n/**\r\n * Checks for any IE version, including IE11 which removed MSIE from the\r\n * userAgent string.\r\n */\r\nexport var isIE: boolean = typeof navigator !== \"undefined\" && (/(msie) ([\\w.]+)/.exec(navigator.userAgent.toLowerCase()) != null || navigator.userAgent.indexOf('Trident') !== -1);\r\n\r\n/**\r\n * Check if we're in a web worker.\r\n */\r\nexport var isWebWorker: boolean = typeof window === \"undefined\";\r\n\r\nexport interface Arrayish<T> {\r\n [idx: number]: T;\r\n length: number;\r\n}\r\n\r\n/**\r\n * Synchronous recursive makedir.\r\n */\r\nexport function mkdirpSync(p: string, mode: number, fs: FileSystem): void {\r\n if (!fs.existsSync(p)) {\r\n mkdirpSync(path.dirname(p), mode, fs);\r\n fs.mkdirSync(p, mode);\r\n }\r\n}\r\n\r\n/**\r\n * Converts a buffer into an array buffer. Attempts to do so in a\r\n * zero-copy manner, e.g. the array references the same memory.\r\n */\r\nexport function buffer2ArrayBuffer(buff: Buffer): ArrayBuffer {\r\n var u8 = buffer2Uint8array(buff),\r\n u8offset = u8.byteOffset,\r\n u8Len = u8.byteLength;\r\n if (u8offset === 0 && u8Len === u8.buffer.byteLength) {\r\n return u8.buffer;\r\n } else {\r\n return u8.buffer.slice(u8offset, u8offset + u8Len)\r\n }\r\n}\r\n\r\n/**\r\n * Converts a buffer into a Uint8Array. Attempts to do so in a\r\n * zero-copy manner, e.g. the array references the same memory.\r\n */\r\nexport function buffer2Uint8array(buff: Buffer): Uint8Array {\r\n if (buff['toUint8Array']) {\r\n return (<any> buff).toUint8Array();\r\n } else if (buff instanceof Uint8Array) {\r\n // Node v4.0 buffers *are* Uint8Arrays.\r\n return <any> buff;\r\n } else {\r\n // Uint8Arrays can be constructed from arrayish numbers.\r\n // At this point, we assume this isn't a BFS array.\r\n return new Uint8Array(buff);\r\n }\r\n}\r\n\r\n/**\r\n * Converts the given buffer into a Uint8 arrayish form. Attempts\r\n * to be zero-copy.\r\n *\r\n * Required for BrowserFS buffers, which do not support indexing.\r\n */\r\nexport function buffer2Arrayish(buff: Buffer): Arrayish<number> {\r\n if (typeof(buff[0]) === 'number') {\r\n return buff;\r\n } else if (SUPPORTS_TYPED_ARRAYS) {\r\n return buffer2Uint8array(buff);\r\n } else {\r\n return buff.toJSON().data;\r\n }\r\n}\r\n\r\n/**\r\n * Converts the given arrayish object into a Buffer. Attempts to\r\n * be zero-copy.\r\n */\r\nexport function arrayish2Buffer(arr: Arrayish<number>): Buffer {\r\n if (SUPPORTS_TYPED_ARRAYS && arr instanceof Uint8Array) {\r\n return uint8Array2Buffer(arr);\r\n } else if (arr instanceof Buffer) {\r\n return arr;\r\n } else {\r\n return new Buffer(<number[]> arr);\r\n }\r\n}\r\n\r\n/**\r\n * Converts the given Uint8Array into a Buffer. Attempts to be zero-copy.\r\n */\r\nexport function uint8Array2Buffer(u8: Uint8Array): Buffer {\r\n if (u8.byteOffset === 0 && u8.byteLength === u8.buffer.byteLength) {\r\n return arrayBuffer2Buffer(u8);\r\n } else {\r\n return new Buffer(u8);\r\n }\r\n}\r\n\r\n/**\r\n * Converts the given array buffer into a Buffer. Attempts to be\r\n * zero-copy.\r\n */\r\nexport function arrayBuffer2Buffer(ab: ArrayBuffer): Buffer {\r\n try {\r\n // Works in BFS and Node v4.2.\r\n return new Buffer(<any> ab);\r\n } catch (e) {\r\n // I believe this copies, but there's no avoiding it in Node < v4.2\r\n return new Buffer(new Uint8Array(ab));\r\n }\r\n}\r\n\r\n// Polyfill for Uint8Array.prototype.slice.\r\n// Safari and some other browsers do not define it.\r\nif (typeof(ArrayBuffer) !== 'undefined' && typeof(Uint8Array) !== 'undefined') {\r\n if (!Uint8Array.prototype['slice']) {\r\n Uint8Array.prototype.slice = function(start: number = 0, end: number = this.length): Uint8Array {\r\n let self: Uint8Array = this;\r\n if (start < 0) {\r\n start =
"/**\r\n * Defines an Emscripten file system object for use in the Emscripten virtual\r\n * filesystem. Allows you to use synchronous BrowserFS file systems from within\r\n * Emscripten.\r\n *\r\n * You can construct a BFSEmscriptenFS, mount it using its mount command,\r\n * and then mount it into Emscripten.\r\n *\r\n * Adapted from Emscripten's NodeFS:\r\n * https://raw.github.com/kripken/emscripten/master/src/library_nodefs.js\r\n */\r\nimport BrowserFS = require('../core/browserfs');\r\nimport FS from '../core/FS';\r\nimport fs = require('../core/node_fs');\r\nimport NodeStats from '../core/node_fs_stats';\r\nimport {uint8Array2Buffer} from '../core/util';\r\n\r\nexport interface Stats {\r\n dev: number;\r\n ino: number;\r\n mode: number;\r\n nlink: number;\r\n uid: number;\r\n gid: number;\r\n rdev: number;\r\n size: number;\r\n blksize: number;\r\n blocks: number;\r\n atime: Date;\r\n mtime: Date;\r\n ctime: Date;\r\n timestamp?: number;\r\n}\r\n\r\nexport interface EmscriptenFSNode {\r\n name: string;\r\n mode: number;\r\n parent: EmscriptenFSNode;\r\n mount: {opts: {root: string}};\r\n stream_ops: EmscriptenStreamOps;\r\n node_ops: EmscriptenNodeOps;\r\n}\r\n\r\nexport interface EmscriptenStream {\r\n node: EmscriptenFSNode;\r\n nfd: any;\r\n flags: string;\r\n position: number;\r\n}\r\n\r\nexport interface EmscriptenNodeOps {\r\n getattr(node: EmscriptenFSNode): Stats;\r\n setattr(node: EmscriptenFSNode, attr: Stats): void;\r\n lookup(parent: EmscriptenFSNode, name: string): EmscriptenFSNode;\r\n mknod(parent: EmscriptenFSNode, name: string, mode: number, dev: any): EmscriptenFSNode;\r\n rename(oldNode: EmscriptenFSNode, newDir: EmscriptenFSNode, newName: string): void;\r\n unlink(parent: EmscriptenFSNode, name: string): void;\r\n rmdir(parent: EmscriptenFSNode, name: string): void;\r\n readdir(node: EmscriptenFSNode): string[];\r\n symlink(parent: EmscriptenFSNode, newName: string, oldPath: string): void;\r\n readlink(node: EmscriptenFSNode): string;\r\n}\r\n\r\nexport interface EmscriptenStreamOps {\r\n open(stream: EmscriptenStream): void;\r\n close(stream: EmscriptenStream): void;\r\n read(stream: EmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number;\r\n write(stream: EmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number;\r\n llseek(stream: EmscriptenStream, offset: number, whence: number): number;\r\n}\r\n\r\nexport interface EmscriptenFS {\r\n mount(mount: {opts: {root: string}}): EmscriptenFSNode;\r\n createNode(parent: EmscriptenFSNode, name: string, mode: number, dev?: any): EmscriptenFSNode;\r\n getMode(path: string): number;\r\n realPath(node: EmscriptenFSNode): string;\r\n node_ops: EmscriptenNodeOps;\r\n stream_ops: EmscriptenStreamOps;\r\n}\r\n\r\nclass BFSEmscriptenStreamOps implements EmscriptenStreamOps {\r\n private FS: any;\r\n private PATH: any;\r\n private ERRNO_CODES: any;\r\n private nodefs: FS;\r\n\r\n constructor(private fs: BFSEmscriptenFS) {\r\n this.nodefs = fs.getNodeFS();\r\n this.FS = fs.getFS();\r\n this.PATH = fs.getPATH();\r\n this.ERRNO_CODES = fs.getERRNO_CODES();\r\n }\r\n\r\n public open(stream: EmscriptenStream): void {\r\n var path = this.fs.realPath(stream.node),\r\n FS = this.FS;\r\n try {\r\n if (FS.isFile(stream.node.mode)) {\r\n stream.nfd = this.nodefs.openSync(path, this.fs.flagsToPermissionString(stream.flags));\r\n }\r\n } catch (e) {\r\n if (!e.code) throw e;\r\n throw new FS.ErrnoError(this.ERRNO_CODES[e.code]);\r\n }\r\n }\r\n\r\n public close(stream: EmscriptenStream): void {\r\n var FS = this.FS;\r\n try {\r\n if (FS.isFile(stream.node.mode) && stream.nfd) {\r\n this.nodefs.closeSync(stream.nfd);\r\n }\r\n } catch (e) {\r\n if (!e.code) throw e;\r\n throw new FS.ErrnoError(this.ERRNO_CODES[e.code]);\r\n }\r\n }\r\n\r\n public read(stream: EmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: numbe
"import {default as Stats, FileType} from '../core/node_fs_stats';\r\nimport path = require('path');\r\n\r\n/**\r\n * A simple class for storing a filesystem index. Assumes that all paths passed\r\n * to it are *absolute* paths.\r\n *\r\n * Can be used as a partial or a full index, although care must be taken if used\r\n * for the former purpose, especially when directories are concerned.\r\n */\r\nexport class FileIndex<T> {\r\n // Maps directory paths to directory inodes, which contain files.\r\n private _index: {[path: string]: DirInode<T>}\r\n\r\n /**\r\n * Constructs a new FileIndex.\r\n */\r\n constructor() {\r\n // _index is a single-level key,value store that maps *directory* paths to\r\n // DirInodes. File information is only contained in DirInodes themselves.\r\n this._index = {};\r\n // Create the root directory.\r\n this.addPath('/', new DirInode());\r\n }\r\n\r\n /**\r\n * Split into a (directory path, item name) pair\r\n */\r\n private _split_path(p: string): string[] {\r\n var dirpath = path.dirname(p);\r\n var itemname = p.substr(dirpath.length + (dirpath === \"/\" ? 0 : 1));\r\n return [dirpath, itemname];\r\n }\r\n\r\n /**\r\n * Runs the given function over all files in the index.\r\n */\r\n public fileIterator<T>(cb: (file: T) => void): void {\r\n for (var path in this._index) {\r\n var dir = this._index[path];\r\n var files = dir.getListing();\r\n for (var i = 0; i < files.length; i++) {\r\n var item = dir.getItem(files[i]);\r\n if (isFileInode<T>(item)) {\r\n cb(item.getData());\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Adds the given absolute path to the index if it is not already in the index.\r\n * Creates any needed parent directories.\r\n * @param [String] path The path to add to the index.\r\n * @param [BrowserFS.FileInode | BrowserFS.DirInode] inode The inode for the\r\n * path to add.\r\n * @return [Boolean] 'True' if it was added or already exists, 'false' if there\r\n * was an issue adding it (e.g. item in path is a file, item exists but is\r\n * different).\r\n * @todo If adding fails and implicitly creates directories, we do not clean up\r\n * the new empty directories.\r\n */\r\n public addPath(path: string, inode: Inode): boolean {\r\n if (inode == null) {\r\n throw new Error('Inode must be specified');\r\n }\r\n if (path[0] !== '/') {\r\n throw new Error('Path must be absolute, got: ' + path);\r\n }\r\n\r\n // Check if it already exists.\r\n if (this._index.hasOwnProperty(path)) {\r\n return this._index[path] === inode;\r\n }\r\n\r\n var splitPath = this._split_path(path);\r\n var dirpath = splitPath[0];\r\n var itemname = splitPath[1];\r\n // Try to add to its parent directory first.\r\n var parent = this._index[dirpath];\r\n if (parent === undefined && path !== '/') {\r\n // Create parent.\r\n parent = new DirInode<T>();\r\n if (!this.addPath(dirpath, parent)) {\r\n return false;\r\n }\r\n }\r\n // Add myself to my parent.\r\n if (path !== '/') {\r\n if (!parent.addItem(itemname, inode)) {\r\n return false;\r\n }\r\n }\r\n // If I'm a directory, add myself to the index.\r\n if (isDirInode<T>(inode)) {\r\n this._index[path] = inode;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Adds the given absolute path to the index if it is not already in the index.\r\n * The path is added without special treatment (no joining of adjacent separators, etc).\r\n * Creates any needed parent directories.\r\n * @param [String] path The path to add to the index.\r\n * @param [BrowserFS.FileInode | BrowserFS.DirInode] inode The inode for the\r\n * path to add.\r\n * @return [Boolean] 'True' if it was added or already exists, 'false' if there\r\n * was an issue adding it (e.g. item in path is a file, item exists but is\r\n * different).\r\n * @todo If adding fails and implicitly creates directories, we do not clean
"import {default as Stats, FileType} from '../core/node_fs_stats';\r\n\r\n/**\r\n * Generic inode definition that can easily be serialized.\r\n */\r\nclass Inode {\r\n constructor(public id: string,\r\n public size: number,\r\n public mode: number,\r\n public atime: number,\r\n public mtime: number,\r\n public ctime: number) { }\r\n\r\n /**\r\n * Handy function that converts the Inode to a Node Stats object.\r\n */\r\n public toStats(): Stats {\r\n return new Stats(\r\n (this.mode & 0xF000) === FileType.DIRECTORY ? FileType.DIRECTORY : FileType.FILE,\r\n this.size, this.mode, new Date(this.atime), new Date(this.mtime), new Date(this.ctime));\r\n }\r\n\r\n /**\r\n * Get the size of this Inode, in bytes.\r\n */\r\n public getSize(): number {\r\n // ASSUMPTION: ID is ASCII (1 byte per char).\r\n return 30 + this.id.length;\r\n }\r\n\r\n /**\r\n * Writes the inode into the start of the buffer.\r\n */\r\n public toBuffer(buff: NodeBuffer = new Buffer(this.getSize())): NodeBuffer {\r\n buff.writeUInt32LE(this.size, 0);\r\n buff.writeUInt16LE(this.mode, 4);\r\n buff.writeDoubleLE(this.atime, 6);\r\n buff.writeDoubleLE(this.mtime, 14);\r\n buff.writeDoubleLE(this.ctime, 22);\r\n buff.write(this.id, 30, this.id.length, 'ascii');\r\n return buff;\r\n }\r\n\r\n /**\r\n * Updates the Inode using information from the stats object. Used by file\r\n * systems at sync time, e.g.:\r\n * - Program opens file and gets a File object.\r\n * - Program mutates file. File object is responsible for maintaining\r\n * metadata changes locally -- typically in a Stats object.\r\n * - Program closes file. File object's metadata changes are synced with the\r\n * file system.\r\n * @return True if any changes have occurred.\r\n */\r\n public update(stats: Stats): boolean {\r\n var hasChanged = false;\r\n if (this.size !== stats.size) {\r\n this.size = stats.size;\r\n hasChanged = true;\r\n }\r\n\r\n if (this.mode !== stats.mode) {\r\n this.mode = stats.mode;\r\n hasChanged = true;\r\n }\r\n\r\n var atimeMs = stats.atime.getTime();\r\n if (this.atime !== atimeMs) {\r\n this.atime = atimeMs;\r\n hasChanged = true;\r\n }\r\n\r\n var mtimeMs = stats.mtime.getTime();\r\n if (this.mtime !== mtimeMs) {\r\n this.mtime = mtimeMs;\r\n hasChanged = true;\r\n }\r\n\r\n var ctimeMs = stats.ctime.getTime();\r\n if (this.ctime !== ctimeMs) {\r\n this.ctime = ctimeMs;\r\n hasChanged = true;\r\n }\r\n\r\n return hasChanged;\r\n }\r\n\r\n /**\r\n * Converts the buffer into an Inode.\r\n */\r\n public static fromBuffer(buffer: NodeBuffer): Inode {\r\n if (buffer === undefined) {\r\n throw new Error(\"NO\");\r\n }\r\n return new Inode(buffer.toString('ascii', 30),\r\n buffer.readUInt32LE(0),\r\n buffer.readUInt16LE(4),\r\n buffer.readDoubleLE(6),\r\n buffer.readDoubleLE(14),\r\n buffer.readDoubleLE(22)\r\n );\r\n }\r\n\r\n // XXX: Copied from Stats. Should reconcile these two into something more\r\n // compact.\r\n\r\n /**\r\n * @return [Boolean] True if this item is a file.\r\n */\r\n public isFile(): boolean {\r\n return (this.mode & 0xF000) === FileType.FILE;\r\n }\r\n\r\n /**\r\n * @return [Boolean] True if this item is a directory.\r\n */\r\n public isDirectory(): boolean {\r\n return (this.mode & 0xF000) === FileType.DIRECTORY;\r\n }\r\n}\r\n\r\nexport = Inode;\r\n",
"import file_system = require('../core/file_system');\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport {default as Stats, FileType} from '../core/node_fs_stats';\r\nimport file = require('../core/file');\r\nimport file_flag = require('../core/file_flag');\r\nimport path = require('path');\r\nimport Inode = require('../generic/inode');\r\nimport preload_file = require('../generic/preload_file');\r\nvar ROOT_NODE_ID: string = \"/\";\r\n\r\n/**\r\n * Generates a random ID.\r\n */\r\nfunction GenerateRandomID(): string {\r\n // From http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\r\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\r\n var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);\r\n return v.toString(16);\r\n });\r\n}\r\n\r\n/**\r\n * Helper function. Checks if 'e' is defined. If so, it triggers the callback\r\n * with 'e' and returns false. Otherwise, returns true.\r\n */\r\nfunction noError(e: ApiError, cb: (e: ApiError) => void): boolean {\r\n if (e) {\r\n cb(e);\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\n/**\r\n * Helper function. Checks if 'e' is defined. If so, it aborts the transaction,\r\n * triggers the callback with 'e', and returns false. Otherwise, returns true.\r\n */\r\nfunction noErrorTx(e: ApiError, tx: AsyncKeyValueRWTransaction, cb: (e: ApiError) => void): boolean {\r\n if (e) {\r\n tx.abort(() => {\r\n cb(e);\r\n });\r\n return false;\r\n }\r\n return true;\r\n}\r\n\r\n/**\r\n * Represents a *synchronous* key-value store.\r\n */\r\nexport interface SyncKeyValueStore {\r\n /**\r\n * The name of the key-value store.\r\n */\r\n name(): string;\r\n /**\r\n * Empties the key-value store completely.\r\n */\r\n clear(): void;\r\n /**\r\n * Begins a new read-only transaction.\r\n */\r\n beginTransaction(type: \"readonly\"): SyncKeyValueROTransaction;\r\n /**\r\n * Begins a new read-write transaction.\r\n */\r\n beginTransaction(type: \"readwrite\"): SyncKeyValueRWTransaction;\r\n beginTransaction(type: string): SyncKeyValueROTransaction;\r\n}\r\n\r\n/**\r\n * A read-only transaction for a synchronous key value store.\r\n */\r\nexport interface SyncKeyValueROTransaction {\r\n /**\r\n * Retrieves the data at the given key. Throws an ApiError if an error occurs\r\n * or if the key does not exist.\r\n * @param key The key to look under for data.\r\n * @return The data stored under the key, or undefined if not present.\r\n */\r\n get(key: string): NodeBuffer;\r\n}\r\n\r\n/**\r\n * A read-write transaction for a synchronous key value store.\r\n */\r\nexport interface SyncKeyValueRWTransaction extends SyncKeyValueROTransaction {\r\n /**\r\n * Adds the data to the store under the given key.\r\n * @param key The key to add the data under.\r\n * @param data The data to add to the store.\r\n * @param overwrite If 'true', overwrite any existing data. If 'false',\r\n * avoids storing the data if the key exists.\r\n * @return True if storage succeeded, false otherwise.\r\n */\r\n put(key: string, data: NodeBuffer, overwrite: boolean): boolean;\r\n /**\r\n * Deletes the data at the given key.\r\n * @param key The key to delete from the store.\r\n */\r\n del(key: string): void;\r\n /**\r\n * Commits the transaction.\r\n */\r\n commit(): void;\r\n /**\r\n * Aborts and rolls back the transaction.\r\n */\r\n abort(): void;\r\n}\r\n\r\n/**\r\n * An interface for simple synchronous key-value stores that don't have special\r\n * support for transactions and such.\r\n */\r\nexport interface SimpleSyncStore {\r\n get(key: string): NodeBuffer;\r\n put(key: string, data: NodeBuffer, overwrite: boolean): boolean;\r\n del(key: string): void;\r\n}\r\n\r\n/**\r\n * A simple RW transaction for simple synchronous key-value stores.\r\n */\r\nexport class SimpleSyncRWTransaction implements SyncKeyValueRWTransaction {\r\n constructor(private store: SimpleSyncStore) { }\r\n /**\r\n * Stores data in the keys we modif
"import file = require('../core/file');\r\nimport file_system = require('../core/file_system');\r\nimport Stats from '../core/node_fs_stats';\r\nimport {FileFlag} from '../core/file_flag';\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\nimport fs = require('../core/node_fs');\r\n\r\n/**\r\n * An implementation of the File interface that operates on a file that is\r\n * completely in-memory. PreloadFiles are backed by a Buffer.\r\n *\r\n * This is also an abstract class, as it lacks an implementation of 'sync' and\r\n * 'close'. Each filesystem that wishes to use this file representation must\r\n * extend this class and implement those two methods.\r\n * @todo 'close' lever that disables functionality once closed.\r\n */\r\nexport class PreloadFile<T extends file_system.FileSystem> extends file.BaseFile {\r\n private _pos: number = 0;\r\n private _path: string;\r\n protected _fs: T;\r\n private _stat: Stats;\r\n private _flag: FileFlag;\r\n private _buffer: NodeBuffer;\r\n private _dirty: boolean = false;\r\n /**\r\n * Creates a file with the given path and, optionally, the given contents. Note\r\n * that, if contents is specified, it will be mutated by the file!\r\n * @param [BrowserFS.FileSystem] _fs The file system that created the file.\r\n * @param [String] _path\r\n * @param [BrowserFS.FileMode] _mode The mode that the file was opened using.\r\n * Dictates permissions and where the file pointer starts.\r\n * @param [BrowserFS.node.fs.Stats] _stat The stats object for the given file.\r\n * PreloadFile will mutate this object. Note that this object must contain\r\n * the appropriate mode that the file was opened as.\r\n * @param [BrowserFS.node.Buffer?] contents A buffer containing the entire\r\n * contents of the file. PreloadFile will mutate this buffer. If not\r\n * specified, we assume it is a new file.\r\n */\r\n constructor(_fs: T, _path: string, _flag: FileFlag, _stat: Stats, contents?: NodeBuffer) {\r\n super();\r\n this._fs = _fs;\r\n this._path = _path;\r\n this._flag = _flag;\r\n this._stat = _stat;\r\n if (contents != null) {\r\n this._buffer = contents;\r\n } else {\r\n // Empty buffer. It'll expand once we write stuff to it.\r\n this._buffer = new Buffer(0);\r\n }\r\n // Note: This invariant is *not* maintained once the file starts getting\r\n // modified.\r\n // Note: Only actually matters if file is readable, as writeable modes may\r\n // truncate/append to file.\r\n if (this._stat.size !== this._buffer.length && this._flag.isReadable()) {\r\n throw new Error(\"Invalid buffer: Buffer is \" + this._buffer.length + \" long, yet Stats object specifies that file is \" + this._stat.size + \" long.\");\r\n }\r\n }\r\n\r\n protected isDirty(): boolean {\r\n return this._dirty;\r\n }\r\n\r\n /**\r\n * Resets the dirty bit. Should only be called after a sync has completed successfully.\r\n */\r\n protected resetDirty() {\r\n this._dirty = false;\r\n }\r\n\r\n /**\r\n * NONSTANDARD: Get the underlying buffer for this file. !!DO NOT MUTATE!! Will mess up dirty tracking.\r\n */\r\n public getBuffer(): NodeBuffer {\r\n return this._buffer;\r\n }\r\n\r\n /**\r\n * NONSTANDARD: Get underlying stats for this file. !!DO NOT MUTATE!!\r\n */\r\n public getStats(): Stats {\r\n return this._stat;\r\n }\r\n\r\n public getFlag(): FileFlag {\r\n return this._flag;\r\n }\r\n\r\n /**\r\n * Get the path to this file.\r\n * @return [String] The path to the file.\r\n */\r\n public getPath(): string {\r\n return this._path;\r\n }\r\n\r\n /**\r\n * Get the current file position.\r\n *\r\n * We emulate the following bug mentioned in the Node documentation:\r\n * > On Linux, positional writes don't work when the file is opened in append\r\n * mode. The kernel ignores the position argument and always appends the data\r\n * to the end of the file.\r\n * @return [Number] The current file position.\r\n */\r\n public getPos(): number {\r\n
"/**\r\n * Contains utility methods for performing a variety of tasks with\r\n * XmlHttpRequest across browsers.\r\n */\r\n\r\nimport util = require('../core/util');\r\nimport {ApiError, ErrorCode} from '../core/api_error';\r\n\r\n// See core/polyfills for the VBScript definition of these functions.\r\ndeclare var IEBinaryToArray_ByteStr: (vbarr: any) => string;\r\ndeclare var IEBinaryToArray_ByteStr_Last: (vbarr: any) => string;\r\n// Converts 'responseBody' in IE into the equivalent 'responseText' that other\r\n// browsers would generate.\r\nfunction getIEByteArray(IEByteArray: any): number[] {\r\n var rawBytes = IEBinaryToArray_ByteStr(IEByteArray);\r\n var lastChr = IEBinaryToArray_ByteStr_Last(IEByteArray);\r\n var data_str = rawBytes.replace(/[\\s\\S]/g, function(match) {\r\n var v = match.charCodeAt(0)\r\n return String.fromCharCode(v&0xff, v>>8)\r\n }) + lastChr;\r\n var data_array = new Array(data_str.length);\r\n for (var i = 0; i < data_str.length; i++) {\r\n data_array[i] = data_str.charCodeAt(i);\r\n }\r\n return data_array;\r\n}\r\n\r\nfunction downloadFileIE(async: boolean, p: string, type: string, cb: (err: ApiError, data?: any) => void): void {\r\n switch(type) {\r\n case 'buffer':\r\n // Fallthrough\r\n case 'json':\r\n break;\r\n default:\r\n return cb(new ApiError(ErrorCode.EINVAL, \"Invalid download type: \" + type));\r\n }\r\n\r\n var req = new XMLHttpRequest();\r\n req.open('GET', p, async);\r\n req.setRequestHeader(\"Accept-Charset\", \"x-user-defined\");\r\n req.onreadystatechange = function(e) {\r\n var data_array;\r\n if (req.readyState === 4) {\r\n if (req.status === 200) {\r\n switch(type) {\r\n case 'buffer':\r\n data_array = getIEByteArray(req.responseBody);\r\n return cb(null, new Buffer(data_array));\r\n case 'json':\r\n return cb(null, JSON.parse(req.responseText));\r\n }\r\n } else {\r\n return cb(new ApiError(req.status, \"XHR error.\"));\r\n }\r\n }\r\n };\r\n req.send();\r\n}\r\n\r\nfunction asyncDownloadFileIE(p: string, type: 'buffer', cb: (err: ApiError, data?: NodeBuffer) => void): void;\r\nfunction asyncDownloadFileIE(p: string, type: 'json', cb: (err: ApiError, data?: any) => void): void;\r\nfunction asyncDownloadFileIE(p: string, type: string, cb: (err: ApiError, data?: any) => void): void;\r\nfunction asyncDownloadFileIE(p: string, type: string, cb: (err: ApiError, data?: any) => void): void {\r\n downloadFileIE(true, p, type, cb);\r\n}\r\n\r\nfunction syncDownloadFileIE(p: string, type: 'buffer'): NodeBuffer;\r\nfunction syncDownloadFileIE(p: string, type: 'json'): any;\r\nfunction syncDownloadFileIE(p: string, type: string): any;\r\nfunction syncDownloadFileIE(p: string, type: string): any {\r\n var rv;\r\n downloadFileIE(false, p, type, function(err: ApiError, data?: any) {\r\n if (err) throw err;\r\n rv = data;\r\n });\r\n return rv;\r\n}\r\n\r\nfunction asyncDownloadFileModern(p: string, type: 'buffer', cb: (err: ApiError, data?: NodeBuffer) => void): void;\r\nfunction asyncDownloadFileModern(p: string, type: 'json', cb: (err: ApiError, data?: any) => void): void;\r\nfunction asyncDownloadFileModern(p: string, type: string, cb: (err: ApiError, data?: any) => void): void;\r\nfunction asyncDownloadFileModern(p: string, type: string, cb: (err: ApiError, data?: any) => void): void {\r\n var req = new XMLHttpRequest();\r\n req.open('GET', p, true);\r\n var jsonSupported = true;\r\n switch(type) {\r\n case 'buffer':\r\n req.responseType = 'arraybuffer';\r\n break;\r\n case 'json':\r\n // Some browsers don't support the JSON response type.\r\n // They either reset responseType, or throw an exception.\r\n // @see https://github.com/Modernizr/Modernizr/blob/master/src/testXhrType.js\r\n try {\r\n req.responseType = 'json';\r\n jsonSupported = req.responseType === 'json';\r\n } catch (e) {\r\n jsonSupported = false;\r\n }\r\n break;\r\n default:\r\
"/**\r\n * BrowserFS's main entry point.\r\n * It installs all of the needed polyfills, and requires() the main module.\r\n */\r\nimport global = require('./core/global');\r\n\r\n// IE < 9 does not define this function.\r\nif (!Date.now) {\r\n Date.now = function now() {\r\n return new Date().getTime();\r\n };\r\n}\r\n\r\n// IE < 9 does not define this function.\r\nif(!Array.isArray) {\r\n Array.isArray = function (vArg): vArg is any[] {\r\n return Object.prototype.toString.call(vArg) === \"[object Array]\";\r\n };\r\n}\r\n\r\n// IE < 9 does not define this function.\r\n// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\r\nif (!Object.keys) {\r\n Object.keys = (function () {\r\n 'use strict';\r\n var hasOwnProperty = Object.prototype.hasOwnProperty,\r\n hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),\r\n dontEnums = [\r\n 'toString',\r\n 'toLocaleString',\r\n 'valueOf',\r\n 'hasOwnProperty',\r\n 'isPrototypeOf',\r\n 'propertyIsEnumerable',\r\n 'constructor'\r\n ],\r\n dontEnumsLength = dontEnums.length;\r\n\r\n return function (obj: any) {\r\n if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {\r\n throw new TypeError('Object.keys called on non-object');\r\n }\r\n\r\n var result: string[] = [], prop: string, i: number;\r\n\r\n for (prop in obj) {\r\n if (hasOwnProperty.call(obj, prop)) {\r\n result.push(prop);\r\n }\r\n }\r\n\r\n if (hasDontEnumBug) {\r\n for (i = 0; i < dontEnumsLength; i++) {\r\n if (hasOwnProperty.call(obj, dontEnums[i])) {\r\n result.push(dontEnums[i]);\r\n }\r\n }\r\n }\r\n return result;\r\n };\r\n }());\r\n}\r\n\r\n// IE substr does not support negative indices\r\nif ('ab'.substr(-1) !== 'b') {\r\n String.prototype.substr = function(substr: (start: number, length?: number) => string) {\r\n return function(start: number, length?: number): string {\r\n // did we get a negative start, calculate how much it is from the\r\n // beginning of the string\r\n if (start < 0) start = this.length + start;\r\n // call the original function\r\n return substr.call(this, start, length);\r\n }\r\n }(String.prototype.substr);\r\n}\r\n\r\n// IE < 9 does not support forEach\r\nif (!Array.prototype.forEach) {\r\n Array.prototype.forEach = function(fn: (value: string, index: number, array: string[]) => void, scope?: any): void {\r\n for (var i = 0; i < this.length; ++i) {\r\n if (i in this) {\r\n fn.call(scope, this[i], i, this);\r\n }\r\n }\r\n };\r\n}\r\n\r\n// IE < 9 does not support filter\r\n// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\r\nif (!Array.prototype.filter) {\r\n Array.prototype.filter = function(fun/*, thisArg*/) {\r\n 'use strict';\r\n\r\n if (this === void 0 || this === null) {\r\n throw new TypeError();\r\n }\r\n\r\n var t = Object(this);\r\n var len = t.length >>> 0;\r\n if (typeof fun !== 'function') {\r\n throw new TypeError();\r\n }\r\n\r\n var res = [];\r\n var thisArg = arguments.length >= 2 ? arguments[1] : void 0;\r\n for (var i = 0; i < len; i++) {\r\n if (i in t) {\r\n var val = t[i];\r\n\r\n // NOTE: Technically this should Object.defineProperty at\r\n // the next index, as push can be affected by\r\n // properties on Object.prototype and Array.prototype.\r\n // But that method's new, and collisions should be\r\n // rare, so use the more-compatible alternative.\r\n if (fun.call(thisArg, val, i, t)) {\r\n res.push(val);\r\n }\r\n }\r\n }\r\n\r\n return res;\r\n };\r\n}\r\n\r\n// Only IE10 has setImmediate.\r\n// @todo: Determine viability of switching to the 'proper' polyfill for this.\r\nif (typeof setImmedi
]
}